/// <summary> /// Intercepts an asynchronous invocation of a simple remote call. /// </summary> /// <param name="request">The request message of the invocation.</param> /// <param name="context">The <see cref="ClientInterceptorContext{TRequest, TResponse}" /> /// associated with the current invocation.</param> /// <param name="continuation">The callback that continues the invocation process. /// This can be invoked zero or more times by the interceptor. /// The interceptor can invoke the continuation passing the given /// request value and context arguments, or substitute them as it sees fit.</param> /// <returns> /// An instance of <see cref="AsyncUnaryCall{TResponse}" /> /// representing an asynchronous unary invocation. /// The interceptor can simply return the return value of the /// continuation delegate passed to it intact, or construct its /// own substitute as it sees fit. /// </returns> public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { AsyncUnaryCall <TResponse> call = continuation(request, context); Task t = call.ResponseAsync.ContinueWith( delegate(Task <TResponse> oldTask) { // Generating log entry is expensive, so let's do that only if the log source // has been configured to do so. if (TraceUtilities.ShouldGenerateRequestLogs()) { LogEntry logEntry = new LogEntry() { Host = Config.ServerUrl, Method = context.Method.FullName, RequestHeaders = context.Options.Headers, Request = request, ResponseHeaders = GetResponseHeader(call), Response = (oldTask.IsFaulted) ? default(TResponse) : oldTask.Result, Exception = GetGoogleAdsException(oldTask.Exception), IsFailure = oldTask.IsFaulted, CustomerId = GetCustomerId(request), PartialFailures = (oldTask.IsFaulted)? "" : GetPartialFailures(oldTask.Result) }; OnLogEventAvailable?.Invoke(this, logEntry); } }); t.Wait(); return(call); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var now = Util.EpochTimeMillis(); var keyLevel = authentication.KeyLevel; var signer = crypto.CreateSigner(keyLevel); var payload = new GrpcAuthPayload { Request = ByteString.CopyFrom(((IMessage)request).ToByteArray()), CreatedAtMs = now }; var signature = signer.Sign(payload); var metadata = context.Options.Headers ?? new Metadata(); metadata.Add("token-realm", "Token"); metadata.Add("token-scheme", "Token-Ed25519-SHA512"); metadata.Add("token-key-id", signer.GetKeyId()); metadata.Add("token-signature", signature); metadata.Add("token-created-at-ms", now.ToString()); metadata.Add("token-member-id", memberId); metadata.Add("token-security-metadata", encodeSecurityMetadata(authentication)); if (authentication.OnBehalfOf != null) { metadata.Add("token-on-behalf-of", authentication.OnBehalfOf); metadata.Add("customer-initiated", authentication.CustomerInitiated.ToString()); } return(continuation(request, new ClientInterceptorContext <TRequest, TResponse>(context.Method, context.Host, context.Options.WithHeaders(metadata)))); }
/// <summary> /// Intercepts an asynchronous invocation of a simple remote call. /// </summary> /// <param name="request">The request message of the invocation.</param> /// <param name="context">The <see cref="ClientInterceptorContext{TRequest, TResponse}" /> /// associated with the current invocation.</param> /// <param name="continuation">The callback that continues the invocation process. /// This can be invoked zero or more times by the interceptor. /// The interceptor can invoke the continuation passing the given /// request value and context arguments, or substitute them as it sees fit.</param> /// <returns> /// An instance of <see cref="AsyncUnaryCall{TResponse}" /> /// representing an asynchronous unary invocation. /// The interceptor can simply return the return value of the /// continuation delegate passed to it intact, or construct its /// own substitute as it sees fit. /// </returns> public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { AsyncUnaryCall <TResponse> call = continuation(request, context); call.ResponseAsync.ContinueWith( delegate(Task <TResponse> oldTask) { LogEntry logEntry = new LogEntry() { Host = Config.ServerUrl, Method = context.Method.FullName, RequestHeaders = context.Options.Headers, Request = request, ResponseHeaders = GetResponseHeader(call), Response = (oldTask.IsFaulted) ? default(TResponse) : oldTask.Result, Exception = GetGoogleAdsException(oldTask.Exception), IsFailure = oldTask.IsFaulted, CustomerId = GetCustomerId(request) }; OnLogEventAvailable?.Invoke(this, logEntry); }); return(call); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { _logger.Info($"Begin '{context.Method.Name}' request with '{request.ToString()}'"); var responseContinuation = continuation(request, context); var responseAsync = responseContinuation.ResponseAsync.ContinueWith(responseTask => { try { var response = responseTask.Result; _logger.Info($"Request to '{context.Method.Name}' with '{request.ToString()}' succeeded!"); return(response); } catch (AggregateException ex) { _logger.Error($"Request to '{context.Method.Name}' with '{request.ToString()}' failed!", ex.InnerException); throw ex.InnerException; } }); var responseHeaderAsync = responseContinuation.ResponseHeadersAsync.ContinueWith(headerTask => { var responseHeader = headerTask.Result; _logger.Info($"Request to '{request.ToString()}' response headers: '{string.Join(",", (responseHeader as IList<Metadata.Entry>).Select(entry => entry.ToString()))}'"); return(responseHeader); }); return(new AsyncUnaryCall <TResponse>(responseAsync, responseHeaderAsync, responseContinuation.GetStatus, responseContinuation.GetTrailers, responseContinuation.Dispose)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { return(continuation(request, GetNewContext(context))); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation ) { var builder = new StringBuilder(); // Call gRPC begin builder.AppendLine($"Call gRPC {context.Host}/{context.Method} begin."); // Logging Request builder.AppendLine(LogRequest(request)); // Logging Response var reply = continuation(request, context); var response = reply.ResponseAsync.Result; var exception = reply.ResponseAsync.Exception; builder.AppendLine(LogResponse(response, exception)); // Call gRPC finish builder.AppendLine($"Call gRPC {context.Host}/{context.Method} finish."); Console.WriteLine(builder.ToString()); return(reply); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { this._logger.LogInformation("AsyncUnaryCall called"); return(base.AsyncUnaryCall(request, context, continuation)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>(TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { long startTicks = timeSource.GetTimestampTicks(); return(HandleResponseAsync(continuation(request, context), (response) => TracingResponseAsync(request, context, response, startTicks))); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var call = continuation(request, context); return(new AsyncUnaryCall <TResponse>(HandleResponse(call.ResponseAsync), call.ResponseHeadersAsync, call.GetStatus, call.GetTrailers, call.Dispose)); }
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse ( TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncUnaryCallContinuation<TRequest, TResponse> continuation ) { return base.AsyncUnaryCall(request, context, continuation); }
/* * BlockingUnaryCall 拦截阻塞调用 * AsyncUnaryCall 拦截异步调用 * AsyncServerStreamingCall 拦截异步服务端流调用 * AsyncClientStreamingCall 拦截异步客户端流调用 * AsyncDuplexStreamingCall 拦截异步双向流调用 * UnaryServerHandler 用于拦截和传入普通调用服务器端处理程序 * ClientStreamingServerHandler 用于拦截客户端流调用的服务器端处理程序 * ServerStreamingServerHandler 用于拦截服务端流调用的服务器端处理程序 * DuplexStreamingServerHandler 用于拦截双向流调用的服务器端处理程序 */ public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { LogCall(context.Method); return(continuation(request, context)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { Console.WriteLine("Logs"); return(continuation(request, context)); }
/// <summary> /// Intercept and add headers to a AsyncUnaryCall. /// </summary> /// <param name="request">The request to intercept.</param> /// <param name="context">The client interceptor context to add headers to.</param> /// <param name="continuation">The continuation of the request after all headers have been added.</param> public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { AddCallerMetadata(ref context); return(continuation(request, context)); }
private AsyncUnaryCallContinuation <TRequest, TResponse> getAsyncUnaryCallChain <TRequest, TResponse>(Interceptor interceptor, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) where TRequest : class where TResponse : class { AsyncUnaryCallContinuation <TRequest, TResponse> fun = (fRequest, fContext) => { return(interceptor.AsyncUnaryCall(fRequest, fContext, continuation)); }; return(fun); }
/// <summary> /// AsyncUnaryCall /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TResponse"></typeparam> /// <param name="request"></param> /// <param name="context"></param> /// <param name="continuation"></param> /// <returns></returns> public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request , ClientInterceptorContext <TRequest, TResponse> context , AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { return(Call(context , () => { return continuation(request, context); } , request) as AsyncUnaryCall <TResponse>); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var now = Util.EpochTimeMillis(); var keyLevel = authentication.KeyLevel; var signer = crypto.CreateSigner(keyLevel); var payload = new GrpcAuthPayload { Request = ByteString.CopyFrom(((IMessage)request).ToByteArray()), CreatedAtMs = now }; var signature = signer.Sign(payload); var metadata = context.Options.Headers ?? new Metadata(); metadata.Add(TOKEN_REALM, "Token"); metadata.Add(TOKEN_SCHEME, "Token-Ed25519-SHA512"); metadata.Add(TOKEN_KEY_ID, signer.GetKeyId()); metadata.Add(TOKEN_SIGNATURE, signature); metadata.Add(TOKEN_CREATED_AT_MS, now.ToString()); metadata.Add(TOKEN_MEMBER_ID, memberId); var customer = authentication.CustomerTrackingMetadata; if (!string.IsNullOrEmpty(customer.IpAddress)) { metadata.Add(CUSTOMER_IP_ADDRESS_KEY, customer.IpAddress); } if (!string.IsNullOrEmpty(customer.GeoLocation)) { metadata.Add(CUSTOMER_GEO_LOCATION_KEY, customer.GeoLocation); } if (!string.IsNullOrEmpty(customer.DeviceId)) { metadata.Add(CUSTOMER_DEVICE_ID_KEY, customer.DeviceId); } if (authentication.OnBehalfOf != null) { metadata.Add(TOKEN_ON_BEHALF_OF, authentication.OnBehalfOf); metadata.Add(CUSTOMER_INITIATED, authentication.CustomerInitiated.ToString()); } return(continuation(request, new ClientInterceptorContext <TRequest, TResponse>(context.Method, context.Host, context.Options.WithHeaders(metadata)))); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs); return(continuation( request, new ClientInterceptorContext <TRequest, TResponse>( context.Method, context.Host, context.Options.WithDeadline(deadline)))); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { try { return(continuation(request, context)); } catch (Exception exception) { _logger.LogError(exception, "Context: {@Context} failed.", context); throw new RpcException(new Status(StatusCode.Unknown, "Request failed.", exception)); } }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var metadata = context.Options.Headers ?? new Metadata(); metadata.Add("X-Correlation-ID", $"{Guid.NewGuid()}"); var newContext = new ClientInterceptorContext <TRequest, TResponse>( context.Method, context.Host, context.Options.WithHeaders(metadata)); return(continuation(request, newContext)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { AsyncUnaryCall <TResponse> call = null; var headers = new TaskCompletionSource <Metadata>(); var task = RetryWrapper(() => call = continuation(request, context), headers); return(new AsyncUnaryCall <TResponse>( task, headers.Task, () => call.GetStatus(), () => call.GetTrailers(), () => call.Dispose())); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var response = continuation(request, context); return(new AsyncUnaryCall <TResponse>(response.ResponseAsync.ContinueWith(t => { if (t.Exception?.InnerException is RpcException ex) { throw ConvertRpcException(ex); } return t.Result; }), response.ResponseHeadersAsync, response.GetStatus, response.GetTrailers, response.Dispose)); }
/// <summary> /// Intercepts an asynchronous invocation of a simple remote call. /// </summary> /// <param name="request">The request message of the invocation.</param> /// <param name="context">The <see cref="ClientInterceptorContext{TRequest, TResponse}" /> /// associated with the current invocation.</param> /// <param name="continuationCallback">The callback that continues the invocation process. /// This can be invoked zero or more times by the interceptor. /// The interceptor can invoke the continuation passing the given /// request value and context arguments, or substitute them as it sees fit.</param> /// <returns> /// An instance of <see cref="AsyncUnaryCall{TResponse}" /> /// representing an asynchronous unary invocation. /// The interceptor can simply return the return value of the /// <paramref name="continuationCallback"/> delegate passed to it intact, or construct its /// own substitute. /// </returns> public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuationCallback) { AsyncUnaryCall <TResponse> call = continuationCallback(request, context); Task t = call.ResponseAsync.ContinueWith( delegate(Task <TResponse> oldTask) { loggingHandler.HandleAsyncUnaryLogging(request, context, oldTask, call); }); t.Wait(); return(UnaryRpcInterceptor.Intercept(call)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var callContext = new ClientCallInterceptorContext(context.Options, context.Host, context.Method); var call = base.AsyncUnaryCall(request, context, continuation); return(new AsyncUnaryCall <TResponse>( WaitAsyncUnaryCall(callContext, call.ResponseAsync), call.ResponseHeadersAsync, call.GetStatus, call.GetTrailers, call.Dispose)); }
/// <inheritdoc/> public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { ClientRpcScope <TRequest, TResponse> rpcScope = null; try { rpcScope = new ClientRpcScope <TRequest, TResponse>(context, this.options); rpcScope.RecordRequest(request); var responseContinuation = continuation(request, rpcScope.Context); var responseAsync = responseContinuation.ResponseAsync.ContinueWith( responseTask => { try { var response = responseTask.Result; rpcScope.RecordResponse(response); rpcScope.Complete(); return(response); } catch (AggregateException ex) { rpcScope.CompleteWithException(ex.InnerException); throw ex.InnerException; } }); return(new AsyncUnaryCall <TResponse>( responseAsync, responseContinuation.ResponseHeadersAsync, responseContinuation.GetStatus, responseContinuation.GetTrailers, responseContinuation.WithBestEffortDispose(rpcScope))); } catch (Exception e) { rpcScope?.CompleteWithException(e); throw; } finally { rpcScope?.RestoreParentActivity(); } }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var token = _httpContextAcessor.HttpContext.Request.Headers["Authorization"]; var headers = new Metadata { { "Authorization", token } }; var options = context.Options.WithHeaders(headers); context = new ClientInterceptorContext <TRequest, TResponse>(context.Method, context.Host, options); return(base.AsyncUnaryCall(request, context, continuation)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var tokenResponse = _client.GetAccessTokenAsync().Result; var headers = context.Options.Headers; if (headers == null) { headers = new Metadata(); var options = context.Options.WithHeaders(headers); context = new ClientInterceptorContext <TRequest, TResponse>(context.Method, context.Host, options); } headers.Add("Authorization", $"{tokenResponse.TokenType} {tokenResponse.AccessToken}"); return(continuation(request, context)); }
/// <summary> /// This is how I will call my grpc service from the server. /// This method override to provide the token via header to call the GRPC server. /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <param name="continuation"></param> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TResponse"></typeparam> /// <returns></returns> public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var token = _httpContextAccessor.HttpContext.Request.Headers["Authorization"]; var headers = new Metadata { { "Authorization", token } }; //It will take my request context that I intercepted and I will add headers var options = context.Options.WithHeaders(headers); //It will create a new context to understand that there is a new header context = new ClientInterceptorContext <TRequest, TResponse>(context.Method, context.Host, options); return(base.AsyncUnaryCall(request, context, continuation)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { var token = _httpContextAccesor.HttpContext.User.Claims .FirstOrDefault(c => c.Type == "JWT")?.Value; var headers = new Metadata { { "Authorization", $"Bearer {token}" } }; var options = context.Options.WithHeaders(headers); context = new ClientInterceptorContext <TRequest, TResponse>(context.Method, context.Host, options); var call = continuation(request, context); return(new AsyncUnaryCall <TResponse>(HandleResponse(call.ResponseAsync), call.ResponseHeadersAsync, call.GetStatus, call.GetTrailers, call.Dispose)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { SecretKeyEncryption?ske = null; byte[]? key = null; if (request is ISessionSecuredMessage ssmRequ) { if (ske == null || key == null) { (ske, key) = ResolveSessionKey(context.Options.Headers); } try { ssmRequ.Encrypt(ske, key); } catch (Exception ex) { throw new RpcException(new Status(StatusCode.Internal, "failed to encrypt session-secured input message: " + ex.Message)); } } var call = continuation(request, context); var response = HandleResponse <TResponse>(call.ResponseAsync, ske, key, context.Options.Headers); return(new AsyncUnaryCall <TResponse>( response, call.ResponseHeadersAsync, call.GetStatus, call.GetTrailers, call.Dispose)); }
/// <summary> /// /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TResponse"></typeparam> /// <param name="request"></param> /// <param name="context"></param> /// <param name="continuation"></param> /// <returns></returns> /// <exception cref="AppException"></exception> /// <exception cref="UnauthorizedAccessException"></exception> public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>(TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { try { return(continuation(request, context)); } catch (RpcException rpc) { HandleException(rpc); } // never reached return(null); }