Path: redb-route/redb.Route/Expressions/ExpressionResolver.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/Expressions/ExpressionResolver.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Expressions.Ast; using SysExpression = System.Linq.Expressions.Expression; namespace redb.Route.Expressions; /// /// Expression resolver with compiled lambda caching for performance optimization. /// public static partial class ExpressionResolver { /// /// Delegate for expressions that resolve a value from an . /// private delegate object? ExpressionDelegate(IExchange exchange); // Caches for compiled expressions private static readonly ConcurrentDictionary> _templateCache = new(); private static readonly ConcurrentDictionary> _propertyResolverCache = new(); private static readonly ConcurrentDictionary> _valueExpressionCache = new(); /// /// Builds a cache key from an optional context ID and expression. /// When contextId is provided, returns "{contextId}:{expression}"; otherwise returns the expression as-is. /// private static string BuildCacheKey(string? contextId, string expression) => contextId is null ? expression : $"{contextId}:{expression}"; // Regular expressions for parsing private static readonly Regex UnaryOperationRegex = new(@"^([!+\-])(.+)$", RegexOptions.Compiled); // Regular expression for prefix increment/decrement private static readonly Regex PrefixIncrementDecrementRegex = new(@"^(\+\+|--)(.+)$", RegexOptions.Compiled); // Regular expression for postfix increment/decrement private static readonly Regex PostfixIncrementDecrementRegex = new(@"^(.+)(\+\+|--)$", RegexOptions.Compiled); // Regular expression for binary operations private static readonly Regex BinaryOperationRegex = new(@"^(.+?)\s*([+\-])\s*(.+)$", RegexOptions.Compiled); // Regular expression for high-priority binary operations private static readonly Regex BinaryHighPriorityOperationRegex = new(@"^(.+?)\s*([*/])\s*(.+)$", RegexOptions.Compiled); // Regular expression for jpath function — lazy quantifier to avoid greedy capture across nested calls private static readonly Regex JPathFunctionRegex = new(@"jpath\((.*?)\)", RegexOptions.Compiled); // Regular expression for xpath function — lazy quantifier to avoid greedy capture across nested calls private static readonly Regex XPathFunctionRegex = new(@"xpath\((.*?)\)", RegexOptions.Compiled); // Prefixes for property types private const string PROPERTY_PREFIX = "property."; private const string HEADER_PREFIX = "header."; private const string BODY_PREFIX = "body."; private const string EXCEPTION_PREFIX = "exception."; // Debug flag private static bool _debugEnabled = false; // Optional logger for expression resolution warnings private static ILogger? _logger; /// /// Sets an optional logger for expression resolution warnings (missing headers, properties, etc.). /// public static void SetLogger(ILogger? logger) => _logger = logger; /// /// Sets an optional logger factory; creates a logger named "redb.Route.Expressions". /// public static void SetLoggerFactory(ILoggerFactory? factory) => _logger = factory?.CreateLogger("redb.Route.Expressions"); /// /// Reports whether a string is a ${...} template rather than a bare expression. /// The two are different positions in the language: a template is interpolated into a string, /// while a bare expression is compiled and evaluated. /// /// The string to inspect. /// true when the string contains at least one ${...} placeholder. public static bool IsTemplate(string expression) { ArgumentNullException.ThrowIfNull(expression); return TemplateScanner.HasPlaceholder(expression); } // Counters for caching metrics private static long _templateHits = 0; private static long _templateMisses = 0; private static long _propertyResolverHits = 0; private static long _propertyResolverMisses = 0; private static long _valueExpressionHits = 0; private static long _valueExpressionMisses = 0; #region Debug methods /// /// Enables or disables debug output. /// /// true to enable debug logging; false to disable it. public static void SetDebugMode(bool enabled) { _debugEnabled = enabled; } /// /// Writes a debug message to the console when debug mode is enabled. /// /// The message to output. public static void DebugLog(string message) { if (_debugEnabled) { Console.WriteLine($"[ExpressionResolver DEBUG] {message}"); } } /// /// Prints an expression tree to the console with indentation reflecting nesting depth. /// /// The expression to visualize. /// Current indentation prefix. /// Whether this is the root expression. public static void DebugPrintExpressionTree(SysExpression expression, string indent = "", bool isRoot = true) { if (!_debugEnabled || expression == null) return; var nodeType = expression.NodeType.ToString(); var expressionType = expression.Type.Name; Console.WriteLine($"[ExprTree] {indent}{(isRoot ? "▶ " : "├─")} {nodeType} ({expressionType})"); // Increase indent for child nodes var childIndent = indent + (isRoot ? " " : "│ "); // Process child expressions depending on the type switch (expression) { case MethodCallExpression methodCall: Console.WriteLine($"[ExprTree] {childIndent}├─ Method: {methodCall.Method.Name}"); Console.WriteLine($"[ExprTree] {childIndent}├─ Object:"); if (methodCall.Object != null) DebugPrintExpressionTree(methodCall.Object, childIndent + "│ ", false); if (methodCall.Arguments.Count > 0) { Console.WriteLine($"[ExprTree] {childIndent}├─ Arguments ({methodCall.Arguments.Count}):"); for (int i = 0; i < methodCall.Arguments.Count; i++) { Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Arg[{i}]:"); DebugPrintExpressionTree(methodCall.Arguments[i], childIndent + "│ │ ", false); } } break; case BinaryExpression binary: Console.WriteLine($"[ExprTree] {childIndent}├─ Left:"); DebugPrintExpressionTree(binary.Left, childIndent + "│ ", false); Console.WriteLine($"[ExprTree] {childIndent}├─ Right:"); DebugPrintExpressionTree(binary.Right, childIndent + "│ ", false); break; case UnaryExpression unary: Console.WriteLine($"[ExprTree] {childIndent}├─ Operand:"); DebugPrintExpressionTree(unary.Operand, childIndent + "│ ", false); break; case System.Linq.Expressions.ConstantExpression constant: var value = constant.Value?.ToString() ?? "null"; Console.WriteLine($"[ExprTree] {childIndent}├─ Value: {value}"); break; case NewExpression newExpr: Console.WriteLine($"[ExprTree] {childIndent}├─ Constructor: {newExpr.Constructor.DeclaringType.Name}"); if (newExpr.Arguments.Count > 0) { Console.WriteLine($"[ExprTree] {childIndent}├─ Arguments ({newExpr.Arguments.Count}):"); for (int i = 0; i < newExpr.Arguments.Count; i++) { Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Arg[{i}]:"); DebugPrintExpressionTree(newExpr.Arguments[i], childIndent + "│ │ ", false); } } break; case LambdaExpression lambda: Console.WriteLine($"[ExprTree] {childIndent}├─ Parameters ({lambda.Parameters.Count}):"); for (int i = 0; i < lambda.Parameters.Count; i++) { var param = lambda.Parameters[i]; Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Param[{i}]: {param.Name} ({param.Type.Name})"); } Console.WriteLine($"[ExprTree] {childIndent}├─ Body:"); DebugPrintExpressionTree(lambda.Body, childIndent + "│ ", false); break; case MemberExpression member: Console.WriteLine($"[ExprTree] {childIndent}├─ Member: {member.Member.Name}"); Console.WriteLine($"[ExprTree] {childIndent}├─ Expression:"); DebugPrintExpressionTree(member.Expression, childIndent + "│ ", false); break; case BlockExpression block: Console.WriteLine($"[ExprTree] {childIndent}├─ Variables ({block.Variables.Count}):"); for (int i = 0; i < block.Variables.Count; i++) { var variable = block.Variables[i]; Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Var[{i}]: {variable.Name} ({variable.Type.Name})"); } Console.WriteLine($"[ExprTree] {childIndent}├─ Expressions ({block.Expressions.Count}):"); for (int i = 0; i < block.Expressions.Count; i++) { Console.WriteLine($"[ExprTree] {childIndent}│ ├─ Expr[{i}]:"); DebugPrintExpressionTree(block.Expressions[i], childIndent + "│ │ ", false); } break; case ConditionalExpression conditional: Console.WriteLine($"[ExprTree] {childIndent}├─ Test:"); DebugPrintExpressionTree(conditional.Test, childIndent + "│ ", false); Console.WriteLine($"[ExprTree] {childIndent}├─ IfTrue:"); DebugPrintExpressionTree(conditional.IfTrue, childIndent + "│ ", false); Console.WriteLine($"[ExprTree] {childIndent}├─ IfFalse:"); DebugPrintExpressionTree(conditional.IfFalse, childIndent + "│ ", false); break; } } #endregion #region Public methods for obtaining compiled delegates /// /// Gets a compiled delegate for processing a template string. /// /// The template string containing ${...} placeholders. /// Optional context identifier for cache isolation. When provided, the cache key is scoped to this context. /// A compiled function that resolves the template against an . public static Func GetCompiledTemplate(string template, string? contextId = null) { ArgumentException.ThrowIfNullOrEmpty(template, nameof(template)); var cacheKey = BuildCacheKey(contextId, template); DebugLog($"Requesting compiled template: '{template}' (key: '{cacheKey}')"); if (_templateCache.TryGetValue(cacheKey, out var cached)) { System.Threading.Interlocked.Increment(ref _templateHits); DebugLog($" Template found in cache: '{cacheKey}'"); return cached; } System.Threading.Interlocked.Increment(ref _templateMisses); DebugLog($" Compiling new template: '{template}'"); var compiled = _templateCache.GetOrAdd(cacheKey, _ => CompileTemplateString(template)); DebugLog($" Template compiled and added to cache: '{cacheKey}'"); return compiled; } /// /// Gets a compiled delegate for resolving properties. /// /// The property expression string. /// Optional context identifier for cache isolation. /// A compiled function that resolves a property value from a source object and expression. public static Func GetCompiledPropertyResolver(string expression, string? contextId = null) { ArgumentException.ThrowIfNullOrEmpty(expression, nameof(expression)); var cacheKey = BuildCacheKey(contextId, expression); DebugLog($"Requesting compiled property resolver: '{expression}' (key: '{cacheKey}')"); if (_propertyResolverCache.TryGetValue(cacheKey, out var cached)) { System.Threading.Interlocked.Increment(ref _propertyResolverHits); DebugLog($" Property resolver found in cache: '{cacheKey}'"); return cached; } System.Threading.Interlocked.Increment(ref _propertyResolverMisses); DebugLog($" Compiling new property resolver: '{expression}'"); var compiled = _propertyResolverCache.GetOrAdd(cacheKey, _ => CompilePropertyResolver(expression)); DebugLog($" Property resolver compiled and added to cache: '{cacheKey}'"); return compiled; } /// /// Gets a compiled delegate for obtaining values from an exchange. /// /// The value expression string. /// Optional context identifier for cache isolation. /// A compiled function that extracts a value from an . public static Func GetCompiledValueExpression(string expression, string? contextId = null) { ArgumentException.ThrowIfNullOrEmpty(expression, nameof(expression)); DebugLog($"Requesting compiled value expression: '{expression}'"); // For expressions with postfix operations, always use the AST parser if (PostfixIncrementDecrementRegex.IsMatch(expression) || PrefixIncrementDecrementRegex.IsMatch(expression)) { DebugLog($"Increment/decrement operation detected, using AST parser: '{expression}'"); return GetCompiledValueExpressionWithAst(expression, contextId); } var cacheKey = BuildCacheKey(contextId, expression); if (_valueExpressionCache.TryGetValue(cacheKey, out var cached)) { System.Threading.Interlocked.Increment(ref _valueExpressionHits); DebugLog($" Value expression found in cache: '{cacheKey}'"); return cached; } System.Threading.Interlocked.Increment(ref _valueExpressionMisses); DebugLog($" Compiling new value expression: '{expression}'"); var compiled = _valueExpressionCache.GetOrAdd(cacheKey, _ => CompileValueExpression(expression)); DebugLog($" Value expression compiled and added to cache: '{cacheKey}'"); return compiled; } /// /// Gets a compiled delegate for obtaining values using the AST parser. /// /// The value expression string. /// Optional context identifier for cache isolation. /// A compiled function that extracts a value from an via AST compilation. public static Func GetCompiledValueExpressionWithAst(string expression, string? contextId = null) { ArgumentException.ThrowIfNullOrEmpty(expression, nameof(expression)); var cacheKey = BuildCacheKey(contextId, "ast:" + expression); DebugLog($"Requesting compiled value expression with AST: '{expression}' (key: '{cacheKey}')"); if (_valueExpressionCache.TryGetValue(cacheKey, out var cached)) { System.Threading.Interlocked.Increment(ref _valueExpressionHits); DebugLog($" Value expression with AST found in cache: '{cacheKey}'"); return cached; } System.Threading.Interlocked.Increment(ref _valueExpressionMisses); DebugLog($" Compiling new value expression with AST: '{expression}'"); var compiled = _valueExpressionCache.GetOrAdd(cacheKey, _ => CompileExpressionWithAst(expression)); DebugLog($" Value expression with AST compiled and added to cache: '{cacheKey}'"); return compiled; } #endregion #region Core public methods /// /// Processes a template using a cached compiled delegate. /// /// The template string containing ${...} placeholders. /// The exchange to resolve values from. /// Optional context identifier for cache isolation. If null, uses exchange.RouteId when available. /// The resolved template string, or the original template if processing fails. public static string ProcessTemplate(string template, IExchange exchange, string? contextId = null) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); DebugLog($"Processing template: '{template}'"); if (string.IsNullOrEmpty(template)) return template; contextId ??= exchange.RouteId; var compiledTemplate = GetCompiledTemplate(template, contextId); try { // Apply the template to get the result var result = compiledTemplate(exchange); DebugLog($"Template processing result: '{result}'"); return result; } catch (Exception ex) when (ex is not ExpressionSandboxViolationException) { // Runtime resolution error — log and rethrow so ErrorHandler can handle it _logger?.LogWarning(ex, "Expression resolution error in template '{Template}'", template); DebugLog($"Template processing error: {ex.Message}"); throw; } } /// /// Resolves a template with type preservation for single expressions. /// If the template is a single ${expr} with no surrounding text, /// resolves via preserving the CLR type (Guid, DateTimeOffset, int, etc.). /// Composite templates (e.g. prefix-${x}-suffix) fall back to returning a string. /// public static object? ResolveTypedOrTemplate(string template, IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); if (string.IsNullOrEmpty(template)) return null; if (TryGetSinglePlaceholder(template, out var placeholder)) { // A whole-string placeholder keeps the CLR type of its value; the shared placeholder // pipeline replaced the private ResolveExpression ladder here on 2026-08-28. return GetCompiledPlaceholder(placeholder)(exchange); } return ProcessTemplate(template, exchange); } #endregion #region Cache management /// /// Clears all caches and resets metric counters. /// public static void ClearAllCaches() { _templateCache.Clear(); _propertyResolverCache.Clear(); _valueExpressionCache.Clear(); // Reset counters System.Threading.Interlocked.Exchange(ref _templateHits, 0); System.Threading.Interlocked.Exchange(ref _templateMisses, 0); System.Threading.Interlocked.Exchange(ref _propertyResolverHits, 0); System.Threading.Interlocked.Exchange(ref _propertyResolverMisses, 0); System.Threading.Interlocked.Exchange(ref _valueExpressionHits, 0); System.Threading.Interlocked.Exchange(ref _valueExpressionMisses, 0); } /// /// Clears the template cache. /// public static void ClearTemplateCache() { _templateCache.Clear(); } /// /// Clears the property resolver cache. /// public static void ClearPropertyResolverCache() { _propertyResolverCache.Clear(); } /// /// Clears the value expression cache. /// public static void ClearValueExpressionCache() { _valueExpressionCache.Clear(); } /// /// Clears all cache entries belonging to the specified context. /// Removes entries whose keys start with "{contextId}:" from all caches. /// /// The context identifier whose cached entries should be removed. public static void ClearCachesForContext(string contextId) { ArgumentException.ThrowIfNullOrEmpty(contextId, nameof(contextId)); var prefix = contextId + ":"; RemoveByPrefix(_templateCache, prefix); RemoveByPrefix(_propertyResolverCache, prefix); RemoveByPrefix(_valueExpressionCache, prefix); } private static void RemoveByPrefix(ConcurrentDictionary cache, string prefix) { foreach (var key in cache.Keys) { if (key.StartsWith(prefix, StringComparison.Ordinal)) cache.TryRemove(key, out _); } } /// /// Returns cache statistics with performance metrics. /// /// A record containing counts, hits, and misses for each cache. public static CacheStatistics GetCacheStatistics() { return new CacheStatistics { TemplateCount = _templateCache.Count, TemplateHits = System.Threading.Interlocked.Read(ref _templateHits), TemplateMisses = System.Threading.Interlocked.Read(ref _templateMisses), PropertyResolverCount = _propertyResolverCache.Count, PropertyResolverHits = System.Threading.Interlocked.Read(ref _propertyResolverHits), PropertyResolverMisses = System.Threading.Interlocked.Read(ref _propertyResolverMisses), ValueExpressionCount = _valueExpressionCache.Count, ValueExpressionHits = System.Threading.Interlocked.Read(ref _valueExpressionHits), ValueExpressionMisses = System.Threading.Interlocked.Read(ref _valueExpressionMisses) }; } #endregion #region Initialization /// /// Sets the console output encoding to UTF-8. /// public static void SetUtf8Output() { Console.OutputEncoding = System.Text.Encoding.UTF8; DebugLog("Console output encoding set to UTF-8"); } /// /// Initializes the environment with UTF-8 output and optional debug mode. /// /// true to enable debug logging; defaults to true. public static void Initialize(bool enableDebug = true) { SetDebugMode(enableDebug); SetUtf8Output(); DebugLog("ExpressionResolver initialized"); } #endregion } /// /// Cache statistics with performance metrics for each expression cache. /// public record CacheStatistics { /// Number of entries in the template cache. public int TemplateCount { get; init; } /// Number of template cache hits. public long TemplateHits { get; init; } /// Number of template cache misses. public long TemplateMisses { get; init; } /// Template cache hit rate as a percentage. public double TemplateHitRate => TemplateHits + TemplateMisses > 0 ? (double)TemplateHits / (TemplateHits + TemplateMisses) * 100 : 0; /// Number of entries in the property resolver cache. public int PropertyResolverCount { get; init; } /// Number of property resolver cache hits. public long PropertyResolverHits { get; init; } /// Number of property resolver cache misses. public long PropertyResolverMisses { get; init; } /// Property resolver cache hit rate as a percentage. public double PropertyResolverHitRate => PropertyResolverHits + PropertyResolverMisses > 0 ? (double)PropertyResolverHits / (PropertyResolverHits + PropertyResolverMisses) * 100 : 0; /// Number of entries in the value expression cache. public int ValueExpressionCount { get; init; } /// Number of value expression cache hits. public long ValueExpressionHits { get; init; } /// Number of value expression cache misses. public long ValueExpressionMisses { get; init; } /// Value expression cache hit rate as a percentage. public double ValueExpressionHitRate => ValueExpressionHits + ValueExpressionMisses > 0 ? (double)ValueExpressionHits / (ValueExpressionHits + ValueExpressionMisses) * 100 : 0; /// Total number of entries across all caches. public int TotalCount => TemplateCount + PropertyResolverCount + ValueExpressionCount; /// Total number of cache hits across all caches. public long TotalHits => TemplateHits + PropertyResolverHits + ValueExpressionHits; /// Total number of cache misses across all caches. public long TotalMisses => TemplateMisses + PropertyResolverMisses + ValueExpressionMisses; /// Overall cache hit rate as a percentage. public double TotalHitRate => TotalHits + TotalMisses > 0 ? (double)TotalHits / (TotalHits + TotalMisses) * 100 : 0; } /// /// Exception thrown when an expression fails to compile. /// public class ExpressionCompilationException : Exception { /// /// Initializes a new instance of the class with a message. /// /// The error message. public ExpressionCompilationException(string message) : base(message) { } /// /// Initializes a new instance of the class with a message and inner exception. /// /// The error message. /// The inner exception that caused this failure. public ExpressionCompilationException(string message, Exception innerException) : base(message, innerException) { } }