-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathBasePlugin.cs
More file actions
186 lines (158 loc) · 7.17 KB
/
BasePlugin.cs
File metadata and controls
186 lines (158 loc) · 7.17 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.CommandLine;
using System.Globalization;
using System.Text.Json;
using DevProxy.Abstractions.Proxy;
using DevProxy.Abstractions.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DevProxy.Abstractions.Plugins;
public abstract class BasePlugin(
ILogger logger,
ISet<UrlToWatch> urlsToWatch) : IPlugin
{
/// <inheritdoc/>
public bool Enabled { get; protected set; } = true;
/// <summary>
/// List of URLs to watch for this plugin.
/// </summary>
public ISet<UrlToWatch> UrlsToWatch { get; } = urlsToWatch;
/// <inheritdoc/>
public abstract string Name { get; }
protected ILogger Logger { get; } = logger;
/// <inheritdoc/>
public virtual Func<RequestArguments, CancellationToken, Task<PluginResponse>>? OnRequestAsync { get; }
/// <inheritdoc/>
public virtual Func<RequestArguments, CancellationToken, Task>? ProvideRequestGuidanceAsync { get; }
/// <inheritdoc/>
public virtual Func<ResponseArguments, CancellationToken, Task<PluginResponse?>>? OnResponseAsync { get; }
/// <inheritdoc/>
public virtual Func<ResponseArguments, CancellationToken, Task>? ProvideResponseGuidanceAsync { get; }
/// <inheritdoc/>
public virtual Func<RequestLogArgs, CancellationToken, Task>? HandleRequestLogAsync { get; }
/// <inheritdoc/>
public virtual Func<RecordingArgs, CancellationToken, Task>? HandleRecordingStopAsync { get; }
/// <inheritdoc/>
public virtual Option[] GetOptions() => [];
/// <inheritdoc/>
public virtual Command[] GetCommands() => [];
/// <inheritdoc/>
public virtual Task InitializeAsync(InitArgs e, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
/// <inheritdoc/>
public virtual void OptionsLoaded(OptionsLoadedArgs e)
{
}
///// <inheritdoc/>
//public virtual Task AfterRecordingStopAsync(RecordingArgs e, CancellationToken cancellationToken)
//{
// return Task.CompletedTask;
//}
/// <inheritdoc/>
public virtual Task MockRequestAsync(EventArgs e, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
public abstract class BasePlugin<TConfiguration>(
HttpClient httpClient,
ILogger logger,
ISet<UrlToWatch> urlsToWatch,
IProxyConfiguration proxyConfiguration,
IConfigurationSection pluginConfigurationSection) :
BasePlugin(logger, urlsToWatch), IPlugin<TConfiguration> where TConfiguration : new()
{
private TConfiguration? _configuration;
private readonly HttpClient _httpClient = httpClient;
protected IProxyConfiguration ProxyConfiguration { get; } = proxyConfiguration;
public TConfiguration Configuration
{
get
{
if (_configuration is null)
{
if (!ConfigurationSection.Exists())
{
_configuration = new();
}
else
{
_configuration = ConfigurationSection.Get<TConfiguration>();
}
}
return _configuration!;
}
}
public IConfigurationSection ConfigurationSection { get; } = pluginConfigurationSection;
public virtual void Register(IServiceCollection services, TConfiguration configuration)
{
}
public override async Task InitializeAsync(InitArgs e, CancellationToken cancellationToken)
{
await base.InitializeAsync(e, cancellationToken);
var (IsValid, ValidationErrors) = await ValidatePluginConfigAsync(cancellationToken);
if (!IsValid)
{
Logger.LogError("Plugin configuration validation failed with the following errors: {Errors}", string.Join(", ", ValidationErrors));
}
}
/// <summary>
/// <para>Evaluates the <paramref name="key"/> array property.
/// If the property exists, the <paramref name="configuredList"/> value is used;
/// otherwise, the default <paramref name="defaultList"/> is applied.</para>
/// <para>If the property is <i>null</i>, it is interpreted as an empty array (<i>[]</i>).</para>
/// <para>Note: This is necessary because .NET configuration binding cannot differentiate between an empty array,
/// a null value, or a missing property in appsettings.json.
/// See at <see cref="https://github.com/dotnet/runtime/issues/58930"/>
/// </para>
/// </summary>
/// <param name="key">The array property name</param>
/// <param name="configuredList">The configured list of string values</param>
/// <param name="defaultList">The default list of string values</param>
/// <returns>Returns the result list of string values</returns>
protected virtual IEnumerable<string>? GetConfigurationValue(string key, IEnumerable<string>? configuredList,
IEnumerable<string>? defaultList = default)
{
ArgumentNullException.ThrowIfNull(key, nameof(key));
var keyExists = ConfigurationSection.GetChildren().Any(f => string.Equals(key, f.Key, StringComparison.Ordinal));
configuredList = configuredList?.Where(static p => !string.IsNullOrEmpty(p));
return keyExists ? configuredList ?? [] : defaultList;
}
private async Task<(bool IsValid, IEnumerable<string> ValidationErrors)> ValidatePluginConfigAsync(CancellationToken cancellationToken)
{
if (!ProxyConfiguration.ValidateSchemas)
{
Logger.LogDebug("Schema validation is disabled");
return (true, []);
}
try
{
var schemaUrl = ConfigurationSection.GetValue<string>("$schema");
if (string.IsNullOrWhiteSpace(schemaUrl))
{
Logger.LogDebug("No schema URL found in configuration file");
return (true, []);
}
var configSectionName = ConfigurationSection.Key;
var configFile = await File.ReadAllTextAsync(ProxyConfiguration.ConfigFile, cancellationToken);
using var document = JsonDocument.Parse(configFile, ProxyUtils.JsonDocumentOptions);
var root = document.RootElement;
if (!root.TryGetProperty(configSectionName, out var configSection))
{
Logger.LogError("Configuration section {SectionName} not found in configuration file", configSectionName);
return (false, [string.Format(CultureInfo.InvariantCulture, "Configuration section {0} not found in configuration file", configSectionName)]);
}
ProxyUtils.ValidateSchemaVersion(schemaUrl, Logger);
return await ProxyUtils.ValidateJsonAsync(configSection.GetRawText(), schemaUrl, _httpClient, Logger, cancellationToken);
}
catch (Exception ex)
{
return (false, [ex.Message]);
}
}
}