Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,8 @@ dotnet_diagnostic.CA1303.severity = none
dotnet_diagnostic.CA1308.severity = none
# Avoid uninstantiated internal classes
dotnet_diagnostic.CA1812.severity = none
# Avoid potentially expensive logging
dotnet_diagnostic.CA1873.severity = none
# Use the LoggerMessage delegates
dotnet_diagnostic.CA1848.severity = none
# Possible multiple enumerations of IEnumerable collection
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1
with:
dotnet-version: 9.0.x
dotnet-version: 10.0.x

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/create-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1
with:
dotnet-version: 9.0.x
dotnet-version: 10.0.x
- name: Rename executable for beta
if: contains(github.ref_name, '-beta')
run: |
Expand All @@ -59,7 +59,7 @@ jobs:
if: matrix.architecture == 'win-x64'
run: dotnet build ./DevProxy.Abstractions/DevProxy.Abstractions.csproj -p:InformationalVersion=$("${{ github.ref_name }}".Substring(1)) -c Release --no-self-contained
- name: Add plugins to output
run: cp ./DevProxy/bin/Release/net9.0/${{ matrix.architecture }}/plugins ./${{ env.release }} -r
run: cp ./DevProxy/bin/Release/net10.0/${{ matrix.architecture }}/plugins ./${{ env.release }} -r
- name: Remove unnecessary files
run: |
pushd
Expand Down Expand Up @@ -112,7 +112,7 @@ jobs:
shell: pwsh
run: >
./sign code azure-key-vault
./DevProxy.Abstractions/bin/Release/net9.0/DevProxy.Abstractions.dll
./DevProxy.Abstractions/bin/Release/net10.0/DevProxy.Abstractions.dll
--publisher-name "${{ env.APP_PUBLISHER }}"
--description "${{ env.APP_DESCRIPTION }}"
--description-url "${{ env.APP_DESCRIPTION_URL }}"
Expand All @@ -127,7 +127,7 @@ jobs:
uses: thedoctor0/zip-release@b57d897cb5d60cb78b51a507f63fa184cfe35554 # master
with:
filename: '../../../../DevProxy.Abstractions-${{ github.ref_name }}.zip'
directory: './DevProxy.Abstractions/bin/Release/net9.0'
directory: './DevProxy.Abstractions/bin/Release/net10.0'
exclusions: '*.json'
- name: Upload abstractions
if: matrix.architecture == 'win-x64'
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1
with:
dotnet-version: 9.0.x
dotnet-version: 10.0.x
- name: Restore workloads
run: dotnet workload restore
- name: Restore dependencies
Expand Down
4 changes: 2 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/DevProxy/bin/Debug/net9.0/devproxy.dll",
"program": "${workspaceFolder}/DevProxy/bin/Debug/net10.0/devproxy.dll",
"args": [],
"cwd": "${workspaceFolder}/DevProxy/bin/Debug/net9.0",
"cwd": "${workspaceFolder}/DevProxy/bin/Debug/net10.0",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "integratedTerminal",
"stopAtEntry": false,
Expand Down
2 changes: 1 addition & 1 deletion DevProxy.Abstractions/DevProxy.Abstractions.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>DevProxy.Abstractions</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ public sealed class OllamaLanguageModelClient(

if (Configuration.CacheResponses && _cacheChatCompletion.TryGetCacheValue(messages, out var cachedResponse))
{
Logger.LogDebug("Returning cached response for message: {LastMessage}", messages.Last().Content);
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug("Returning cached response for message: {LastMessage}", messages.Last().Content);
}
return cachedResponse;
}

Expand Down Expand Up @@ -181,7 +184,10 @@ protected override async Task<bool> IsEnabledCoreAsync(CancellationToken cancell
try
{
var url = $"{Configuration.Url?.TrimEnd('/')}/api/chat";
Logger.LogDebug("Requesting chat completion. Message: {LastMessage}", messages.Last().Content);
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug("Requesting chat completion. Message: {LastMessage}", messages.Last().Content);
}

var response = await _httpClient.PostAsJsonAsync(url,
new
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ public sealed class OpenAILanguageModelClient(

if (Configuration.CacheResponses && _cacheChatCompletion.TryGetCacheValue(messages, out var cachedResponse))
{
_logger.LogDebug("Returning cached response for message: {LastMessage}", messages.Last().Content);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Returning cached response for message: {LastMessage}", messages.Last().Content);
}
return cachedResponse;
}

Expand Down Expand Up @@ -148,7 +151,10 @@ protected override async Task<bool> IsEnabledCoreAsync(CancellationToken cancell
try
{
var url = $"{Configuration.Url?.TrimEnd('/')}/chat/completions";
_logger.LogDebug("Requesting chat completion. Message: {LastMessage}", messages.Last().Content);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Requesting chat completion. Message: {LastMessage}", messages.Last().Content);
}

var payload = new OpenAIChatCompletionRequest
{
Expand Down
7 changes: 6 additions & 1 deletion DevProxy.Abstractions/Models/MockResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public object Clone()

public static MockResponse FromHttpResponse(string httpResponse, ILogger logger)
{
ArgumentNullException.ThrowIfNull(logger);

logger.LogTrace("{Method} called", nameof(FromHttpResponse));

if (string.IsNullOrWhiteSpace(httpResponse))
Expand All @@ -40,7 +42,10 @@ public static MockResponse FromHttpResponse(string httpResponse, ILogger logger)
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i];
logger.LogTrace("Processing line {LineNumber}: {LineContent}", i + 1, line);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Processing line {LineNumber}: {LineContent}", i + 1, line);
}

if (i == 0)
{
Expand Down
5 changes: 4 additions & 1 deletion DevProxy.Abstractions/Plugins/BaseLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,10 @@ private async Task<bool> ValidateFileContentsAsync(string fileContents, Cancella

if (!IsValid)
{
Logger.LogError("Schema validation failed for {File} with the following errors: {Errors}", FilePath, string.Join(", ", ValidationErrors));
if (Logger.IsEnabled(LogLevel.Error))
{
Logger.LogError("Schema validation failed for {File} with the following errors: {Errors}", FilePath, string.Join(", ", ValidationErrors));
}
}

return IsValid;
Expand Down
5 changes: 4 additions & 1 deletion DevProxy.Abstractions/Plugins/BasePlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,10 @@ public override async Task InitializeAsync(InitArgs e, CancellationToken cancell
var (IsValid, ValidationErrors) = await ValidatePluginConfigAsync(cancellationToken);
if (!IsValid)
{
Logger.LogError("Plugin configuration validation failed with the following errors: {Errors}", string.Join(", ", ValidationErrors));
if (Logger.IsEnabled(LogLevel.Error))
{
Logger.LogError("Plugin configuration validation failed with the following errors: {Errors}", string.Join(", ", ValidationErrors));
}
}
}

Expand Down
31 changes: 5 additions & 26 deletions DevProxy.Abstractions/packages.lock.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"version": 1,
"dependencies": {
"net9.0": {
"net10.0": {
"Markdig": {
"type": "Direct",
"requested": "[0.41.3, )",
Expand All @@ -20,8 +20,7 @@
"Microsoft.Extensions.DependencyModel": "9.0.4",
"Microsoft.Extensions.Logging": "9.0.4",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.10",
"SQLitePCLRaw.core": "2.1.10",
"System.Text.Json": "9.0.4"
"SQLitePCLRaw.core": "2.1.10"
}
},
"Microsoft.Extensions.Configuration": {
Expand Down Expand Up @@ -102,8 +101,7 @@
"contentHash": "HiICGm0e44+i4aVHpLn+aphmSC2eQnDvlTttw1rE0hntOZKoLGRy37sydqqbRP1ZokMf3Mt0GEgSWxDwnucKGg==",
"dependencies": {
"BouncyCastle.Cryptography": "2.4.0",
"Microsoft.Extensions.Logging.Abstractions": "8.0.1",
"System.Runtime.CompilerServices.Unsafe": "6.0.0"
"Microsoft.Extensions.Logging.Abstractions": "8.0.1"
}
},
"YamlDotNet": {
Expand Down Expand Up @@ -168,8 +166,7 @@
"Microsoft.Extensions.Configuration.Abstractions": "9.0.4",
"Microsoft.Extensions.DependencyModel": "9.0.4",
"Microsoft.Extensions.Logging": "9.0.4",
"SQLitePCLRaw.core": "2.1.10",
"System.Text.Json": "9.0.4"
"SQLitePCLRaw.core": "2.1.10"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
Expand Down Expand Up @@ -304,10 +301,7 @@
"SQLitePCLRaw.core": {
"type": "Transitive",
"resolved": "2.1.10",
"contentHash": "Ii8JCbC7oiVclaE/mbDEK000EFIJ+ShRPwAvvV89GOZhQ+ZLtlnSWl6ksCNMKu/VGXA4Nfi2B7LhN/QFN9oBcw==",
"dependencies": {
"System.Memory": "4.5.3"
}
"contentHash": "Ii8JCbC7oiVclaE/mbDEK000EFIJ+ShRPwAvvV89GOZhQ+ZLtlnSWl6ksCNMKu/VGXA4Nfi2B7LhN/QFN9oBcw=="
},
"SQLitePCLRaw.lib.e_sqlite3": {
"type": "Transitive",
Expand All @@ -321,21 +315,6 @@
"dependencies": {
"SQLitePCLRaw.core": "2.1.10"
}
},
"System.Memory": {
"type": "Transitive",
"resolved": "4.5.3",
"contentHash": "3oDzvc/zzetpTKWMShs1AADwZjQ/36HnsufHRPcOjyRAAMLDlu2iD33MBI2opxnezcVUtXyqDXXjoFMOU9c7SA=="
},
"System.Runtime.CompilerServices.Unsafe": {
"type": "Transitive",
"resolved": "6.0.0",
"contentHash": "/iUeP3tq1S0XdNNoMz5C9twLSrM/TH+qElHkXWaPvuNOt+99G75NrV0OS2EqHx5wMN7popYjpc8oTjC1y16DLg=="
},
"System.Text.Json": {
"type": "Transitive",
"resolved": "9.0.4",
"contentHash": "pYtmpcO6R3Ef1XilZEHgXP2xBPVORbYEzRP7dl0IAAbN8Dm+kfwio8aCKle97rAWXOExr292MuxWYurIuwN62g=="
}
}
}
Expand Down
5 changes: 4 additions & 1 deletion DevProxy.Plugins/Behavior/GenericErrorResponsesLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ protected override void LoadData(string fileContents)
if (configResponses is not null)
{
_configuration.Errors = configResponses;
Logger.LogInformation("{ConfigResponseCount} error responses loaded from {ErrorFile}", configResponses.Count(), _configuration.ErrorsFile);
if (Logger.IsEnabled(LogLevel.Information))
{
Logger.LogInformation("{ConfigResponseCount} error responses loaded from {ErrorFile}", configResponses.Count(), _configuration.ErrorsFile);
}
}
}
catch (Exception ex)
Expand Down
15 changes: 9 additions & 6 deletions DevProxy.Plugins/Behavior/GenericRandomErrorPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -308,12 +308,15 @@ private void ValidateErrors()
}

var suggestedWildcards = ProxyUtils.GetWildcardPatterns(unmatchedErrorUrls.AsReadOnly());
Logger.LogWarning(
"The following URLs in {ErrorsFile} don't match any URL to watch: {UnmatchedMocks}. Add the following URLs to URLs to watch: {UrlsToWatch}",
Configuration.ErrorsFile,
string.Join(", ", unmatchedErrorUrls),
string.Join(", ", suggestedWildcards)
);
if (Logger.IsEnabled(LogLevel.Warning))
{
Logger.LogWarning(
"The following URLs in {ErrorsFile} don't match any URL to watch: {UnmatchedMocks}. Add the following URLs to URLs to watch: {UrlsToWatch}",
Configuration.ErrorsFile,
string.Join(", ", unmatchedErrorUrls),
string.Join(", ", suggestedWildcards)
);
}
}

private static bool HasMatchingBody(GenericErrorResponse errorResponse, Request request)
Expand Down
2 changes: 1 addition & 1 deletion DevProxy.Plugins/DevProxy.Plugins.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>DevProxy.Plugins</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
Expand Down
23 changes: 16 additions & 7 deletions DevProxy.Plugins/Extensions/ApiCenterExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,14 @@ internal static async Task<Dictionary<string, ApiDefinition>> GetApiDefinitionsB
}
}

logger.LogDebug(
"Loaded API definitions from API Center for APIs:{NewLine}- {Apis}",
Environment.NewLine,
string.Join($"{Environment.NewLine}- ", apiDefinitions.Keys)
);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Loaded API definitions from API Center for APIs:{NewLine}- {Apis}",
Environment.NewLine,
string.Join($"{Environment.NewLine}- ", apiDefinitions.Keys)
);
}

