Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Address warnings in 2.x #2861

Merged
merged 2 commits into from
Nov 13, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ internal static Task InvokeFunctionAsync(this HttpContext context)
{
var coordinator = context.RequestServices.GetRequiredService<IHttpCoordinator>();
context.Request.Headers.TryGetValue(Constants.CorrelationHeader, out StringValues invocationId);
return coordinator.RunFunctionInvocationAsync(invocationId);
return coordinator.RunFunctionInvocationAsync(invocationId!); // will fail later if null.
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public async Task Invoke(HttpContext context)
throw new InvalidOperationException($"Expected correlation id header ('{Constants.CorrelationHeader}') not present");
}

FunctionContext functionContext = await _coordinator.SetHttpContextAsync(invocationId, context);
FunctionContext functionContext = await _coordinator.SetHttpContextAsync(invocationId!, context);

// Explicitly set the RequestServices to prevent a new scope from being created internally.
// This also prevents the scope from being disposed when the request is complete. We want this to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ private Task ProcessResponseStarting()
_originalResponseHeaders.Clear();
foreach (var item in ((HeadersEnumerable)this))
{
_originalResponseHeaders.Add(item.Key, item.Value);
_originalResponseHeaders[item.Key] = item.Value;
}

return Task.CompletedTask;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ public ExtensionTrace(ILoggerFactory loggerFactory)
_defaultLogger = loggerFactory.CreateLogger("Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore");
}

public IDisposable BeginScope<TState>(TState state) => _defaultLogger.BeginScope(state);
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull
=> _defaultLogger.BeginScope(state);

public bool IsEnabled(LogLevel logLevel) => _defaultLogger.IsEnabled(logLevel);

Expand Down
1 change: 1 addition & 0 deletions sdk/Sdk.Analyzers/Sdk.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<Nullable>disable</Nullable>
<PackageTags>Azure Functions Worker, analyzers</PackageTags>
<TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_AddAnalyzersToOutput</TargetsForTfmSpecificContentInPackage>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup>

<Import Project="..\..\build\Common.props" />
Expand Down
7 changes: 7 additions & 0 deletions sdk/Sdk.Generators/Constants.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;

