-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathAspNetRuleProvider.cs
79 lines (69 loc) · 3 KB
/
AspNetRuleProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using aggregator.Engine;
using aggregator.Engine.Language;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace aggregator
{
internal class AspNetRuleProvider : IRuleProvider
{
private const string SCRIPT_RULE_DIRECTORY = "rules";
private const string SCRIPT_RULE_NAME_PATTERN = ".rule";
private readonly IAggregatorLogger _logger;
private readonly IConfiguration _configuration;
public AspNetRuleProvider(ForwarderLogger logger, IConfiguration configuration)
{
this._logger = logger;
this._configuration = configuration;
}
/// <inheritdoc />
public async Task<IRule> GetRule(string name)
{
var ruleFilePath = GetRuleFilePath(name);
var (preprocessedRule, _) = await RuleFileParser.ReadFile(ruleFilePath);
return new ScriptedRuleWrapper(name, preprocessedRule);
}
private string GetRuleFilePath(string ruleName)
{
bool IsRequestedRule(IFileInfo info)
{
return string.Equals(ruleName, Path.GetFileNameWithoutExtension(info.Name), StringComparison.OrdinalIgnoreCase);
}
string ruleFilePath = null;
string rulesPath = _configuration.GetValue<string>("Aggregator_RulesPath");
if (string.IsNullOrEmpty(rulesPath))
{
rulesPath = _configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
_logger.WriteVerbose($"Searching '{ruleName}' in {rulesPath}");
var provider = new PhysicalFileProvider(rulesPath);
var contents = provider.GetDirectoryContents(SCRIPT_RULE_DIRECTORY).Where(f => f.Name.EndsWith(SCRIPT_RULE_NAME_PATTERN));
ruleFilePath = contents.First(IsRequestedRule)?.PhysicalPath;
}
else
{
_logger.WriteVerbose($"Searching '{ruleName}' in {rulesPath}");
string ruleFullPath = Path.Combine(rulesPath, $"{ruleName}{SCRIPT_RULE_NAME_PATTERN}");
ruleFilePath = File.Exists(ruleFullPath) ? ruleFullPath : null;
}
if (ruleFilePath == null)
{
var errorMsg = $"Rule code file '{ruleName}{SCRIPT_RULE_NAME_PATTERN}' not found at expected Path {rulesPath}";
var ruleNotFound = new EventTelemetry()
{
Name = "Rule code file not found",
};
ruleNotFound.Properties["rule"] = ruleName;
Telemetry.TrackEvent(ruleNotFound);
_logger.WriteError(errorMsg);
throw new FileNotFoundException(errorMsg);
}
_logger.WriteVerbose($"Rule code found at {ruleFilePath}");
return ruleFilePath;
}
}
}