return apiDefinitions;
}
Expand Down Expand Up @@ -165,7 +168,10 @@ internal static IEnumerable<string> GetUrls(this Api api)

if (api.Versions.Length == 1)
{
logger.LogDebug("API {Api} has only one version {Version}. Returning", api.Name, api.Versions[0].Name);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("API {Api} has only one version {Version}. Returning", api.Name, api.Versions[0].Name);
}
return api.Versions[0];
}

Expand Down Expand Up @@ -198,7 +204,10 @@ internal static IEnumerable<string> GetUrls(this Api api)
);
if (header is not null)
{
logger.LogDebug("Version {Version} found in header {Header}", $"{apiVersion.Name}/{apiVersion.Properties?.Title}", header.Name);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Version {Version} found in header {Header}", $"{apiVersion.Name}/{apiVersion.Properties?.Title}", header.Name);
}
return apiVersion;
}
}
Expand Down
5 changes: 4 additions & 1 deletion DevProxy.Plugins/Extensions/OpenApiDocumentExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ static class OpenApiDocumentExtensions
public static ApiPermissionsInfo CheckMinimalPermissions(this OpenApiDocument openApiDocument, IEnumerable<RequestLog> requests,
ILogger logger, string? schemeName = default)
{
logger.LogInformation("Checking minimal permissions for API {ApiName}...", openApiDocument.Servers.First().Url);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Checking minimal permissions for API {ApiName}...", openApiDocument.Servers.First().Url);
}

