-
Notifications
You must be signed in to change notification settings - Fork 765
/
HttpContextServerCallContext.cs
544 lines (461 loc) · 19.9 KB
/
HttpContextServerCallContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Shared;
using Grpc.Shared.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
namespace Grpc.AspNetCore.Server.Internal
{
internal sealed partial class HttpContextServerCallContext : ServerCallContext, IServerCallContextFeature
{
private static readonly AuthContext UnauthenticatedContext = new AuthContext(null, new Dictionary<string, List<AuthProperty>>());
private string? _peer;
private Metadata? _requestHeaders;
private Metadata? _responseTrailers;
private Status _status;
private AuthContext? _authContext;
private Activity? _activity;
// Internal for tests
internal ServerCallDeadlineManager? DeadlineManager;
private HttpContextSerializationContext? _serializationContext;
private DefaultDeserializationContext? _deserializationContext;
internal HttpContextServerCallContext(HttpContext httpContext, MethodOptions options, Type requestType, Type responseType, ILogger logger)
{
HttpContext = httpContext;
Options = options;
RequestType = requestType;
ResponseType = responseType;
Logger = logger;
}
internal ILogger Logger { get; }
internal HttpContext HttpContext { get; }
internal MethodOptions Options { get; }
internal Type RequestType { get; }
internal Type ResponseType { get; }
internal string? ResponseGrpcEncoding { get; private set; }
internal HttpContextSerializationContext SerializationContext
{
get => _serializationContext ??= new HttpContextSerializationContext(this);
}
internal DefaultDeserializationContext DeserializationContext
{
get => _deserializationContext ??= new DefaultDeserializationContext();
}
internal bool HasResponseTrailers => _responseTrailers != null;
protected override string MethodCore => HttpContext.Request.Path.Value!;
protected override string HostCore => HttpContext.Request.Host.Value;
protected override string? PeerCore
{
get
{
// Follows the standard at https://github.com/grpc/grpc/blob/master/doc/naming.md
if (_peer == null)
{
var connection = HttpContext.Connection;
if (connection.RemoteIpAddress != null)
{
switch (connection.RemoteIpAddress.AddressFamily)
{
case AddressFamily.InterNetwork:
_peer = "ipv4:" + connection.RemoteIpAddress + ":" + connection.RemotePort;
break;
case AddressFamily.InterNetworkV6:
_peer = "ipv6:[" + connection.RemoteIpAddress + "]:" + connection.RemotePort;
break;
default:
// TODO(JamesNK) - Test what should be output when used with UDS and named pipes
_peer = "unknown:" + connection.RemoteIpAddress + ":" + connection.RemotePort;
break;
}
}
}
return _peer;
}
}
protected override DateTime DeadlineCore => DeadlineManager?.Deadline ?? DateTime.MaxValue;
protected override Metadata RequestHeadersCore
{
get
{
if (_requestHeaders == null)
{
_requestHeaders = new Metadata();
foreach (var header in HttpContext.Request.Headers)
{
if (GrpcProtocolHelpers.ShouldSkipHeader(header.Key))
{
continue;
}
if (header.Key.EndsWith(Metadata.BinaryHeaderSuffix, StringComparison.OrdinalIgnoreCase))
{
_requestHeaders.Add(header.Key, GrpcProtocolHelpers.ParseBinaryHeader(header.Value));
}
else
{
_requestHeaders.Add(header.Key, header.Value);
}
}
}
return _requestHeaders;
}
}
internal Task ProcessHandlerErrorAsync(Exception ex, string method)
{
if (DeadlineManager == null)
{
ProcessHandlerError(ex, method);
return Task.CompletedTask;
}
// Could have a fast path for no deadline being raised when an error happens,
// but it isn't worth the complexity.
return ProcessHandlerErrorAsyncCore(ex, method);
}
private async Task ProcessHandlerErrorAsyncCore(Exception ex, string method)
{
Debug.Assert(DeadlineManager != null, "Deadline manager should have been created.");
if (!DeadlineManager.TrySetCallComplete())
{
await DeadlineManager.WaitDeadlineCompleteAsync();
}
try
{
ProcessHandlerError(ex, method);
}
finally
{
await DeadlineManager.DisposeAsync();
GrpcServerLog.DeadlineStopped(Logger);
}
}
private void ProcessHandlerError(Exception ex, string method)
{
if (ex is RpcException rpcException)
{
GrpcServerLog.RpcConnectionError(Logger, rpcException.StatusCode, ex);
// There are two sources of metadata entries on the server-side:
// 1. serverCallContext.ResponseTrailers
// 2. trailers in RpcException thrown by user code in server side handler.
// As metadata allows duplicate keys, the logical thing to do is
// to just merge trailers from RpcException into serverCallContext.ResponseTrailers.
foreach (var entry in rpcException.Trailers)
{
ResponseTrailers.Add(entry);
}
_status = rpcException.Status;
}
else
{
GrpcServerLog.ErrorExecutingServiceMethod(Logger, method, ex);
var message = ErrorMessageHelper.BuildErrorMessage("Exception was thrown by handler.", ex, Options.EnableDetailedErrors);
// Note that the exception given to status won't be returned to the client.
// It is still useful to set in case an interceptor accesses the status on the server.
_status = new Status(StatusCode.Unknown, message, ex);
}
// Don't update trailers if request has exceeded deadline
if (DeadlineManager == null || !DeadlineManager.IsDeadlineExceededStarted)
{
HttpContext.Response.ConsolidateTrailers(this);
}
DeadlineManager?.SetCallEnded();
LogCallEnd();
}
// If there is a deadline then we need to have our own cancellation token.
// Deadline will call CompleteAsync, then Reset/Abort. This order means RequestAborted
// is not raised, so deadlineCts will be triggered instead.
protected override CancellationToken CancellationTokenCore => DeadlineManager?.CancellationToken ?? HttpContext.RequestAborted;
protected override Metadata ResponseTrailersCore
{
get
{
if (_responseTrailers == null)
{
_responseTrailers = new Metadata();
}
return _responseTrailers;
}
}
protected override Status StatusCore
{
get => _status;
set => _status = value;
}
internal Task EndCallAsync()
{
if (DeadlineManager == null)
{
EndCallCore();
return Task.CompletedTask;
}
else if (DeadlineManager.TrySetCallComplete())
{
// Fast path when deadline hasn't been raised.
EndCallCore();
GrpcServerLog.DeadlineStopped(Logger);
return DeadlineManager.DisposeAsync().AsTask();
}
// Deadline is exceeded
return EndCallAsyncCore();
}
private async Task EndCallAsyncCore()
{
Debug.Assert(DeadlineManager != null, "Deadline manager should have been created.");
try
{
// Deadline has started
await DeadlineManager.WaitDeadlineCompleteAsync();
EndCallCore();
DeadlineManager.SetCallEnded();
GrpcServerLog.DeadlineStopped(Logger);
}
finally
{
await DeadlineManager.DisposeAsync();
}
}
private void EndCallCore()
{
// Don't update trailers if request has exceeded deadline
if (DeadlineManager == null || !DeadlineManager.IsDeadlineExceededStarted)
{
HttpContext.Response.ConsolidateTrailers(this);
}
LogCallEnd();
}
private void LogCallEnd()
{
if (_activity != null)
{
_activity.AddTag(GrpcServerConstants.ActivityStatusCodeTag, _status.StatusCode.ToTrailerString());
}
if (_status.StatusCode != StatusCode.OK)
{
GrpcEventSource.Log.CallFailed(_status.StatusCode);
}
GrpcEventSource.Log.CallStop();
}
protected override WriteOptions? WriteOptionsCore { get; set; }
protected override AuthContext AuthContextCore
{
get
{
if (_authContext == null)
{
var clientCertificate = HttpContext.Connection.ClientCertificate;
if (clientCertificate == null)
{
_authContext = UnauthenticatedContext;
}
else
{
_authContext = GrpcProtocolHelpers.CreateAuthContext(clientCertificate);
}
}
return _authContext;
}
}
public ServerCallContext ServerCallContext => this;
protected override IDictionary<object, object> UserStateCore => HttpContext.Items!;
internal bool HasBufferedMessage { get; set; }
protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions options)
{
// TODO(JunTaoLuo, JamesNK): Currently blocked on ContextPropagationToken implementation in Grpc.Core.Api
// https://github.com/grpc/grpc-dotnet/issues/40
throw new NotImplementedException("CreatePropagationToken will be implemented in a future version.");
}
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders)
{
// Headers can only be written once. Throw on subsequent call to write response header instead of silent no-op.
if (HttpContext.Response.HasStarted)
{
throw new InvalidOperationException("Response headers can only be sent once per call.");
}
if (responseHeaders != null)
{
foreach (var entry in responseHeaders)
{
if (entry.Key == GrpcProtocolConstants.CompressionRequestAlgorithmHeader)
{
// grpc-internal-encoding-request is used in the server to set message compression
// on a per-call bassis.
// 'grpc-encoding' is sent even if WriteOptions.Flags = NoCompress. In that situation
// individual messages will not be written with compression.
ResponseGrpcEncoding = entry.Value;
HttpContext.Response.Headers[GrpcProtocolConstants.MessageEncodingHeader] = ResponseGrpcEncoding;
}
else
{
var encodedValue = entry.IsBinary ? Convert.ToBase64String(entry.ValueBytes) : entry.Value;
HttpContext.Response.Headers.Append(entry.Key, encodedValue);
}
}
}
return HttpContext.Response.BodyWriter.FlushAsync().GetAsTask();
}
// Clock is for testing
public void Initialize(ISystemClock? clock = null)
{
_activity = GetHostActivity();
if (_activity != null)
{
_activity.AddTag(GrpcServerConstants.ActivityMethodTag, MethodCore);
}
GrpcEventSource.Log.CallStart(MethodCore);
var timeout = GetTimeout();
if (timeout != TimeSpan.Zero)
{
DeadlineManager = new ServerCallDeadlineManager(this, clock ?? SystemClock.Instance, timeout);
GrpcServerLog.DeadlineStarted(Logger, timeout);
}
var serviceDefaultCompression = Options.ResponseCompressionAlgorithm;
if (serviceDefaultCompression != null &&
!GrpcProtocolConstants.IsGrpcEncodingIdentity(serviceDefaultCompression) &&
IsEncodingInRequestAcceptEncoding(serviceDefaultCompression))
{
ResponseGrpcEncoding = serviceDefaultCompression;
}
// grpc-encoding response header is optional and is inferred as 'identity' when not present.
// Only write a non-identity value for performance.
if (ResponseGrpcEncoding != null)
{
HttpContext.Response.Headers[GrpcProtocolConstants.MessageEncodingHeader] = ResponseGrpcEncoding;
}
}
private Activity? GetHostActivity()
{
var activity = Activity.Current;
while (activity != null)
{
// We only want to add gRPC metadata to the host activity
// Search parent activities in case a new activity was started in middleware before gRPC endpoint is invoked
if (string.Equals(activity.OperationName, GrpcServerConstants.HostActivityName, StringComparison.Ordinal))
{
return activity;
}
activity = activity.Parent;
}
return null;
}
private TimeSpan GetTimeout()
{
if (HttpContext.Request.Headers.TryGetValue(GrpcProtocolConstants.TimeoutHeader, out var values))
{
if (GrpcProtocolHelpers.TryDecodeTimeout(values, out var timeout) &&
timeout > TimeSpan.Zero)
{
if (timeout.Ticks > GrpcProtocolConstants.MaxDeadlineTicks)
{
GrpcServerLog.DeadlineTimeoutTooLong(Logger, timeout);
timeout = TimeSpan.FromTicks(GrpcProtocolConstants.MaxDeadlineTicks);
}
return timeout;
}
GrpcServerLog.InvalidTimeoutIgnored(Logger, values);
}
return TimeSpan.Zero;
}
internal async Task DeadlineExceededAsync()
{
GrpcServerLog.DeadlineExceeded(Logger, GetTimeout());
GrpcEventSource.Log.CallDeadlineExceeded();
var status = new Status(StatusCode.DeadlineExceeded, "Deadline Exceeded");
var trailersDestination = GrpcProtocolHelpers.GetTrailersDestination(HttpContext.Response);
GrpcProtocolHelpers.SetStatus(trailersDestination, status);
_status = status;
// Immediately send remaining response content and trailers
// If feature is null then reset/abort will still end request, but response won't have trailers
var completionFeature = HttpContext.Features.Get<IHttpResponseBodyFeature>();
if (completionFeature != null)
{
await completionFeature.CompleteAsync();
}
// HttpResetFeature should always be set on context,
// but in case it isn't, fall back to HttpContext.Abort.
// Abort will send error code INTERNAL_ERROR instead of NO_ERROR.
var resetFeature = HttpContext.Features.Get<IHttpResetFeature>();
if (resetFeature != null)
{
GrpcServerLog.ResettingResponse(Logger, GrpcProtocolConstants.ResetStreamNoError);
resetFeature.Reset(GrpcProtocolConstants.ResetStreamNoError);
}
else
{
// Note that some clients will fail with error code INTERNAL_ERROR.
GrpcServerLog.AbortingResponse(Logger);
HttpContext.Abort();
}
}
internal string? GetRequestGrpcEncoding()
{
if (HttpContext.Request.Headers.TryGetValue(GrpcProtocolConstants.MessageEncodingHeader, out var values))
{
return values;
}
return null;
}
internal bool IsEncodingInRequestAcceptEncoding(string encoding)
{
if (HttpContext.Request.Headers.TryGetValue(GrpcProtocolConstants.MessageAcceptEncodingHeader, out var values))
{
var acceptEncoding = values.ToString().AsSpan();
while (true)
{
var separatorIndex = acceptEncoding.IndexOf(',');
ReadOnlySpan<char> segment;
if (separatorIndex != -1)
{
segment = acceptEncoding.Slice(0, separatorIndex);
acceptEncoding = acceptEncoding.Slice(separatorIndex + 1);
}
else
{
segment = acceptEncoding;
}
// Check segment
if (segment.SequenceEqual(encoding))
{
return true;
}
if (separatorIndex == -1)
{
break;
}
}
// Check remainder
if (acceptEncoding.SequenceEqual(encoding))
{
return true;
}
}
return false;
}
internal void ValidateAcceptEncodingContainsResponseEncoding()
{
var resolvedResponseGrpcEncoding = ResponseGrpcEncoding ?? GrpcProtocolConstants.IdentityGrpcEncoding;
if (!IsEncodingInRequestAcceptEncoding(resolvedResponseGrpcEncoding))
{
GrpcServerLog.EncodingNotInAcceptEncoding(Logger, resolvedResponseGrpcEncoding);
}
}
}
}