google-api-dotnet-client: Errors while generating requests after upgrading to .NET 9 on Azure

Environment details

  • Programming language: C#
  • Language runtime version: .NET 9
  • Package version: Google.Apis.PeopleService.v1 v1.68.0.3359 / Google.Apis.Calendar.v3 v1.68.0.3592

Steps to reproduce

  1. Create a new .NET 9 Azure Functions project / bare-bones asp.net core web app and use the sample code (see below)
  2. Deploy it to an Azure functions app / Web app
  3. Trigger the function app / web app

Sample code

using System.Security.Cryptography;
using System.Text.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Http;
using Google.Apis.PeopleService.v1;
using Google.Apis.Services;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace TestGoogleBatches;

public class TestBatches
{
    private const string Email = "<service account email>";
    private const string RsaParameters = "<rsa parameters>";
    
    private readonly ILogger<TestBatches> _logger;

    public TestBatches(ILogger<TestBatches> logger)
    {
        _logger = logger;
    }

    [Function("TestBatches")]
    public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
    {
        _logger.LogInformation("C# HTTP trigger function processed a request.");

        var parameters =
            JsonSerializer.Deserialize<RSAParameters>(RsaParameters,
                new JsonSerializerOptions { IncludeFields = true });
        
        var rsa = RSA.Create(parameters);

        var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(Email)
        {
            Key = rsa,
            Scopes = new[] { PeopleServiceService.ScopeConstants.DirectoryReadonly },
            User = "<test user>"
        };
        
        var initializer = new BaseClientService.Initializer
        {
            HttpClientInitializer = new ServiceAccountCredential(serviceAccountCredentialInitializer)
        };
        
        var searchRequest = new PeopleServiceService(initializer).People.SearchDirectoryPeople();
        
        searchRequest.Query = "<query>";
        searchRequest.ReadMask = "photos,emailAddresses";
        searchRequest.Sources = PeopleResource
            .SearchDirectoryPeopleRequest
            .SourcesEnum
            .DIRECTORYSOURCETYPEDOMAINPROFILE;
        searchRequest.PageSize = 10;
        
        var response = await searchRequest.ExecuteAsync();
        _logger.LogInformation(JsonSerializer.Serialize(response));

        return new OkObjectResult($"Welcome to Azure Functions! Received {response.People.Count} people");
    }
}

Stack trace

