From 63aba56cc1351bc5d9b83bcd27ece5ce34b7424f Mon Sep 17 00:00:00 2001 From: Paul DeVito Date: Fri, 20 Nov 2026 08:35:57 +0200 Subject: [PATCH] refactor(filter): hold the state of one parse in a FilterParseScope ParseFilter kept its per-parse state in five thread-static fields in two files. It saved, set, and restored each field by hand. The state now lives in one FilterParseScope object. A nested parse on the same thread gets its own scope, and the outer scope comes back when the nested parse ends. The public API and the parse results do not change. A new test pins that a parse inside a parse keeps the settings of the outer parse. --- QueryKit.UnitTests/NestedParseTests.cs | 64 ++++++++++++++++++++++++++ QueryKit/FilterParseScope.cs | 32 +++++++++++++ QueryKit/FilterParser.cs | 51 ++++++-------------- QueryKit/FilterValue.cs | 14 ++---- 4 files changed, 113 insertions(+), 48 deletions(-) create mode 100644 QueryKit.UnitTests/NestedParseTests.cs create mode 100644 QueryKit/FilterParseScope.cs diff --git a/QueryKit.UnitTests/NestedParseTests.cs b/QueryKit.UnitTests/NestedParseTests.cs new file mode 100644 index 0000000..f298791 --- /dev/null +++ b/QueryKit.UnitTests/NestedParseTests.cs @@ -0,0 +1,64 @@ +namespace QueryKit.UnitTests; + +using System.Linq.Expressions; +using Exceptions; +using FluentAssertions; +using QueryKit.Configuration; +using WebApiTestProject.Entities; + +public class NestedParseTests +{ + [Fact] + public void a_parse_inside_a_parse_keeps_the_settings_of_the_outer_parse() + { + var config = new QueryKitConfiguration(settings => + { + settings.ParameterizeFilterValues = true; + settings.MaxNestingDepth = 1; + settings.Property(x => x.Id).HasConversion(); + }); + + IdThatParsesOnConstruction.NestedParses = 0; + var filter = FilterParser.ParseFilter("""Id ^^ ["1"] && (Name == "one")""", config); + + IdThatParsesOnConstruction.NestedParses.Should().BeGreaterThan(0); + var holders = new MemberCollector(); + holders.Visit(filter); + holders.HolderTypes.Should().Contain(typeof(FilterValue)); + + var tooDeep = () => FilterParser.ParseFilter("""Id ^^ ["1"] && ((Name == "one"))""", config); + tooDeep.Should().Throw(); + } + + private class Row + { + public IdThatParsesOnConstruction Id { get; set; } = null!; + public string Name { get; set; } = null!; + } + + private class IdThatParsesOnConstruction + { + public IdThatParsesOnConstruction(string value) + { + Value = value; + FilterParser.ParseFilter("((Age > 1))"); + NestedParses++; + } + + public static int NestedParses { get; set; } + + public string Value { get; } + } + + private sealed class MemberCollector : ExpressionVisitor + { + public List HolderTypes { get; } = new(); + + protected override Expression VisitMember(MemberExpression node) + { + if (node.Expression is ConstantExpression constant) + HolderTypes.Add(constant.Type); + return base.VisitMember(node); + } + } +} diff --git a/QueryKit/FilterParseScope.cs b/QueryKit/FilterParseScope.cs new file mode 100644 index 0000000..051b68c --- /dev/null +++ b/QueryKit/FilterParseScope.cs @@ -0,0 +1,32 @@ +namespace QueryKit; + +internal sealed class FilterParseScope : IDisposable +{ + // Parsing is synchronous, so the thread that parses owns the scope. An async parse would need AsyncLocal. + [ThreadStatic] private static FilterParseScope? _current; + + private readonly FilterParseScope? _previous; + + private FilterParseScope(bool parameterize, int maxNestingDepth) + { + Parameterize = parameterize; + MaxNestingDepth = maxNestingDepth; + _previous = _current; + _current = this; + } + + internal static FilterParseScope? Current => _current; + + internal static FilterParseScope Begin(bool parameterize, int maxNestingDepth) => new(parameterize, maxNestingDepth); + + internal bool Parameterize { get; } + + internal int MaxNestingDepth { get; } + + internal int NestingDepth { get; set; } + + internal bool QueryNameHidUnknownIdentifier { get; set; } + internal bool RetryingForLegacyException { get; set; } + + public void Dispose() => _current = _previous; +} diff --git a/QueryKit/FilterParser.cs b/QueryKit/FilterParser.cs index 503b2de..09e49a5 100644 --- a/QueryKit/FilterParser.cs +++ b/QueryKit/FilterParser.cs @@ -25,28 +25,21 @@ public static Expression> ParseFilter(string input, IQueryKitCo var parameter = Expression.Parameter(typeof(T), "x"); Expression expr; - var parameterizeBefore = FilterValue.Parameterize; - FilterValue.Parameterize = config is IQueryKitFilterBehavior { ParameterizeFilterValues: true }; - var maxNestingDepthBefore = _maxNestingDepth; - var nestingDepthBefore = _nestingDepth; - var queryNameOverUnknownBefore = _queryNameOverUnknown; - var queryNameFallbackOffBefore = _queryNameFallbackOff; - _maxNestingDepth = (config as IQueryKitParseLimits)?.MaxNestingDepth ?? QueryKitSettings.DefaultMaxNestingDepth; - _nestingDepth = 0; - _queryNameOverUnknown = false; - _queryNameFallbackOff = false; + using var scope = FilterParseScope.Begin( + config is IQueryKitFilterBehavior { ParameterizeFilterValues: true }, + (config as IQueryKitParseLimits)?.MaxNestingDepth ?? QueryKitSettings.DefaultMaxNestingDepth); try { try { expr = ExprParser(parameter, config).End().Parse(input); } - catch (Exception) when (_queryNameOverUnknown) + catch (Exception) when (scope.QueryNameHidUnknownIdentifier) { // v1.14.2 threw UnknownFilterPropertyException where a query name now reads an unknown identifier. // A filter that fails now also failed in v1.14.2, so parse it again without the query names to get the v1.14.2 exception. - _queryNameFallbackOff = true; - _nestingDepth = 0; + scope.RetryingForLegacyException = true; + scope.NestingDepth = 0; expr = ExprParser(parameter, config).End().Parse(input); } @@ -74,14 +67,6 @@ public static Expression> ParseFilter(string input, IQueryKitCo { throw new ParsingException(e); } - finally - { - FilterValue.Parameterize = parameterizeBefore; - _maxNestingDepth = maxNestingDepthBefore; - _nestingDepth = nestingDepthBefore; - _queryNameOverUnknown = queryNameOverUnknownBefore; - _queryNameFallbackOff = queryNameFallbackOffBefore; - } return Expression.Lambda>(expr, parameter); } @@ -107,16 +92,6 @@ private static void EnsureWithinInputLength(string input, IQueryKitConfiguration } } - // The nesting depth limit of the parse on this thread, and the number of parenthesized groups - // that the parser is in now. Parsing is synchronous, so the values belong to the thread that parses. - [ThreadStatic] private static int _maxNestingDepth; - [ThreadStatic] private static int _nestingDepth; - - // Set when a derived property or custom operation query name reads text where v1.14.2 read an unknown identifier. - // When the fallback is off, the parser throws for the unknown identifier like v1.14.2. - [ThreadStatic] private static bool _queryNameOverUnknown; - [ThreadStatic] private static bool _queryNameFallbackOff; - // Parses '(' inner ')' and counts the group against MaxNestingDepth. The grammar does the count, // so a '(' or ')' inside a quoted value cannot change it. The parser recurses once for each group, // so the limit also limits the depth of the call stack. @@ -124,19 +99,20 @@ private static Parser Grouped(Parser inner) { Parser counted = input => { + var scope = FilterParseScope.Current!; try { - _nestingDepth++; - if (_nestingDepth > _maxNestingDepth) + scope.NestingDepth++; + if (scope.NestingDepth > scope.MaxNestingDepth) { - throw new QueryKitNestingDepthExceededException(_nestingDepth, _maxNestingDepth); + throw new QueryKitNestingDepthExceededException(scope.NestingDepth, scope.MaxNestingDepth); } return inner(input); } finally { - _nestingDepth--; + scope.NestingDepth--; } }; @@ -1217,8 +1193,9 @@ private static Parser CreateLeftExprParser(Type entityType, I var identifierReference = identifier.WasSuccessful ? PropertyResolver.Resolve(entityType, identifier.Value, config) : null; if (identifierReference?.Kind == PropertyReferenceKind.Unknown && config?.AllowUnknownProperties != true) { - _queryNameOverUnknown = true; - if (_queryNameFallbackOff) + var scope = FilterParseScope.Current!; + scope.QueryNameHidUnknownIdentifier = true; + if (scope.RetryingForLegacyException) { throw new UnknownFilterPropertyException(identifierReference.UnknownSegment!); } diff --git a/QueryKit/FilterValue.cs b/QueryKit/FilterValue.cs index 5916323..6ca3911 100644 --- a/QueryKit/FilterValue.cs +++ b/QueryKit/FilterValue.cs @@ -17,21 +17,13 @@ public FilterValue(T value) internal static class FilterValue { - // The parser sets this for one parse when ParameterizeFilterValues is on. Parsing is synchronous, - // so the value belongs to the thread that parses. - [ThreadStatic] private static bool _parameterize; - - public static bool Parameterize - { - get => _parameterize; - set => _parameterize = value; - } + private static bool Parameterize => FilterParseScope.Current?.Parameterize == true; // Returns a field read on a FilterValue holder when parameters are on. Otherwise returns the // same literal expression as v1.14.2. public static Expression Create(object? value, Type type) { - if (!_parameterize) + if (!Parameterize) { return Literal(value, type); } @@ -46,7 +38,7 @@ public static Expression Create(object? value, Type type) public static Expression CreateList(object list, Type elementType) { var listType = typeof(List<>).MakeGenericType(elementType); - if (_parameterize) + if (Parameterize) { return Create(list, listType); }