Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
809dc3e
Stop hot reload from retaining every previous generation
waldekmastykarz Nov 21, 2026
88f0070
Invalidate plugin load context when a loaded dependency changes
waldekmastykarz Nov 21, 2026
de5a64b
Scope DevTools WebSocket semaphore to the server instance and release…
waldekmastykarz Nov 21, 2026
fbe4159
Don't dispose the DevTools semaphore while sends may be in flight; sk…
waldekmastykarz Nov 21, 2026
ec7ff7c
Scope OpenAI telemetry meter to the plugin instance
waldekmastykarz Nov 21, 2026
c18be49
Merge branch 'main' into hot-reload-retention-fixes
waldekmastykarz Nov 24, 2026
12e5951
Replace plugin file with a new inode in fallback test
waldekmastykarz Nov 24, 2026
176841f
Merge branch 'main' into hot-reload-retention-fixes
waldekmastykarz Nov 25, 2026
47ee0e0
Merge branch 'main' into hot-reload-retention-fixes
waldekmastykarz Nov 26, 2026
835af76
Merge branch 'main' into hot-reload-retention-fixes
waldekmastykarz Nov 26, 2026
e38cf5e
Merge branch 'main' into hot-reload-retention-fixes
waldekmastykarz Nov 26, 2026
28a8dbe
Merge branch 'main' into hot-reload-retention-fixes
waldekmastykarz Nov 27, 2026
f9c140c
Merge upstream main into hot-reload-retention-fixes
waldekmastykarz Nov 27, 2026
6fc08bf
Merge upstream main into hot-reload-retention-fixes
waldekmastykarz Dec 1, 2026
2d9e2a2
Log plugin init failures through the live logger
waldekmastykarz Dec 1, 2026
d989530
Merge branch 'main' into hot-reload-retention-fixes
waldekmastykarz Dec 2, 2026
c8db6a8
Merge dotnet/dev-proxy main into hot-reload-retention-fixes
waldekmastykarz Dec 2, 2026
f90ce04
Restore CRLF line endings in DevProxyCommand.cs
waldekmastykarz Dec 2, 2026
ea1de6e
Merge dotnet/dev-proxy main into hot-reload-retention-fixes
waldekmastykarz Dec 2, 2026
09723f3
Merge dotnet/dev-proxy main into hot-reload-retention-fixes
waldekmastykarz Dec 2, 2026
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
13 changes: 12 additions & 1 deletion DevProxy.Abstractions/Data/MSGraphDb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.OpenApi.Reader;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;

namespace DevProxy.Abstractions.Data;

Expand All @@ -21,6 +22,7 @@ public sealed class MSGraphDb(HttpClient httpClient, ILogger<MSGraphDb> logger)
#pragma warning restore CA2213 // Disposable fields should be disposed
private readonly ILogger<MSGraphDb> _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");
Expand All @@ -32,6 +34,7 @@ public SqliteConnection Connection
if (_connection is null)
{
_connection = new($"Data Source={MSGraphDbFilePath}");
_connectionOpened = true;
_connection.Open();
}

Expand Down Expand Up @@ -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();
}
9 changes: 5 additions & 4 deletions DevProxy.Plugins/Inspection/OpenAITelemetryPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<double>? _requestCostMetric;
private static Counter<double>? _totalCostMetric;
private static Histogram<long>? _tokenUsageMetric;
private readonly Meter _meter = new(ActivitySourceName);
private Histogram<double>? _requestCostMetric;
private Counter<double>? _totalCostMetric;
private Histogram<long>? _tokenUsageMetric;

private readonly ActivitySource _activitySource = new(ActivitySourceName);
private LanguageModelPricesLoader? _loader;
Expand Down Expand Up @@ -1105,6 +1105,7 @@ protected override void Dispose(bool disposing)
_activitySource?.Dispose();
_tracerProvider?.Dispose();
_meterProvider?.Dispose();
_meter.Dispose();
}
base.Dispose(disposing);
}
Expand Down
17 changes: 11 additions & 6 deletions DevProxy.Plugins/Inspection/WebSocketServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -135,11 +136,15 @@ public async Task SendAsync<TMsg>(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<byte>(messageBytes), WebSocketMessageType.Text, true, cancellationToken);

_ = _webSocketSemaphore.Release();
try
{
var messageBytes = Encoding.UTF8.GetBytes(messageString);
await _webSocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, cancellationToken);
}
finally
{
_ = _webSocketSemaphore.Release();
}
}