namespace Microsoft.Azure.Functions.Worker.Sdk.Generators
{
internal static class Constants
{
#pragma warning disable RS1035 // Do not use APIs banned for analyzers
// Suppressing warning based on https://github.com/dotnet/roslyn-analyzers/issues/6467
internal static readonly string NewLine = Environment.NewLine;
#pragma warning restore RS1035 // Do not use APIs banned for analyzers

internal static class ExecutionModel
{
internal const string Isolated = "isolated";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ namespace {{FunctionsUtil.GetNamespaceForGeneratedCode(context)}}
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class DirectFunctionExecutor : global::Microsoft.Azure.Functions.Worker.Invocation.IFunctionExecutor
{
private readonly global::Microsoft.Azure.Functions.Worker.IFunctionActivator _functionActivator;{{(defaultExecutorNeeded ? $"{Environment.NewLine} private Lazy<global::Microsoft.Azure.Functions.Worker.Invocation.IFunctionExecutor> _defaultExecutor;" : string.Empty)}}
private readonly global::Microsoft.Azure.Functions.Worker.IFunctionActivator _functionActivator;{{(defaultExecutorNeeded ? $"{Constants.NewLine} private Lazy<global::Microsoft.Azure.Functions.Worker.Invocation.IFunctionExecutor> _defaultExecutor;" : string.Empty)}}
{{GetTypesDictionary(functions)}}
public DirectFunctionExecutor(global::Microsoft.Azure.Functions.Worker.IFunctionActivator functionActivator)
{
Expand All @@ -47,7 +47,7 @@ public DirectFunctionExecutor(global::Microsoft.Azure.Functions.Worker.IFunction
public async global::System.Threading.Tasks.ValueTask ExecuteAsync(global::Microsoft.Azure.Functions.Worker.FunctionContext context)
{
{{GetMethodBody(functions, defaultExecutorNeeded)}}
}{{(defaultExecutorNeeded ? $"{Environment.NewLine}{EmitCreateDefaultExecutorMethod(context)}" : string.Empty)}}
}{{(defaultExecutorNeeded ? $"{Constants.NewLine}{EmitCreateDefaultExecutorMethod(context)}" : string.Empty)}}
}

/// <summary>
Expand Down Expand Up @@ -105,7 +105,7 @@ private static string GetTypesDictionary(IEnumerable<ExecutableFunction> functio
return $$"""
private readonly Dictionary<string, Type> types = new Dictionary<string, Type>()
{
{{string.Join($",{Environment.NewLine} ", typesDict.Select(c => $$""" { "{{c.Key}}", Type.GetType("{{c.Key}}, {{c.Value}}") }"""))}}
{{string.Join($",{Constants.NewLine} ", typesDict.Select(c => $$""" { "{{c.Key}}", Type.GetType("{{c.Key}}, {{c.Value}}") }"""))}}
};

""";
Expand Down Expand Up @@ -147,7 +147,7 @@ private static string GetMethodBody(IEnumerable<ExecutableFunction> functions, b
var inputBindingFeature = context.Features.Get<global::Microsoft.Azure.Functions.Worker.Context.Features.IFunctionInputBindingFeature>();
var inputBindingResult = await inputBindingFeature.BindFunctionInputAsync(context);
var inputArguments = inputBindingResult.Values;
{(anyDefaultExecutor ? $" _defaultExecutor = new Lazy<global::Microsoft.Azure.Functions.Worker.Invocation.IFunctionExecutor>(() => CreateDefaultExecutorInstance(context));{Environment.NewLine}" : string.Empty)}
{(anyDefaultExecutor ? $" _defaultExecutor = new Lazy<global::Microsoft.Azure.Functions.Worker.Invocation.IFunctionExecutor>(() => CreateDefaultExecutorInstance(context));{Constants.NewLine}" : string.Empty)}
""");

foreach (ExecutableFunction function in functions)
Expand Down
5 changes: 5 additions & 0 deletions sdk/Sdk.Generators/Sdk.Generators.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<MinorProductVersion>3</MinorProductVersion>
<PatchProductVersion>4</PatchProductVersion>
<IsRoslynComponent>true</IsRoslynComponent>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup>

<Import Project="..\..\build\Common.props" />
Expand All @@ -35,4 +36,8 @@
<None Include="$(PKGMicrosoft_Bcl_AsyncInterfaces)\lib\netstandard2.0\*.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(PKGSystem_Text_Encodings_Web)\lib\netstandard2.0\*.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>

<ItemGroup>
<None Remove="bin\Debug\netstandard2.0\\Microsoft.Azure.Functions.Worker.Sdk.Generators.dll" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion src/DotNetWorker.Core/Logging/ISystemLogWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ internal interface ISystemLogWriter
/// <param name="state">The entry to be written. Can be also an object.</param>
/// <param name="exception">The exception related to this entry.</param>
/// <param name="formatter"> Function to create a <see cref="System.String"/> message of the state and exception.</param>
void WriteSystemLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter);
void WriteSystemLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter);
}
}
2 changes: 1 addition & 1 deletion src/DotNetWorker.Core/Logging/IUserLogWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ internal interface IUserLogWriter
/// <param name="state">The entry to be written. Can be also an object.</param>
/// <param name="exception">The exception related to this entry.</param>
/// <param name="formatter"> Function to create a <see cref="System.String"/> message of the state and exception.</param>
void WriteUserLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter);
void WriteUserLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter);
}
}
4 changes: 2 additions & 2 deletions src/DotNetWorker.Core/Logging/NullLogWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ private NullLogWriter()
public static NullLogWriter Instance = new NullLogWriter();

/// <inheritdoc/>
public void WriteSystemLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void WriteSystemLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception, string> formatter)
{
}

/// <inheritdoc/>
public void WriteUserLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void WriteUserLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception, string> formatter)
{
}

Expand Down
5 changes: 3 additions & 2 deletions src/DotNetWorker.Core/Logging/WorkerLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ public WorkerLogger(string category, ISystemLogWriter systemLogWriter, IUserLogW
_scopeProvider = scopeProvider;
}

public IDisposable BeginScope<TState>(TState state)
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull
{
// The built-in DI wire-up guarantees that scope provider will be set.
return _scopeProvider.Push(state);
Expand All @@ -33,7 +34,7 @@ public bool IsEnabled(LogLevel logLevel)
return logLevel != LogLevel.None;
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (WorkerMessage.IsSystemLog)
{
Expand Down
6 changes: 3 additions & 3 deletions src/DotNetWorker.Grpc/GrpcFunctionsHostLogWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public GrpcFunctionsHostLogWriter(GrpcHostChannel channel, IOptions<WorkerOption
_serializer = workerOptions.Value.Serializer ?? throw new ArgumentNullException(nameof(workerOptions.Value.Serializer), "Serializer on WorkerOptions cannot be null");
}

public void WriteUserLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void WriteUserLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
Log(RpcLogCategory.User, scopeProvider, categoryName, logLevel, eventId, state, exception, formatter);
}
Expand All @@ -54,12 +54,12 @@ public void WriteUserMetric(IExternalScopeProvider scopeProvider, IDictionary<st
_channelWriter.TryWrite(response);
}

public void WriteSystemLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void WriteSystemLog<TState>(IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
Log(RpcLogCategory.System, scopeProvider, categoryName, logLevel, eventId, state, exception, formatter);
}

public void Log<TState>(RpcLogCategory category, IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void Log<TState>(RpcLogCategory category, IExternalScopeProvider scopeProvider, string categoryName, LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
var response = new StreamingMessage();
var rpcLog = new RpcLog
Expand Down
4 changes: 3 additions & 1 deletion src/DotNetWorker.Grpc/Handlers/InvocationHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,11 @@ public async Task<InvocationResponse> InvokeAsync(InvocationRequest request)
}
catch (Exception ex) when (!ex.IsFatal())
{
#pragma warning disable CS0618 // Type or member is obsolete
response.Result.Exception = _workerOptions.EnableUserCodeException ? ex.ToUserRpcException() : ex.ToRpcException();
response.Result.Status = StatusResult.Types.Status.Failure;
#pragma warning restore CS0618 // Type or member is obsolete

response.Result.Status = StatusResult.Types.Status.Failure;
if (ex.InnerException is TaskCanceledException or OperationCanceledException)
{
response.Result.Status = StatusResult.Types.Status.Cancelled;
Expand Down
2 changes: 1 addition & 1 deletion src/DotNetWorker.Grpc/RpcExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ internal static FunctionDefinition ToFunctionDefinition(this FunctionLoadRequest
/// Returns an RpcException for system exception scenarios.
/// </summary>
/// <returns>An RpcException</returns>
internal static RpcException? ToRpcException(this Exception exception)
internal static RpcException? ToRpcException(this Exception? exception)
{
if (exception is null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<Nullable>disable</Nullable>
</PropertyGroup>

<ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Core.NewtonsoftJson" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.0" />
<PackageReference Include="Moq" Version="4.20.70" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.XUnit" Version="1.1.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.XUnit" Version="1.1.2" />
<PackageReference Include="System.Formats.Asn1" Version="6.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down