var tokenPermissions = new List<string>();
var operationsFromRequests = new List<ApiOperation>();
Expand Down
10 changes: 8 additions & 2 deletions DevProxy.Plugins/Generation/ApiCenterOnboardingPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,10 @@ public override async Task AfterRecordingStopAsync(RecordingArgs e, Cancellation
newApisMessageChunks.AddRange(apiPerHost.Select(a => $" {a.method} {a.url}"));
}

Logger.LogInformation("{NewApis}", string.Join(Environment.NewLine, newApisMessageChunks));
if (Logger.IsEnabled(LogLevel.Information))
{
Logger.LogInformation("{NewApis}", string.Join(Environment.NewLine, newApisMessageChunks));
}

if (!Configuration.CreateApicEntryForNewApis)
{
Expand Down Expand Up @@ -328,7 +331,10 @@ async Task CreateApisInApiCenterAsync(
}
else
{
Logger.LogError("Failed to create API version for {Api}", apiId[apiId.LastIndexOf('/')..]);
if (Logger.IsEnabled(LogLevel.Error))
{
Logger.LogError("Failed to create API version for {Api}", apiId[apiId.LastIndexOf('/')..]);
}
}

return newApiVersion;
Expand Down
2 changes: 1 addition & 1 deletion DevProxy.Plugins/Generation/HarGeneratorPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private HarEntry CreateHarEntry(RequestLog log)
QueryString = [.. HttpUtility.ParseQueryString(request.RequestUri?.Query ?? "")
.AllKeys
.Where(key => key is not null)
.Select(key => new HarQueryParam { Name = key!, Value = HttpUtility.ParseQueryString(request.RequestUri?.Query ?? "")[key] ?? "" })],
.Select(key => new HarQueryParam { Name = key, Value = HttpUtility.ParseQueryString(request.RequestUri?.Query ?? "")[key] ?? "" })],
Cookies = [.. request.Headers
.Where(h => string.Equals(h.Name, "Cookie", StringComparison.OrdinalIgnoreCase))
.Select(h => h.Value)
Expand Down
Loading