From 809dc3eb8485dd2369d05e553ff734b960999969 Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sat, 21 Nov 2026 15:05:10 +0100 Subject: [PATCH 1/6] Stop hot reload from retaining every previous generation - Dispose the temporary service provider used to get a logger while registering plugins. - Create the --config-file option per DevProxyCommand instance, so System.CommandLine's parent tracking doesn't keep every command (and its WebApplication) alive. - Never expire HttpClientFactory handlers; recycle pooled connections every 2 minutes instead. The handler expiry timers kept each generation's root service provider alive. - Reuse a plugin's load context across reloads while the plugin file is unchanged, find plugin types from metadata instead of GetTypes(), and don't load Microsoft.Data.Sqlite when disposing an unused MSGraphDb. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Abstractions/Data/MSGraphDb.cs | 13 ++- DevProxy.Tests/PluginLoadingTests.cs | 108 ++++++++++++++++++ DevProxy/Commands/DevProxyCommand.cs | 11 +- DevProxy/Commands/StdioCommand.cs | 7 +- .../IServiceCollectionExtensions.cs | 12 +- DevProxy/Plugins/PluginServiceExtensions.cs | 102 +++++++++++++++-- 6 files changed, 233 insertions(+), 20 deletions(-) create mode 100644 DevProxy.Tests/PluginLoadingTests.cs 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.Tests/PluginLoadingTests.cs b/DevProxy.Tests/PluginLoadingTests.cs new file mode 100644 index 000000000..60e5ad320 --- /dev/null +++ b/DevProxy.Tests/PluginLoadingTests.cs @@ -0,0 +1,108 @@ +// 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_UnchangedFile_ReusesContext() + { + var pluginPath = CopyTestAssembly(); + try + { + var first = PluginServiceExtensions.GetPluginLoadContext(pluginPath); + var second = PluginServiceExtensions.GetPluginLoadContext(pluginPath); + + Assert.Same(first, second); + } + finally + { + File.Delete(pluginPath); + } + } + + [Fact] + public void GetPluginLoadContext_ChangedFile_CreatesNewContext() + { + var pluginPath = CopyTestAssembly(); + try + { + var first = PluginServiceExtensions.GetPluginLoadContext(pluginPath); + File.SetLastWriteTimeUtc(pluginPath, File.GetLastWriteTimeUtc(pluginPath).AddMinutes(1)); + var second = PluginServiceExtensions.GetPluginLoadContext(pluginPath); + + Assert.NotSame(first, second); + } + finally + { + File.Delete(pluginPath); + } + } + + [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 static string CopyTestAssembly() + { + var pluginPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.dll"); + File.Copy(typeof(PluginLoadingTests).Assembly.Location, pluginPath); + return pluginPath; + } + } + + 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 e46dbe450..1ae058d78 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -34,7 +34,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." @@ -410,8 +412,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)) @@ -646,7 +647,7 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions) apiPortOption, apiIpAddressOption, asSystemProxyOption, - ConfigFileOption, + _configFileOption, detachedOption, discoverOption, envOption, @@ -681,7 +682,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 1e54a097b..8216678c2 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