Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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;
}
11 changes: 6 additions & 5 deletions DevProxy/Commands/DevProxyCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string?> 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<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."
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -857,7 +858,7 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions)
apiPortOption,
apiIpAddressOption,
asSystemProxyOption,
ConfigFileOption,
_configFileOption,
detachedOption,
discoverOption,
envOption,
Expand Down Expand Up @@ -893,7 +894,7 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions)
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<LogsCommand>(_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