-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathGrpcUtils.cs
More file actions
294 lines (262 loc) · 12.6 KB
/
GrpcUtils.cs
File metadata and controls
294 lines (262 loc) · 12.6 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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Grpc.Core;
using ServiceStack.Text;
namespace ServiceStack
{
public static class GrpcUtils
{
public static Task<TResponse> Execute<TRequest, TResponse>(this Channel channel, TRequest request,
string servicesName, string methodName,
CallOptions options = default, string host = null)
where TRequest : class
where TResponse : class
=> Execute<TRequest, TResponse>(new DefaultCallInvoker(channel), request, servicesName, methodName, options,
host);
public static async Task<TResponse> Execute<TRequest, TResponse>(this CallInvoker invoker, TRequest request,
string servicesName, string methodName,
CallOptions options = default, string host = null)
where TRequest : class
where TResponse : class
{
var method = new Method<TRequest, TResponse>(MethodType.Unary, servicesName, methodName,
GrpcMarshaller<TRequest>.Instance, GrpcMarshaller<TResponse>.Instance);
using (var auc = invoker.AsyncUnaryCall(method, host, options, request))
{
return await auc.ResponseAsync.ConfigAwait();
}
}
public static HttpClientHandler AddPemCertificate(this HttpClientHandler handler, X509Certificate2 cert,
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>
serverCertificateCustomValidationCallback = null)
{
handler.ClientCertificates.Add(cert);
if (serverCertificateCustomValidationCallback != null)
handler.ServerCertificateCustomValidationCallback = serverCertificateCustomValidationCallback;
return handler;
}
public static HttpClientHandler AddPemCertificateFromFile(this HttpClientHandler handler, string fileName,
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> serverCertificateCustomValidationCallback = null) =>
handler.AddPemCertificate(new X509Certificate2(fileName), serverCertificateCustomValidationCallback);
public static HttpClientHandler AllowSelfSignedCertificatesFrom(this HttpClientHandler handler, string dnsName)
{
handler.ServerCertificateCustomValidationCallback = AllowSelfSignedCertificatesFrom(dnsName);
return handler;
}
public static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> AllowSelfSignedCertificatesFrom(string dnsName) =>
(req, cert, certChain, sslPolicyErrors) =>
cert.SubjectName.RawData.SequenceEqual(cert.IssuerName.RawData) && // self-signed
cert.GetNameInfo(X509NameType.DnsName, forIssuer: false) == dnsName &&
(sslPolicyErrors & ~SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.None; // only this
public static void Set(this Metadata headers, string name, string value)
{
for (var i = 0; i < headers.Count; i++)
{
var entry = headers[i];
if (entry.Key.EqualsIgnoreCase(name))
{
headers.RemoveAt(i);
break;
}
}
headers.Add(name, value);
}
public static CallOptions Init(this CallOptions options, GrpcClientConfig config, bool noAuth)
{
var auth = noAuth
? null
: !string.IsNullOrEmpty(config.UserName) && !string.IsNullOrEmpty(config.Password)
? "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(config.UserName + ":" + config.Password))
: !string.IsNullOrEmpty(config.BearerToken)
? "Bearer " + config.BearerToken
: !string.IsNullOrEmpty(config.SessionId)
? nameof(config.SessionId)
: null;
if (config.Headers.Count > 0 || auth != null || config.UserAgent != null)
{
var headers = options.Headers;
if (headers == null)
options = options.WithHeaders(headers = new Metadata());
foreach (var entry in config.Headers)
{
headers.Add(entry);
}
if (auth != null)
{
if (auth == nameof(config.SessionId))
headers.Set(GrpcClientConfig.Keywords.HeaderSessionId, config.SessionId);
else
headers.Set(HttpHeaders.Authorization, auth);
}
if (config.UserAgent != null)
headers.Set(HttpHeaders.UserAgent, config.UserAgent);
}
return options;
}
public static bool InitRequestDto(GrpcClientConfig config, object requestDto)
{
config.PopulateRequestMetadata(requestDto);
var authIncluded = !string.IsNullOrEmpty((requestDto is IHasBearerToken hasBearerToken ? hasBearerToken.BearerToken : null) ??
(requestDto is IHasSessionId hasSessionId ? hasSessionId.SessionId : null));
return authIncluded;
}
public static async Task<(TResponse, ResponseStatus, Metadata)> GetResponseAsync<TResponse>(GrpcClientConfig config, AsyncUnaryCall<TResponse> auc)
{
var headers = await auc.ResponseHeadersAsync.ConfigAwait();
object status = null;
ResponseStatus typedStatus = null;
string errorCode = null;
string message = null;
TResponse response = default;
try
{
response = await auc.ResponseAsync.ConfigAwait();
status = response.GetResponseStatus();
if (response is AuthenticateResponse authResponse)
{
if (!string.IsNullOrEmpty(authResponse.BearerToken))
config.BearerToken = authResponse.BearerToken;
else if (!string.IsNullOrEmpty(authResponse.SessionId))
config.SessionId = authResponse.SessionId;
}
}
catch (RpcException ex)
{
var statusBytes = ResponseCallContext.GetHeaderBytes(headers, GrpcClientConfig.Keywords.GrpcResponseStatus);
status = statusBytes != null
? GrpcServiceStack.ParseResponseStatus(statusBytes)
: new ResponseStatus {
ErrorCode = errorCode = ex.Status.Detail ?? ex.StatusCode.ToString(),
Message = message = HttpStatus.GetStatusDescription(ResponseCallContext.GetHttpStatus(headers))
};
typedStatus = status as ResponseStatus;
if (typedStatus != null && string.IsNullOrEmpty(typedStatus.Message))
{
typedStatus.ErrorCode = errorCode = ex.StatusCode.ToString();
typedStatus.Message = message = ex.Status.Detail;
}
var prop = TypeProperties<TResponse>.GetAccessor(nameof(IHasResponseStatus.ResponseStatus));
if (prop != null)
{
response = typeof(TResponse).CreateInstance<TResponse>();
if (prop.PropertyInfo.PropertyType.IsInstanceOfType(status))
{
prop.PublicSetter(response, status);
}
else
{
// Protoc clients generate different ResponseStatus DTO
var propStatus = status.ConvertTo(prop.PropertyInfo.PropertyType);
prop.PublicSetter(response, propStatus);
}
}
}
finally
{
await InvokeResponseFiltersAsync(config, auc, response).ConfigAwait();
}
if (typedStatus == null)
typedStatus = status as ResponseStatus;
if (typedStatus == null && status != null)
{
typedStatus = new ResponseStatus {
ErrorCode = errorCode ?? TypeProperties.Get(status.GetType()).GetPublicGetter(nameof(ResponseStatus.ErrorCode))(status) as string,
Message = message ?? TypeProperties.Get(status.GetType()).GetPublicGetter(nameof(ResponseStatus.Message))(status) as string,
};
}
return (response, typedStatus, headers);
}
public static async Task<Metadata> InvokeResponseFiltersAsync<TResponse>(GrpcClientConfig config, AsyncUnaryCall<TResponse> auc, TResponse response, Action<ResponseCallContext> fn = null)
{
var headers = await auc.ResponseHeadersAsync.ConfigAwait();
if (GrpcClientConfig.GlobalResponseFilter != null || config.ResponseFilter != null)
{
var ctx = new ResponseCallContext(response, auc.GetStatus(), headers);
fn?.Invoke(ctx);
GrpcClientConfig.GlobalResponseFilter?.Invoke(ctx);
config.ResponseFilter?.Invoke(ctx);
}
return headers;
}
public static async Task<Metadata> InvokeResponseFiltersAsync<TResponse>(GrpcClientConfig config, AsyncServerStreamingCall<TResponse> asc, IAsyncStreamReader<TResponse> response, Action<ResponseCallContext> fn = null)
{
var headers = await asc.ResponseHeadersAsync.ConfigAwait();
if (GrpcClientConfig.GlobalResponseFilter != null || config.ResponseFilter != null)
{
var ctx = new ResponseCallContext(response, asc.GetStatus(), headers);
fn?.Invoke(ctx);
GrpcClientConfig.GlobalResponseFilter?.Invoke(ctx);
config.ResponseFilter?.Invoke(ctx);
}
return headers;
}
public static async Task<(IAsyncStreamReader<TResponse>, ResponseStatus, Metadata)> GetResponseAsync<TResponse>(GrpcClientConfig config, AsyncServerStreamingCall<TResponse> auc)
{
var headers = await auc.ResponseHeadersAsync.ConfigAwait();
ResponseStatus status = null;
IAsyncStreamReader<TResponse> response = default;
try
{
response = auc.ResponseStream;
status = response.GetResponseStatus();
}
catch (RpcException ex)
{
status = HandleRpcException(headers, ex);
}
finally
{
await InvokeResponseFiltersAsync(config, auc, response).ConfigAwait();
}
return (response, status, headers);
}
public static ResponseStatus HandleRpcException(Metadata headers, RpcException ex)
{
var statusBytes = ResponseCallContext.GetHeaderBytes(headers, GrpcClientConfig.Keywords.GrpcResponseStatus);
var status = statusBytes != null
? GrpcMarshaller<ResponseStatus>.Instance.Deserializer(statusBytes)
: new ResponseStatus {
ErrorCode = ex.Status.Detail ?? ex.StatusCode.ToString(),
Message = HttpStatus.GetStatusDescription(ResponseCallContext.GetHttpStatus(headers))
};
return status;
}
public static WebHeaderCollection ResolveHeaders(Metadata headers)
{
var to = new WebHeaderCollection();
foreach (var header in headers)
{
if (header.Key.EndsWith("-bin"))
continue;
to[header.Key] = header.Value;
}
return to;
}
public static Metadata ToHeaders(Dictionary<string, string> headers)
{
var to = new Metadata();
foreach (var entry in headers)
{
to.Add(entry.Key, entry.Value);
}
return to;
}
public static Metadata ToHeaders<T>(T headers)
{
var to = new Metadata();
var objDictionary = headers.ToObjectDictionary();
foreach (var entry in objDictionary)
{
var val = entry.Value.ConvertTo<string>();
to.Add(entry.Key, val);
}
return to;
}
}
}