private async Task HandleMessagesAsync(WebSocket ws)
Expand Down
169 changes: 169 additions & 0 deletions DevProxy.Tests/PluginLoadingTests.cs
Original file line number Diff line number Diff line change
@@ -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;
}
23 changes: 13 additions & 10 deletions DevProxy/Commands/DevProxyCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,14 @@ 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<string?> ConfigFileOption = new(ConfigFileOptionName, "-c")
private const string ConfigFileHelpName = "config-file";
private const string ConfigFileDescription = "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.";
// 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<string?> _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."
HelpName = ConfigFileHelpName,
Description = ConfigFileDescription
};
internal const string NoFirstRunOptionName = "--no-first-run";
internal const string NoWatchOptionName = "--no-watch";
Expand Down Expand Up @@ -468,7 +472,7 @@ public async Task<int> InvokeAsync(string[] args, WebApplication app)
// Subcommands that use the configuration, including plugin commands that
// only exist when the configuration that loads their plugin is selected,
// must accept the config file option. Options must follow the subcommand
// (see GetLeadingOptionsError) and ConfigFileOption isn't recursive, so
// (see GetLeadingOptionsError) and the root config file option isn't recursive, so
// add a recursive copy. resolvedConfigFile is the config file path resolved
// before --env changed the environment, which is the file that was loaded.
internal static void AddConfigFileOption(Command command, string? resolvedConfigFile)
Expand All @@ -484,8 +488,8 @@ static bool DeclaresConfigFile(Command c) =>

var option = new Option<string?>(ConfigFileOptionName, "-c")
{
HelpName = ConfigFileOption.HelpName,
Description = ConfigFileOption.Description,
HelpName = ConfigFileHelpName,
Description = ConfigFileDescription,
Recursive = true
};
option.Validators.Add(CreateConfigFileValidator(resolvedConfigFile));
Expand Down Expand Up @@ -755,11 +759,10 @@ await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _pr

private void ConfigureCommand()
{
ConfigFileOption.Validators.Clear();
ConfigFileOption.Validators.Add(CreateConfigFileValidator(_configOptions.ConfigFile));
_configFileOption.Validators.Add(CreateConfigFileValidator(_configOptions.ConfigFile));

var options = CreateRootOptions(_proxyConfiguration);
options.Add(ConfigFileOption);
options.Add(_configFileOption);
options.AddRange(_plugins
.SelectMany(p => p.GetOptions())
// remove duplicates by comparing the option names
Expand All @@ -775,7 +778,7 @@ private void ConfigureCommand()
ActivatorUtilities.CreateInstance<OutdatedCommand>(_serviceProvider),
ActivatorUtilities.CreateInstance<JwtCommand>(_serviceProvider),
ActivatorUtilities.CreateInstance<CertCommand>(_serviceProvider),
ActivatorUtilities.CreateInstance<StdioCommand>(_serviceProvider),
ActivatorUtilities.CreateInstance<StdioCommand>(_serviceProvider, _configFileOption),
ActivatorUtilities.CreateInstance<StatusCommand>(_serviceProvider),
ActivatorUtilities.CreateInstance<StopCommand>(_serviceProvider),
ActivatorUtilities.CreateInstance<SystemProxyCommand>(_serviceProvider),
Expand Down
7 changes: 5 additions & 2 deletions DevProxy/Commands/StdioCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ sealed class StdioCommand : Command
{
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly Option<string?> _configFileOption;
private readonly IEnumerable<IStdioPlugin> _plugins;

// Global data shared across stdio sessions
Expand All @@ -31,7 +32,8 @@ sealed class StdioCommand : Command
public StdioCommand(
ILogger<StdioCommand> logger,
ILoggerFactory loggerFactory,
IEnumerable<IStdioPlugin> plugins) :
IEnumerable<IStdioPlugin> plugins,
Option<string?> configFileOption) :
base("stdio", """
Proxy stdin/stdout/stderr of local executables.
Dev Proxy intercepts and processes the stdio streams of the specified command,
Expand All @@ -49,6 +51,7 @@ devproxy stdio -c myconfig.json node app.js With custom config
_logger = logger;
_loggerFactory = loggerFactory;
_plugins = plugins;
_configFileOption = configFileOption;

ConfigureCommand();
}
Expand All @@ -57,7 +60,7 @@ private void ConfigureCommand()
{
Add(_commandArgument);

var options = new List<Option> { DevProxyCommand.ConfigFileOption };
var options = new List<Option> { _configFileOption };
// Add plugin options
options.AddRange(_plugins
.OfType<IPlugin>()
Expand Down
12 changes: 11 additions & 1 deletion DevProxy/Extensions/IServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,17 @@ static IServiceCollection AddApplicationServices(
.AddSingleton<UpdateNotification>()
.AddSingleton<DevProxyCommand>()
.AddSingleton<MSGraphDb>()
.AddHttpClient();
.AddHttpClient()
// Handler rotation keeps the factory's expiry timers rooted, and through
// them every hot-reload generation's service provider. Never expire
// handlers and recycle pooled connections instead, so DNS changes are
// still picked up.
.ConfigureHttpClientDefaults(b => b
.SetHandlerLifetime(Timeout.InfiniteTimeSpan)
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(2)
}));

_ = services.AddPlugins(configuration, options);

Expand Down
Loading
Loading