Skip to content

Conversation

JamesNK
Copy link
Member

@JamesNK JamesNK commented Apr 28, 2023

Addresses #2108

Adds AuthInterceptorContext.CancellationToken property. The context is passed to call credential interceptors.

This change allows call credentials that do async work to be canceled when the gRPC call is canceled:

var callCredentials = CallCredentials.FromInterceptor(async (context, metadata) =>
{
    metadata["authorize"] = await GetTokenAsync(context.CancellationToken);
});

if (configurator.Interceptor != null)
{
var authInterceptorContext = GrpcProtocolHelpers.CreateAuthInterceptorContext(channel.Address, method);
configurator.CachedContext ??= CreateAuthInterceptorContext(channel.Address, method, cancellationToken);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looked scary at first, but the call sites don't reuse the DefaultCallCredentialsConfigurator for different channel + method + cancellation combos.

Can we make that more obvious somehow so this code doesn't look scary?

e.g.

ReadCredentialMetadata(...)
{
    ReadCredentialMetadataCore(...);
    configurator.CachedContext = null;
}

// Rename current method
ReadCredentialMetadataInner(...)
{
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated comments and renamed some fields to make it clearer what is going on.

await Task.Delay(50);

// Ensure task hasn't been completed.
Assert.False(tcs.Task.IsCompleted);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bit odd. I think in theory the compiler or synccontext could choose to run this asynchronously before it gets here in which case it would be a race.

Generally you would instead use 2 tcs's to ensure order.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the test was fine. The tcs couldn't be completed until after the auth interceptor awaits. The assert was to verify that behavior.

But I agree the test looks a little weird. And it's brittle. I've switched it to use a sync point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants