-
Notifications
You must be signed in to change notification settings - Fork 832
Expand file tree
/
Copy pathServerCallHandlerBase.cs
More file actions
224 lines (195 loc) · 8.82 KB
/
ServerCallHandlerBase.cs
File metadata and controls
224 lines (195 loc) · 8.82 KB
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
#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.Diagnostics.CodeAnalysis;
using Grpc.Core;
using Grpc.Shared.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
#if NET8_0_OR_GREATER
using Microsoft.AspNetCore.Http.Timeouts;
#endif
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Grpc.AspNetCore.Server.Internal.CallHandlers;
internal abstract class ServerCallHandlerBase<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse>
where TService : class
where TRequest : class
where TResponse : class
{
private const string LoggerName = "Grpc.AspNetCore.Server.ServerCallHandler";
protected ServerMethodInvokerBase<TService, TRequest, TResponse> MethodInvoker { get; }
protected ILogger Logger { get; }
protected ServerCallHandlerBase(
ServerMethodInvokerBase<TService, TRequest, TResponse> methodInvoker,
ILoggerFactory loggerFactory)
{
MethodInvoker = methodInvoker;
Logger = loggerFactory.CreateLogger(LoggerName);
}
public Task HandleCallAsync(HttpContext httpContext)
{
if (GrpcProtocolHelpers.IsInvalidContentType(httpContext, out var error))
{
return ProcessInvalidContentTypeRequest(httpContext, error);
}
if (!GrpcProtocolConstants.IsHttp2(httpContext.Request.Protocol)
&& !GrpcProtocolConstants.IsHttp3(httpContext.Request.Protocol))
{
return ProcessNonHttp2Request(httpContext);
}
var serverCallContext = new HttpContextServerCallContext(httpContext, MethodInvoker.Options, typeof(TRequest), typeof(TResponse), Logger);
httpContext.Features.Set<IServerCallContextFeature>(serverCallContext);
GrpcProtocolHelpers.AddProtocolHeaders(httpContext.Response);
try
{
serverCallContext.Initialize();
var handleCallTask = HandleCallAsyncCore(httpContext, serverCallContext);
if (handleCallTask.IsCompletedSuccessfully)
{
return serverCallContext.EndCallAsync();
}
else
{
return AwaitHandleCall(serverCallContext, handleCallTask);
}
}
catch (Exception ex)
{
// Enhanced exception handling for deserialization errors
return HandleCallExceptionAsync(serverCallContext, ex);
}
static async Task AwaitHandleCall(HttpContextServerCallContext serverCallContext, Task handleCall)
{
try
{
await handleCall;
await serverCallContext.EndCallAsync();
}
catch (Exception ex)
{
await HandleCallExceptionAsync(serverCallContext, ex);
}
}
}
protected abstract Task HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext);
/// <summary>
/// This should only be called from client streaming calls
/// </summary>
/// <param name="httpContext"></param>
protected void DisableMinRequestBodyDataRateAndMaxRequestBodySize(HttpContext httpContext)
{
var minRequestBodyDataRateFeature = httpContext.Features.Get<IHttpMinRequestBodyDataRateFeature>();
if (minRequestBodyDataRateFeature != null)
{
minRequestBodyDataRateFeature.MinDataRate = null;
}
var maxRequestBodySizeFeature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
if (maxRequestBodySizeFeature != null)
{
if (!maxRequestBodySizeFeature.IsReadOnly)
{
maxRequestBodySizeFeature.MaxRequestBodySize = null;
}
else
{
// IsReadOnly could be true if middleware has already started reading the request body
// In that case we can't disable the max request body size for the request stream
GrpcServerLog.UnableToDisableMaxRequestBodySize(Logger);
}
}
}
#if NET8_0_OR_GREATER
protected void DisableRequestTimeout(HttpContext httpContext)
{
// Disable global request timeout on streaming methods.
var requestTimeoutFeature = httpContext.Features.Get<IHttpRequestTimeoutFeature>();
if (requestTimeoutFeature is not null)
{
// Don't disable if the endpoint has explicit timeout metadata.
var endpoint = httpContext.GetEndpoint();
if (endpoint is not null)
{
if (endpoint.Metadata.GetMetadata<RequestTimeoutAttribute>() is not null ||
endpoint.Metadata.GetMetadata<RequestTimeoutPolicy>() is not null)
{
return;
}
}
requestTimeoutFeature.DisableTimeout();
}
}
#endif
/// <summary>
/// Handles exceptions that occur during call processing, with special handling for deserialization cancellations.
/// </summary>
private static Task HandleCallExceptionAsync(HttpContextServerCallContext serverCallContext, Exception ex)
{
// If it's already an RpcException, let the existing logic handle it
if (ex is RpcException rpcEx)
{
return serverCallContext.ProcessHandlerErrorAsync(rpcEx, serverCallContext.Method);
}
// Convert specific exception types to proper RpcExceptions
var convertedException = ConvertToRpcException(ex, serverCallContext);
return serverCallContext.ProcessHandlerErrorAsync(convertedException, serverCallContext.Method);
}
/// <summary>
/// Converts framework exceptions to appropriate RpcExceptions.
/// </summary>
private static RpcException ConvertToRpcException(Exception ex, HttpContextServerCallContext _)
{
return ex switch
{
OperationCanceledException _ when _.HttpContext.RequestAborted.IsCancellationRequested =>
new RpcException(new Status(StatusCode.Cancelled, "Call canceled by the client.", ex)),
IOException ioEx when IsConnectionResetException(ioEx) =>
new RpcException(new Status(StatusCode.Cancelled, "Client disconnected.", ex)),
_ => new RpcException(new Status(StatusCode.Unknown, "Error processing call.", ex))
};
}
private static bool IsConnectionResetException(IOException ex)
{
return ex.Message.Contains("reset", StringComparison.OrdinalIgnoreCase) ||
ex.Message.Contains("aborted", StringComparison.OrdinalIgnoreCase) ||
ex.Message.Contains("disconnect", StringComparison.OrdinalIgnoreCase);
}
private Task ProcessNonHttp2Request(HttpContext httpContext)
{
GrpcServerLog.UnsupportedRequestProtocol(Logger, httpContext.Request.Protocol);
var protocolError = $"Request protocol '{httpContext.Request.Protocol}' is not supported.";
GrpcProtocolHelpers.BuildHttpErrorResponse(httpContext.Response, StatusCodes.Status426UpgradeRequired, StatusCode.Internal, protocolError);
httpContext.Response.Headers[HeaderNames.Upgrade] = GrpcProtocolConstants.Http2Protocol;
return Task.CompletedTask;
}
private Task ProcessInvalidContentTypeRequest(HttpContext httpContext, string error)
{
// This might be a CORS preflight request and CORS middleware hasn't been configured
if (GrpcProtocolHelpers.IsCorsPreflightRequest(httpContext))
{
GrpcServerLog.UnhandledCorsPreflightRequest(Logger);
GrpcProtocolHelpers.BuildHttpErrorResponse(httpContext.Response, StatusCodes.Status405MethodNotAllowed, StatusCode.Internal, "Unhandled CORS preflight request received. CORS may not be configured correctly in the application.");
httpContext.Response.Headers[HeaderNames.Allow] = HttpMethods.Post;
return Task.CompletedTask;
}
else
{
GrpcServerLog.UnsupportedRequestContentType(Logger, httpContext.Request.ContentType);
GrpcProtocolHelpers.BuildHttpErrorResponse(httpContext.Response, StatusCodes.Status415UnsupportedMediaType, StatusCode.Internal, error);
return Task.CompletedTask;
}
}
}