diff --git a/DevProxy.Abstractions/Data/MSGraphDb.cs b/DevProxy.Abstractions/Data/MSGraphDb.cs index a4e7a95f6..c7d487f49 100644 --- a/DevProxy.Abstractions/Data/MSGraphDb.cs +++ b/DevProxy.Abstractions/Data/MSGraphDb.cs @@ -9,6 +9,7 @@ using Microsoft.OpenApi.Reader; using System.Net; using System.Net.Http.Headers; +using System.Runtime.CompilerServices; namespace DevProxy.Abstractions.Data; @@ -21,6 +22,7 @@ public sealed class MSGraphDb(HttpClient httpClient, ILogger logger) #pragma warning restore CA2213 // Disposable fields should be disposed private readonly ILogger _logger = logger; private SqliteConnection? _connection; + private bool _connectionOpened; // v1 refers to v1 of the db schema, not the graph version public static string MSGraphDbFilePath => Path.Combine(ProxyUtils.AppFolder!, "msgraph-openapi-v1.db"); @@ -32,6 +34,7 @@ public SqliteConnection Connection if (_connection is null) { _connection = new($"Data Source={MSGraphDbFilePath}"); + _connectionOpened = true; _connection.Open(); } @@ -314,6 +317,14 @@ private void SetDbJournaling(bool enabled) public void Dispose() { - _connection?.Dispose(); + if (_connectionOpened) + { + DisposeConnection(); + } } + + // Kept separate so that disposing an unused instance doesn't need to + // load Microsoft.Data.Sqlite just to JIT-compile Dispose. + [MethodImpl(MethodImplOptions.NoInlining)] + private void DisposeConnection() => _connection?.Dispose(); } \ No newline at end of file diff --git a/DevProxy.Plugins/Inspection/OpenAITelemetryPlugin.cs b/DevProxy.Plugins/Inspection/OpenAITelemetryPlugin.cs index 69aae586d..bb10abc32 100644 --- a/DevProxy.Plugins/Inspection/OpenAITelemetryPlugin.cs +++ b/DevProxy.Plugins/Inspection/OpenAITelemetryPlugin.cs @@ -58,10 +58,10 @@ public sealed class OpenAITelemetryPlugin( private const string ActivitySourceName = "DevProxy.OpenAI"; private const string OpenAISystem = "openai"; - private static readonly Meter _meter = new(ActivitySourceName); - private static Histogram? _requestCostMetric; - private static Counter? _totalCostMetric; - private static Histogram? _tokenUsageMetric; + private readonly Meter _meter = new(ActivitySourceName); + private Histogram? _requestCostMetric; + private Counter? _totalCostMetric; + private Histogram? _tokenUsageMetric; private readonly ActivitySource _activitySource = new(ActivitySourceName); private LanguageModelPricesLoader? _loader; @@ -1105,6 +1105,7 @@ protected override void Dispose(bool disposing) _activitySource?.Dispose(); _tracerProvider?.Dispose(); _meterProvider?.Dispose(); + _meter.Dispose(); } base.Dispose(disposing); } diff --git a/DevProxy.Plugins/Inspection/WebSocketServer.cs b/DevProxy.Plugins/Inspection/WebSocketServer.cs index b83707363..d4db90f16 100644 --- a/DevProxy.Plugins/Inspection/WebSocketServer.cs +++ b/DevProxy.Plugins/Inspection/WebSocketServer.cs @@ -31,7 +31,8 @@ public sealed class WebSocketServer(string host, int port, string token, ILogger private readonly string _host = host; private readonly int _port = port; private readonly string _path = $"/{token}"; - static readonly SemaphoreSlim _webSocketSemaphore = new(1, 1); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Sends may be in flight during disposal; no wait handle is allocated")] + private readonly SemaphoreSlim _webSocketSemaphore = new(1, 1); private HttpListener? _listener; private WebSocket? _webSocket; @@ -135,11 +136,15 @@ public async Task SendAsync(TMsg message, CancellationToken cancellationTo // we need a semaphore to avoid multiple simultaneous writes // which aren't allowed await _webSocketSemaphore.WaitAsync(cancellationToken); - - var messageBytes = Encoding.UTF8.GetBytes(messageString); - await _webSocket.SendAsync(new ArraySegment(messageBytes), WebSocketMessageType.Text, true, cancellationToken); - - _ = _webSocketSemaphore.Release(); + try + { + var messageBytes = Encoding.UTF8.GetBytes(messageString); + await _webSocket.SendAsync(new ArraySegment(messageBytes), WebSocketMessageType.Text, true, cancellationToken); + } + finally + { + _ = _webSocketSemaphore.Release(); + } } private async Task HandleMessagesAsync(WebSocket ws) diff --git a/DevProxy.Tests/PluginLoadingTests.cs b/DevProxy.Tests/PluginLoadingTests.cs new file mode 100644 index 000000000..4dd36bb5e --- /dev/null +++ b/DevProxy.Tests/PluginLoadingTests.cs @@ -0,0 +1,169 @@ +// 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 DevProxy.Abstractions.Plugins; +using DevProxy.Abstractions.Proxy; +using Microsoft.Extensions.DependencyInjection; +using System.CommandLine; +using Xunit; + +namespace DevProxy.Tests +{ + public class PluginLoadingTests + { + [Fact] + public void GetPluginLoadContext_UnchangedFiles_ReusesContext() + { + using var plugin = new TempPlugin(); + + var first = PluginServiceExtensions.GetPluginLoadContext(plugin.PluginPath); + _ = first.LoadFromAssemblyName(new(DependencyName)); + var second = PluginServiceExtensions.GetPluginLoadContext(plugin.PluginPath); + + Assert.Same(first, second); + } + + [Fact] + public void GetPluginLoadContext_ChangedPlugin_CreatesNewContext() + { + using var plugin = new TempPlugin(); + + var first = PluginServiceExtensions.GetPluginLoadContext(plugin.PluginPath); + TempPlugin.Touch(plugin.PluginPath); + var second = PluginServiceExtensions.GetPluginLoadContext(plugin.PluginPath); + + Assert.NotSame(first, second); + } + + [Fact] + public void GetPluginLoadContext_ChangedLoadedDependency_CreatesNewContext() + { + using var plugin = new TempPlugin(); + + var first = PluginServiceExtensions.GetPluginLoadContext(plugin.PluginPath); + var dependency = first.LoadFromAssemblyName(new(DependencyName)); + // loaded from the plugin's folder (the temp path may be a symlink) + Assert.EndsWith(Path.Combine(Path.GetFileName(Path.GetDirectoryName(plugin.DependencyPath)!), $"{DependencyName}.dll"), dependency.Location, StringComparison.Ordinal); + TempPlugin.Touch(plugin.DependencyPath); + var second = PluginServiceExtensions.GetPluginLoadContext(plugin.PluginPath); + + Assert.NotSame(first, second); + } + + [Fact] + public void FindPluginType_ReplacedAssemblyFile_FallsBackToLoadedAssembly() + { + // Windows locks loaded assemblies, so the file can't be replaced + if (OperatingSystem.IsWindows()) + { + return; + } + + using var plugin = new TempPlugin(); + var context = PluginServiceExtensions.GetPluginLoadContext(plugin.PluginPath); + var assembly = context.LoadFromAssemblyName(new(Path.GetFileNameWithoutExtension(plugin.PluginPath))); + // a different assembly on disk has a different MVID and none of the plugin types; + // delete first so the loaded (memory-mapped) file isn't overwritten in place, + // which would corrupt the loaded image on Linux + File.Delete(plugin.PluginPath); + File.Copy(plugin.DependencyPath, plugin.PluginPath); + + var type = PluginServiceExtensions.FindPluginType(assembly, nameof(LookupPlugin)); + + Assert.NotNull(type); + Assert.Equal(typeof(LookupPlugin).FullName, type.FullName); + } + + [Fact] + public void FindPluginType_SkipsSameNamedNonPluginTypes() + { + var type = PluginServiceExtensions.FindPluginType(typeof(PluginLoadingTests).Assembly, nameof(LookupPlugin)); + + Assert.Equal(typeof(LookupPlugin), type); + } + + [Fact] + public void FindPluginType_FindsNestedPluginType() + { + var type = PluginServiceExtensions.FindPluginType(typeof(PluginLoadingTests).Assembly, nameof(Outer.NestedLookupPlugin)); + + Assert.Equal(typeof(Outer.NestedLookupPlugin), type); + } + + [Fact] + public void FindPluginType_UnknownName_ReturnsNull() + { + Assert.Null(PluginServiceExtensions.FindPluginType(typeof(PluginLoadingTests).Assembly, "DoesNotExistPlugin")); + } + + private const string DependencyName = "xunit.assert"; + + private sealed class TempPlugin : IDisposable + { + private readonly string _directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + + public string PluginPath { get; } + public string DependencyPath { get; } + + public TempPlugin() + { + _ = Directory.CreateDirectory(_directory); + var source = typeof(PluginLoadingTests).Assembly.Location; + var sourceDirectory = Path.GetDirectoryName(source)!; + PluginPath = Path.Combine(_directory, Path.GetFileName(source)); + DependencyPath = Path.Combine(_directory, $"{DependencyName}.dll"); + File.Copy(source, PluginPath); + File.Copy(Path.ChangeExtension(source, ".deps.json"), Path.ChangeExtension(PluginPath, ".deps.json")); + File.Copy(Path.Combine(sourceDirectory, $"{DependencyName}.dll"), DependencyPath); + } + + public static void Touch(string path) => + File.SetLastWriteTimeUtc(path, File.GetLastWriteTimeUtc(path).AddMinutes(1)); + + public void Dispose() + { + try + { + Directory.Delete(_directory, recursive: true); + } + catch (IOException) + { + // loaded assemblies may still be locked on Windows + } + catch (UnauthorizedAccessException) + { + } + } + } + } + + public abstract class LookupPluginBase : IPlugin + { + public string Name => GetType().Name; + public bool Enabled => true; + public Option[] GetOptions() => []; + public Command[] GetCommands() => []; + public Task InitializeAsync(InitArgs e, CancellationToken cancellationToken) => Task.CompletedTask; + public void OptionsLoaded(OptionsLoadedArgs e) { } + public Task BeforeRequestAsync(ProxyRequestArgs e, CancellationToken cancellationToken) => Task.CompletedTask; + public Task BeforeResponseAsync(ProxyResponseArgs e, CancellationToken cancellationToken) => Task.CompletedTask; + public Task AfterResponseAsync(ProxyResponseArgs e, CancellationToken cancellationToken) => Task.CompletedTask; + public Task AfterRequestLogAsync(RequestLogArgs e, CancellationToken cancellationToken) => Task.CompletedTask; + public Task AfterRecordingStopAsync(RecordingArgs e, CancellationToken cancellationToken) => Task.CompletedTask; + public Task MockRequestAsync(EventArgs e, CancellationToken cancellationToken) => Task.CompletedTask; + } + + public sealed class LookupPlugin : LookupPluginBase; + + public static class Outer + { + public sealed class NestedLookupPlugin : LookupPluginBase; + } +} + +// Same name as a plugin type, but not a plugin, so lookup must skip it. +namespace DevProxy.Tests.Aaa +{ + public sealed class LookupPlugin; +} diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 5ff34d65d..9332a507b 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -38,7 +38,9 @@ sealed class DevProxyCommand : RootCommand internal const string WatchProcessNamesOptionName = "--watch-process-names"; internal const string WatchProcessTreeOptionName = "--watch-process-tree"; internal const string ConfigFileOptionName = "--config-file"; - internal static readonly Option ConfigFileOption = new(ConfigFileOptionName, "-c") + // Per instance: System.CommandLine records each command an option is added + // to, so a static option would keep every hot-reload generation alive. + private readonly Option _configFileOption = new(ConfigFileOptionName, "-c") { HelpName = "config-file", Description = "Path to config file. If not specified, Dev Proxy searches for devproxyrc.jsonc or devproxyrc.json in the current directory, then in a .devproxy/ directory, then under the ~appFolder location. Supports ~appFolder and ~dataFolder tokens, and a leading ~/ for the home directory." @@ -631,8 +633,7 @@ await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _pr private void ConfigureCommand(DevProxyConfigOptions configOptions) { - ConfigFileOption.Validators.Clear(); - ConfigFileOption.Validators.Add(input => + _configFileOption.Validators.Add(input => { var filePath = configOptions.ConfigFile ?? ProxyUtils.ReplacePathTokens(input.Tokens[0].Value); if (string.IsNullOrEmpty(filePath)) @@ -857,7 +858,7 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions) apiPortOption, apiIpAddressOption, asSystemProxyOption, - ConfigFileOption, + _configFileOption, detachedOption, discoverOption, envOption, @@ -893,7 +894,7 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions) ActivatorUtilities.CreateInstance(_serviceProvider), ActivatorUtilities.CreateInstance(_serviceProvider), ActivatorUtilities.CreateInstance(_serviceProvider), - ActivatorUtilities.CreateInstance(_serviceProvider), + ActivatorUtilities.CreateInstance(_serviceProvider, _configFileOption), ActivatorUtilities.CreateInstance(_serviceProvider), ActivatorUtilities.CreateInstance(_serviceProvider), ActivatorUtilities.CreateInstance(_serviceProvider), diff --git a/DevProxy/Commands/StdioCommand.cs b/DevProxy/Commands/StdioCommand.cs index a58b05c97..b57fa7413 100644 --- a/DevProxy/Commands/StdioCommand.cs +++ b/DevProxy/Commands/StdioCommand.cs @@ -14,6 +14,7 @@ sealed class StdioCommand : Command { private readonly ILogger _logger; private readonly ILoggerFactory _loggerFactory; + private readonly Option _configFileOption; private readonly IEnumerable _plugins; // Global data shared across stdio sessions @@ -31,7 +32,8 @@ sealed class StdioCommand : Command public StdioCommand( ILogger logger, ILoggerFactory loggerFactory, - IEnumerable plugins) : + IEnumerable plugins, + Option configFileOption) : base("stdio", """ Proxy stdin/stdout/stderr of local executables. Dev Proxy intercepts and processes the stdio streams of the specified command, @@ -49,6 +51,7 @@ devproxy stdio -c myconfig.json node app.js With custom config _logger = logger; _loggerFactory = loggerFactory; _plugins = plugins; + _configFileOption = configFileOption; ConfigureCommand(); } @@ -57,7 +60,7 @@ private void ConfigureCommand() { Add(_commandArgument); - var options = new List