Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

### Features
- New `ReSettings.EnableAssemblyScanning` (default `true`). Set to `false` to opt out of scanning every AppDomain assembly for `[DynamicLinqType]`-marked types during rule expression parsing. When disabled, only the explicitly supplied `CustomTypes` (plus auto-registered input types) are available in expressions, avoiding the scan cost. Preserves existing behavior by default (#749).

### Fixes
- `AutoRegisterInputType` no longer replaces `ReSettings.CustomTypes` with a new array on every workflow registration when no new types were discovered. The unconditional reassignment broke the `ReferenceEquals` cache in `RuleExpressionParser`, forcing a fresh `CustomTypeProvider` (and assembly scan) each time workflows were added (#749).

## [6.0.1]

Stable release rolling up everything from `6.0.1-preview.1` through `6.0.1-preview.3` — no additional code changes beyond preview.3. See per-preview sections below for the full delta from `6.0.0`.
Expand Down
12 changes: 10 additions & 2 deletions src/RulesEngine/CustomTypeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,15 @@ namespace RulesEngine
public class CustomTypeProvider : DefaultDynamicLinqCustomTypeProvider
{
private readonly HashSet<Type> _types;
private readonly bool _enableAssemblyScanning;

public CustomTypeProvider(Type[] types) : base(ParsingConfig.Default)
public CustomTypeProvider(Type[] types) : this(types, true)
{
}

public CustomTypeProvider(Type[] types, bool enableAssemblyScanning) : base(ParsingConfig.Default)
{
_enableAssemblyScanning = enableAssemblyScanning;
_types = new HashSet<Type>(types ?? Array.Empty<Type>());

_types.Add(typeof(ExpressionUtils));
Expand Down Expand Up @@ -50,7 +56,9 @@ public override HashSet<Type> GetCustomTypes()
// The provider's type set is fixed after construction, so merge exactly once.
if (_mergedTypes == null)
{
var all = new HashSet<Type>(base.GetCustomTypes());
var all = _enableAssemblyScanning
? new HashSet<Type>(base.GetCustomTypes())
: new HashSet<Type>();
all.UnionWith(_types);
_mergedTypes = all;
}
Expand Down
4 changes: 2 additions & 2 deletions src/RulesEngine/ExpressionBuilders/RuleExpressionParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ private static string BuildSettingsFingerprint(ReSettings settings)
var customTypesKey = settings.CustomTypes == null
? "<null>"
: string.Join(",", settings.CustomTypes.Where(t => t != null).Select(t => t.AssemblyQualifiedName));
return $"cs={settings.IsExpressionCaseSensitive};fast={settings.UseFastExpressionCompiler};types={customTypesKey}";
return $"cs={settings.IsExpressionCaseSensitive};fast={settings.UseFastExpressionCompiler};scan={settings.EnableAssemblyScanning};types={customTypesKey}";
}

private string BuildCompileCacheKey(string expression, RuleParameter[] ruleParams, Type returnType)
Expand Down Expand Up @@ -98,7 +98,7 @@ private ParsingConfig GetParsingConfig()
if (config == null || !ReferenceEquals(_cachedParsingConfigCustomTypes, customTypes))
{
config = new ParsingConfig {
CustomTypeProvider = new CustomTypeProvider(customTypes),
CustomTypeProvider = new CustomTypeProvider(customTypes, _reSettings.EnableAssemblyScanning),
IsCaseSensitive = _reSettings.IsExpressionCaseSensitive
};
_cachedParsingConfigCustomTypes = customTypes;
Expand Down
10 changes: 10 additions & 0 deletions src/RulesEngine/Models/ReSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ internal ReSettings(ReSettings reSettings)
CacheConfig = reSettings.CacheConfig;
IsExpressionCaseSensitive = reSettings.IsExpressionCaseSensitive;
AutoRegisterInputType = reSettings.AutoRegisterInputType;
EnableAssemblyScanning = reSettings.EnableAssemblyScanning;
UseFastExpressionCompiler = reSettings.UseFastExpressionCompiler;
EnableExceptionAsErrorMessageForRuleExpressionParsing = reSettings.EnableExceptionAsErrorMessageForRuleExpressionParsing;
AutoExecuteActions = reSettings.AutoExecuteActions;
Expand Down Expand Up @@ -78,6 +79,15 @@ internal ReSettings(ReSettings reSettings)
/// </summary>
public bool AutoRegisterInputType { get; set; } = true;

/// <summary>
/// When true (default), the CustomTypeProvider scans all assemblies loaded in the
/// AppDomain for types decorated with [DynamicLinqType] so they can be used in rule
/// expressions. Set to false to opt out of this scan entirely (only the explicitly
/// supplied CustomTypes and input types are registered), which avoids the scanning
/// cost on workflow registration. See #749.
/// </summary>
public bool EnableAssemblyScanning { get; set; } = true;

/// <summary>
/// Sets the mode for Nested rule execution, Default: All
/// </summary>
Expand Down
10 changes: 9 additions & 1 deletion src/RulesEngine/RulesEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -378,13 +378,21 @@ private bool RegisterRule(string workflowName, params RuleParameter[] ruleParams
if (_reSettings.AutoRegisterInputType)
{
var collector = new HashSet<Type>(_reSettings.CustomTypes.Safe());
var originalCount = collector.Count;

foreach (var rp in ruleParams)
{
CollectAllElementTypes(rp.Type, collector);
}

_reSettings.CustomTypes = collector.ToArray();
// Only swap the array when new types were actually discovered. Reassigning it
// unconditionally replaces the reference on every registration, which breaks the
// ReferenceEquals-based cache in RuleExpressionParser and forces a fresh assembly
// scan each time workflows are added. See #749.
if (collector.Count != originalCount)
{
_reSettings.CustomTypes = collector.ToArray();
}
}

// Compile global params ONCE per workflow registration. The resulting delegate is
Expand Down
130 changes: 130 additions & 0 deletions test/RulesEngine.UnitTest/Issue749Test.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using RulesEngine.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Dynamic.Core.CustomTypeProviders;
using System.Threading.Tasks;
using Xunit;

namespace RulesEngine.UnitTest
{
[DynamicLinqType]
[ExcludeFromCodeCoverage]
public static class Issue749ScannedType
{
public static bool IsSpecial(int value) => value == 42;
}

[Trait("Category", "Unit")]
[ExcludeFromCodeCoverage]
public class Issue749Test
{
[Fact]
public void CustomTypeProvider_ScanningEnabled_IncludesDynamicLinqTypeMarkedType()
{
var provider = new CustomTypeProvider(Array.Empty<Type>(), enableAssemblyScanning: true);

var allTypes = provider.GetCustomTypes();

Assert.Contains(typeof(Issue749ScannedType), allTypes);
}

[Fact]
public void CustomTypeProvider_ScanningDisabled_ExcludesDynamicLinqTypeMarkedType()
{
var provider = new CustomTypeProvider(Array.Empty<Type>(), enableAssemblyScanning: false);

var allTypes = provider.GetCustomTypes();

Assert.DoesNotContain(typeof(Issue749ScannedType), allTypes);
}

[Fact]
public void CustomTypeProvider_ScanningDisabled_StillIncludesExplicitAndInputTypes()
{
var provider = new CustomTypeProvider(new[] { typeof(List<string>) }, enableAssemblyScanning: false);

var allTypes = provider.GetCustomTypes();

Assert.Contains(typeof(List<string>), allTypes);
Assert.Contains(typeof(System.Linq.Enumerable), allTypes);
Assert.Contains(typeof(System.Collections.IEnumerable), allTypes);
}

[Fact]
public async Task ScanningDisabled_BasicRuleAndInputMethods_StillWork()
{
var workflow = new Workflow
{
WorkflowName = "wf",
Rules = new[] {
new Rule {
RuleName = "R",
Expression = "input1.Value.ToString() == \"42\""
}
}
};

var reSettings = new ReSettings { EnableAssemblyScanning = false };
var engine = new RulesEngine(new[] { workflow }, reSettings);

var result = await engine.ExecuteAllRulesAsync("wf",
new RuleParameter("input1", new { Value = 42 }));

Assert.True(result[0].IsSuccess);
}

[Fact]
public async Task ScanningEnabled_DynamicLinqTypeStaticMethod_Resolves()
{
var workflow = new Workflow
{
WorkflowName = "wf",
Rules = new[] {
new Rule {
RuleName = "R",
Expression = "Issue749ScannedType.IsSpecial(input1.Value)"
}
}
};

var reSettings = new ReSettings { EnableAssemblyScanning = true };
var engine = new RulesEngine(new[] { workflow }, reSettings);

var result = await engine.ExecuteAllRulesAsync("wf",
new RuleParameter("input1", new { Value = 42 }));

Assert.True(result[0].IsSuccess);
}

[Fact]
public async Task ScanningDisabled_TypeRegisteredExplicitly_StaticMethodResolves()
{
var workflow = new Workflow
{
WorkflowName = "wf",
Rules = new[] {
new Rule {
RuleName = "R",
Expression = "Issue749ScannedType.IsSpecial(input1.Value)"
}
}
};

var reSettings = new ReSettings {
EnableAssemblyScanning = false,
CustomTypes = new[] { typeof(Issue749ScannedType) }
};
var engine = new RulesEngine(new[] { workflow }, reSettings);

var result = await engine.ExecuteAllRulesAsync("wf",
new RuleParameter("input1", new { Value = 42 }));

Assert.True(result[0].IsSuccess);
}
}
}
Loading