For the sample code above we’ve got the following

   at System.Collections.Generic.Dictionary`2.FindValue(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at Google.Apis.Requests.ClientServiceRequest`1.AddParameters(RequestBuilder requestBuilder, ParameterCollection inputParameters)
   at Google.Apis.Requests.ClientServiceRequest`1.CreateBuilder()
   at Google.Apis.Requests.ClientServiceRequest`1.CreateRequest(Nullable`1 overrideGZipEnabled)
   at Google.Apis.Requests.ClientServiceRequest`1.ExecuteUnparsedAsync(CancellationToken cancellationToken)
   at Google.Apis.Requests.ClientServiceRequest`1.ExecuteAsync(CancellationToken cancellationToken)
   at Google.Apis.Requests.ClientServiceRequest`1.ExecuteAsync()
   at TestGoogleBatches.TestBatches.Run(HttpRequest req) in D:\Projects\_something\TestGoogleBatches\TestGoogleBatches\TestBatches.cs:line 59
   at TestGoogleBatches.DirectFunctionExecutor.ExecuteAsync(FunctionContext context) in D:\Projects\_something\TestGoogleBatches\TestGoogleBatches\obj\Release\net9.0\Microsoft.Azure.Functions.Worker.Sdk.Generators\Microsoft.Azure.Functions.Worker.Sdk.Generators.FunctionExecutorGenerator\GeneratedFunctionExecutor.g.cs:line 38
   at Microsoft.Azure.Functions.Worker.OutputBindings.OutputBindingsMiddleware.Invoke(FunctionContext context, FunctionExecutionDelegate next) in D:\a\_work\1\s\src\DotNetWorker.Core\OutputBindings\OutputBindingsMiddleware.cs:line 13
   at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.FunctionsHttpProxyingMiddleware.Invoke(FunctionContext context, FunctionExecutionDelegate next) in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\FunctionsMiddleware\FunctionsHttpProxyingMiddleware.cs:line 54
   at Microsoft.Azure.Functions.Worker.FunctionsApplication.InvokeFunctionAsync(FunctionContext context) in D:\a\_work\1\s\src\DotNetWorker.Core\FunctionsApplication.cs:line 96
   at Microsoft.Azure.Functions.Worker.Handlers.InvocationHandler.InvokeAsync(InvocationRequest request) in D:\a\_work\1\s\src\DotNetWorker.Grpc\Handlers\InvocationHandler.cs:line 89

We also experienced the issue for another request, namely the CalendarService.Events.Watch:

Parameter validation failed for "calendarId" : The parameter value must be a non-empty string
Exception: The service calendar has thrown an exception.
No HttpStatusCode was specified.
No error details were specified.
Google.GoogleApiException: Parameter validation failed for "calendarId" : The parameter value must be a non-empty string
   at Google.Apis.Requests.ClientServiceRequest`1.AddParameters(RequestBuilder requestBuilder, ParameterCollection inputParameters)
   at Google.Apis.Requests.ClientServiceRequest`1.CreateBuilder()
   at Google.Apis.Requests.ClientServiceRequest`1.CreateRequest(Nullable`1 overrideGZipEnabled)
   at Google.Apis.Requests.BatchRequest.CreateIndividualRequest(IClientServiceRequest request)
   at Google.Apis.Requests.BatchRequest.CreateOuterRequestContent(IEnumerable`1 requests)
   at Google.Apis.Requests.BatchRequest.ExecuteAsync(CancellationToken cancellationToken)

Few notes

  • we realise that it might well be the “MS bug” and not the “Google bug” (whoa, we just created a clash of 2 tech giants here)
  • it works perfectly on the .NET 8, i.e. the only change i need to make to make it work is <TargetFramework>net8.0</TargetFramework> opposed to <TargetFramework>net9.0</TargetFramework> in the csproj file.
  • we tried to do some remote debugging and we couldn’t find anything which would help us to pinpoint the issue further
    • except that we had some quantum effects and after spending some time with attached debugger the issue disappeared and that dictionary was filled correctly
  • originally we noticed that issue while doing batch requests but then it turned out that it’s reproducible in a “single request” mode (that’s why the 2nd example mentions BatchRequest).

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 16 (1 by maintainers)

Commits related to this issue

Most upvoted comments

Dropping by just to add some context in case other people run into this: it’s indeed a .NET 9 bug that isn’t fixed as of .NET 9.0.101.

For reference: https://github.com/dotnet/runtime/issues/108969 and https://github.com/dotnet/runtime/pull/109143

In the meantime, you can workaround this by (re)enabling tiered compilation <TieredCompilation>true</TieredCompilation> or setting the environment variable DOTNET_JitEnablePhysicalPromotion=0.

In our case, we were running a standard desktop app using the Google.Apis.Sheets.v4 API, and it couldn’t connect with this error: Importing google sheet failed: Parameter validation failed for "spreadsheetId" : The parameter value must be a non-empty string

@jskeet We’ve further isolated this, see here:

dotnet/aspnetcore#59341

So, as you suggested, it’s not specific to this library. I guess we can go ahead and close it @stukalin .

Just in case this helps anyone via Google search we’ve run into the exact same problem when upgrading to dotnet9.

Our exception was:-

The service bigquery has thrown an exception.
No HttpStatusCode was specified.
No error details were specified.
Google.GoogleApiException: Parameter validation failed for "tableId" : The parameter value must be a non-empty string
   at Google.Apis.Requests.ClientServiceRequest`1.AddParameters(RequestBuilder requestBuilder, ParameterCollection inputParameters)
   at Google.Apis.Requests.ClientServiceRequest`1.CreateBuilder()
   at Google.Apis.Requests.ClientServiceRequest`1.CreateRequest(Nullable`1 overrideGZipEnabled)
   at Google.Apis.Requests.ClientServiceRequest`1.ExecuteUnparsedAsync(CancellationToken cancellationToken)
   at Google.Apis.Requests.ClientServiceRequest`1.Execute()
   at Google.Cloud.BigQuery.V2.BigQueryClientImpl.GetTable(TableReference tableReference, GetTableOptions options)
   at REDACTED
   at REDACTED
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at REDACTED

We fixed it via web.config:-

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <aspNetCore>
      <environmentVariables>
        <environmentVariable name="DOTNET_JitEnablePhysicalPromotion" value="0"/>
      </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

Great, thanks very much for doing all the digging! (I’ll close this now, but we can reopen it if necessary of course.)

@jskeet We’ve further isolated this, see here:

https://github.com/dotnet/aspnetcore/issues/59341

So, as you suggested, it’s not specific to this library. I guess we can go ahead and close it @stukalin .

I’d also note that if this looks like it’s a bug in .NET 9 in some scenarios, while this may fix the immediate problem, it’s highly likely there’ll be other similar issues elsewhere. That’s why I really want to make sure I understand the problem rather than just chalking it up to “hey, this looks like it might fix it”.

We’ll want to understand the change before merging it - please give us a bit of time to have a look at things. Note that once this is merged, releasing the support libraries is non-trivial (not hard, but not “free” either). We’ll try to get this in before the next release freeze though.

Okay, thanks. We’ll have a look when we can, but I don’t expect us to have significant amounts of time to put into this very soon.