/// <summary> /// 拦截异步服务端流调用 /// </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 AsyncServerStreamingCall <TResponse> AsyncServerStreamingCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncServerStreamingCallContinuation <TRequest, TResponse> continuation) { var clientId = context.Options.Headers?.GetClientId() ?? ""; CheckRepeat(clientId, ServiceProvider.GetJsonProvider().Serializer(request), request.GetGenericTypeName()); return(continuation(request, context)); }
/// <summary> /// Creates a continuation with test partial failure results. /// </summary> /// <param name="request">The test request.</param> /// <param name="context">The client interceptor context.</param> /// <returns>An async unary call that returns test response and metadata upon completion. /// </returns> private AsyncUnaryCall <HelloResponse> ContinuationWithPartialFailures(HelloRequest request, ClientInterceptorContext <HelloRequest, HelloResponse> context) { Task <HelloResponse> responseTask = Task.FromResult(TEST_RESPONSE_PARTIAL_FAILURES); Task <Metadata> responseHeadersTask = Task.FromResult(TEST_RESPONSE_METADATA); return(new AsyncUnaryCall <HelloResponse>(responseTask, responseHeadersTask, null, null, null)); }
public void SetUp() { method = new Method <string, string>(MethodType.Unary, FakeServiceName, FakeMethodName, Marshallers.StringMarshaller, Marshallers.StringMarshaller); context = new ClientInterceptorContext <string, string>(method, FakeHost, new CallOptions()); classUnderTest = new FakeUnaryInterceptor(); }
public override AsyncDuplexStreamingCall <TRequest, TResponse> AsyncDuplexStreamingCall <TRequest, TResponse>(Method <TRequest, TResponse> method, string host, CallOptions options) { var _context = new ClientInterceptorContext <TRequest, TResponse>(method, host, options); var rspCnt = Calls.AsyncDuplexStreamingCall(CreateCall(method, host, options)); var tracingRequestStream = new TracingClientStreamWriter <TRequest, TResponse>(rspCnt.RequestStream, _context, _tracer.Request); var tracingResponseStream = new TracingAsyncClientStreamReader <TResponse, TRequest>(rspCnt.ResponseStream, _context, _tracer.Response, _tracer.Finish, _tracer.Exception); return(new AsyncDuplexStreamingCall <TRequest, TResponse>(tracingRequestStream, tracingResponseStream, rspCnt.ResponseHeadersAsync, rspCnt.GetStatus, rspCnt.GetTrailers, rspCnt.Dispose)); }
public void Request <TRequest, TResponse>(TRequest request, ClientInterceptorContext <TRequest, TResponse> context) where TRequest : class where TResponse : class { // 修改Channel //context.Options.Headers.Add(Constants.MetadataKey_ChannelTarget, "127.0.0.1:10003"); Console.WriteLine("start request"); }
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse ( TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncUnaryCallContinuation<TRequest, TResponse> continuation ) { return base.AsyncUnaryCall(request, context, continuation); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { Console.WriteLine("Logs"); return(continuation(request, context)); }
public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation) { AddCallerMetadata(ref context); return(continuation(request, context)); }
/// <summary> /// Creates a continuation with test exception. /// </summary> /// <param name="request">The test request.</param> /// <param name="context">The client interceptor context.</param> /// <returns>An async unary call that throws a test exception and returns test metadata /// upon completion. /// </returns> private AsyncUnaryCall <HelloResponse> ContinuationWithException(HelloRequest request, ClientInterceptorContext <HelloRequest, HelloResponse> context) { Task <Metadata> responseHeadersTask = Task.FromResult(TEST_RESPONSE_METADATA); Task <HelloResponse> responseTask = FromException <HelloResponse>(TEST_EXCEPTION); return(new AsyncUnaryCall <HelloResponse>(responseTask, responseHeadersTask, null, null, null)); }
public override AsyncClientStreamingCall <TRequest, TResponse> AsyncClientStreamingCall <TRequest, TResponse>( ClientInterceptorContext <TRequest, TResponse> context, AsyncClientStreamingCallContinuation <TRequest, TResponse> continuation) { LogCall(context.Method); AddCallerMetadata(ref context); return(continuation(context)); }
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)); }
/// <summary> /// Extracts logging fields from the gRPC invocation context. /// </summary> /// <param name="context">An invocation context.</param> /// <returns>A dictionary of fields.</returns> private static IDictionary <string, object> FieldsFromContext <TRequest, TResponse>( ClientInterceptorContext <TRequest, TResponse> context) where TResponse : class where TRequest : class { return(new Dictionary <string, object> { { "method", context.Method.Name }, { "service", context.Method.ServiceName.Replace("proto.", "") } }); }
AsyncServerStreamingCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncServerStreamingCallContinuation <TRequest, TResponse> continuation) { Console.WriteLine($"AsyncServerStreamingCall: {context.Method.FullName}"); return(base.AsyncServerStreamingCall(request, context, continuation)); }
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 TResponse BlockingUnaryCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, BlockingUnaryCallContinuation <TRequest, TResponse> continuation) { LogCall(context.Method); AddCallerMetadata(ref context); return(continuation(request, context)); }
public override AsyncDuplexStreamingCall <TRequest, TResponse> AsyncDuplexStreamingCall <TRequest, TResponse>( ClientInterceptorContext <TRequest, TResponse> context, AsyncDuplexStreamingCallContinuation <TRequest, TResponse> continuation) { LogCall(context.Method); var call = continuation(context); return(new AsyncDuplexStreamingCall <TRequest, TResponse>(call.RequestStream, call.ResponseStream, call.ResponseHeadersAsync, call.GetStatus, call.GetTrailers, call.Dispose)); }
/// <summary> /// AsyncDuplexStreamingCall /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TResponse"></typeparam> /// <param name="context"></param> /// <param name="continuation"></param> /// <returns></returns> public override AsyncDuplexStreamingCall <TRequest, TResponse> AsyncDuplexStreamingCall <TRequest, TResponse>( ClientInterceptorContext <TRequest, TResponse> context , AsyncDuplexStreamingCallContinuation <TRequest, TResponse> continuation) { return(Call(context , () => { return continuation(context); }) as AsyncDuplexStreamingCall <TRequest, TResponse>); }
public override AsyncServerStreamingCall <TResponse> AsyncServerStreamingCall <TRequest, TResponse>( TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncServerStreamingCallContinuation <TRequest, TResponse> continuation) { var response = continuation(request, context); return(new AsyncServerStreamingCall <TResponse>(new AsyncStreamReader <TResponse>(response.ResponseStream), response.ResponseHeadersAsync, response.GetStatus, response.GetTrailers, response.Dispose)); }
/// <summary> /// Creates an async unary call continuation with test results. /// </summary> /// <param name="request">The test request.</param> /// <param name="context">The client interceptor context.</param> /// <returns>An async unary call that returns test response and metadata upon completion. /// </returns> private AsyncUnaryCall <HelloResponse> ContinuationWithResults(HelloRequest request, ClientInterceptorContext <HelloRequest, HelloResponse> context) { Task <HelloResponse> responseTask = Task.FromResult(TEST_RESPONSE); Task <Metadata> responseHeadersTask = Task.FromResult(TEST_RESPONSE_METADATA); Func <Metadata> trailersTask = () => TEST_TRAILERS_METADATA; return(new AsyncUnaryCall <HelloResponse>(responseTask, responseHeadersTask, null, trailersTask, null)); }
public override AsyncDuplexStreamingCall <TRequest, TResponse> AsyncDuplexStreamingCall <TRequest, TResponse>( ClientInterceptorContext <TRequest, TResponse> context, AsyncDuplexStreamingCallContinuation <TRequest, TResponse> continuation) { var response = continuation(context); return(new AsyncDuplexStreamingCall <TRequest, TResponse>(response.RequestStream, new StreamReader <TResponse>(response.ResponseStream, ReportNewLeader), response.ResponseHeadersAsync, response.GetStatus, response.GetTrailers, response.Dispose)); }
public void SetUp() { recorder = Substitute.For <RpcRecorder>(); method = new Method <string, string>(MethodType.Unary, FakeServiceName, FakeMethodName, Marshallers.StringMarshaller, Marshallers.StringMarshaller); context = new ClientInterceptorContext <string, string>(method, FakeHost, new CallOptions()); interceptor = new MetricsInterceptor(recorder); }
public InterceptedClientHandler BeforeSendRequest(ref Message request, ClientInterceptorContext context) { _context = context; var span = InitializeSpanWithHeaders(); _logger = new WcfTraceLogger(span, _configuration); _configuration.Tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new MetadataCarrier(_context.Options.Headers)); _logger.Request(ref request); return(this); }
/// <summary> /// Makes an asynchronous connection for a read and write stream via gRPC and logs any errors that occur. /// </summary> /// <param name="context">The gRPC context (service, method, etc.).</param> /// <param name="continuation">The actual client method implementation function.</param> /// <returns>A wrapped asynchronous call.</returns> public override AsyncDuplexStreamingCall <TRequest, TResponse> AsyncDuplexStreamingCall <TRequest, TResponse>( ClientInterceptorContext <TRequest, TResponse> context, AsyncDuplexStreamingCallContinuation <TRequest, TResponse> continuation) { var call = base.AsyncDuplexStreamingCall(context, continuation); var fields = FieldsFromContext(context); var logger = _logger.WithFields(fields); return(WrapCall(call, logger, context.Options.CancellationToken)); }
private ClientInterceptorContext <TRequest, TResponse> GetNewContext <TRequest, TResponse>( ClientInterceptorContext <TRequest, TResponse> context) where TRequest : class where TResponse : class { var options = context.Options; var metadata = options.Headers ?? new Metadata(); return(new ClientInterceptorContext <TRequest, TResponse>( context.Method, context.Host, options.WithHeaders(interceptor(metadata)))); }
public override AsyncClientStreamingCall <TRequest, TResponse> AsyncClientStreamingCall <TRequest, TResponse>( ClientInterceptorContext <TRequest, TResponse> context, AsyncClientStreamingCallContinuation <TRequest, TResponse> continuation) { var response = continuation(context); response.ResponseAsync.ContinueWith(ReportNewLeader, ContinuationOptions); return(new AsyncClientStreamingCall <TRequest, TResponse>(response.RequestStream, response.ResponseAsync, response.ResponseHeadersAsync, response.GetStatus, response.GetTrailers, response.Dispose)); }
public void TestServerStreamingWithException() { GoogleAdsConfig config = new GoogleAdsConfig(); LoggingHandler handler = new LoggingHandler(config); handler.WriteSummaryLogs = delegate(LogEntry logEntry) { Assert.AreEqual(config.ServerUrl, logEntry.Host); Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method); CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders); Assert.True(logEntry.IsFailure); HelloException helloException = logEntry.Exception as HelloException; Assert.NotNull(helloException); Assert.AreEqual(TEST_REQUEST_ID, helloException.RequestId); Assert.NotNull(helloException.Failure); Assert.AreEqual(1, helloException.Failure.Errors.Count); Assert.NotNull(helloException.Failure.Errors[0].ErrorCode); Assert.NotNull(helloException.Failure.Errors[0].ErrorCode.RequestError); }; handler.WriteDetailedLogs = delegate(LogEntry logEntry) { Assert.AreEqual(config.ServerUrl, logEntry.Host); Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method); CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders); CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders); Assert.AreSame(TEST_REQUEST, logEntry.Request); // Response is null if there's an exception. Assert.IsNull(logEntry.Response); Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId); Assert.True(logEntry.IsFailure); HelloException helloException = logEntry.Exception as HelloException; Assert.NotNull(helloException); Assert.AreEqual(TEST_REQUEST_ID, helloException.RequestId); Assert.NotNull(helloException.Failure); Assert.AreEqual(1, helloException.Failure.Errors.Count); Assert.NotNull(helloException.Failure.Errors[0].ErrorCode); Assert.NotNull(helloException.Failure.Errors[0].ErrorCode.RequestError); }; ClientInterceptorContext <HelloRequest, HelloResponse> context = GetClientInterceptorContext(); AsyncServerStreamingCall <HelloResponse> call = StreamingContinuationWithException <HelloResponse>(); handler.HandleAsyncServerStreamingLogging(TEST_REQUEST, null, context, new AggregateException(TEST_EXCEPTION), call); }
public TracingAsyncClientStreamReader(IAsyncStreamReader <T> reader, ClientInterceptorContext <TRequest, T> context, Action <T, ClientInterceptorContext <TRequest, T> > onMessage, Action <ClientInterceptorContext <TRequest, T> > onStreamEnd = null, Action <ClientInterceptorContext <TRequest, T>, Exception, TRequest> onException = null) { _reader = reader; _context = context; _onMessage = onMessage; _onStreamEnd = onStreamEnd; _onException = onException; }
public override AsyncServerStreamingCall <TResponse> AsyncServerStreamingCall <TRequest, TResponse>(TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncServerStreamingCallContinuation <TRequest, TResponse> continuation) { var token = Blocker.Block(GetAccessToken()); var headers = new Metadata(); headers.Add("Authorization", token); var newContext = new ClientInterceptorContext <TRequest, TResponse>(context.Method, context.Host, context.Options.WithHeaders(headers)); return(base.AsyncServerStreamingCall(request, newContext, continuation)); }
/// <summary> /// Handles the logging of asynchronous unary calls. /// </summary> /// <typeparam name="TRequest">The type of the request.</typeparam> /// <typeparam name="TResponse">The type of the response.</typeparam> /// <param name="request">The request.</param> /// <param name="context">The context.</param> /// <param name="oldTask">The old task.</param> /// <param name="call">The call.</param> internal void HandleAsyncUnaryLogging <TRequest, TResponse>(TRequest request, ClientInterceptorContext <TRequest, TResponse> context, Task <TResponse> oldTask, AsyncUnaryCall <TResponse> call) where TRequest : class where TResponse : class { // Generating log entry is expensive, so let's do that only if the log source // has been configured to do so. RpcException exception = null; if (TraceUtilities.ShouldGenerateSummaryRequestLogs()) { exception = UnaryRpcInterceptor.ParseTaskException <TResponse>(oldTask.Exception); LogEntry logEntry = new LogEntry(logCustomizer) { Host = config.ServerUrl, Method = context.Method.FullName, RequestHeaders = context.Options.Headers, // includes the RequestId IsFailure = oldTask.IsFaulted, Exception = exception, CustomerId = GetCustomerId(request), ResponseHeaders = Merge(GetResponseHeader(call.ResponseHeadersAsync), call.GetTrailers()), Response = (oldTask.IsFaulted) ? default : oldTask.Result, }; WriteSummaryLogs(logEntry); } if (TraceUtilities.ShouldGenerateDetailedRequestLogs()) { LogEntry logEntry = new LogEntry(logCustomizer) { Host = config.ServerUrl, Method = context.Method.FullName, RequestHeaders = context.Options.Headers, Request = request, ResponseHeaders = Merge(GetResponseHeader(call.ResponseHeadersAsync), call.GetTrailers()), Response = (oldTask.IsFaulted) ? default : oldTask.Result, Exception = exception ?? UnaryRpcInterceptor.ParseTaskException <TResponse>( oldTask.Exception), IsFailure = oldTask.IsFaulted, CustomerId = GetCustomerId(request), PartialFailures = (oldTask.IsFaulted) ? "" : GetPartialFailures(oldTask.Result) }; WriteDetailedLogs(logEntry); } }
/// <summary> /// Initializes a new instance of the <see cref="ClientRpcScope{TRequest, TResponse}" /> class. /// </summary> /// <param name="context">The context.</param> /// <param name="options">The options.</param> public ClientRpcScope(ClientInterceptorContext <TRequest, TResponse> context, ClientTracingInterceptorOptions options) : base(context.Method?.FullName, options.RecordMessageEvents) { this.context = context; // Capture the current activity. this.parentActivity = Activity.Current; // Short-circuit if nobody is listening if (!GrpcCoreInstrumentation.ActivitySource.HasListeners()) { return; } // This if block is for unit testing only. IEnumerable <KeyValuePair <string, object> > customTags = null; if (options.ActivityIdentifierValue != default) { customTags = new List <KeyValuePair <string, object> > { new KeyValuePair <string, object>(SemanticConventions.AttributeActivityIdentifier, options.ActivityIdentifierValue), }; } // We want to start an activity but don't activate it. // After calling StartActivity, Activity.Current will be the new Activity. // This scope is created synchronously before the RPC invocation starts and so this new Activity will overwrite // the callers current Activity which isn't what we want. We need to restore the original immediately after doing this. // If this call happened after some kind of async context await then a restore wouldn't be necessary. // gRPC Core just doesn't have the hooks to do this as far as I can tell. var rpcActivity = GrpcCoreInstrumentation.ActivitySource.StartActivity( this.FullServiceName, ActivityKind.Client, this.parentActivity == default ? default : this.parentActivity.Context, tags: customTags); if (rpcActivity == null) { return; } var callOptions = context.Options; if (callOptions.Headers == null) { callOptions = callOptions.WithHeaders(new Metadata()); } this.SetActivity(rpcActivity); options.Propagator.Inject(new PropagationContext(rpcActivity.Context, Baggage.Current), callOptions.Headers, MetadataSetter); this.context = new ClientInterceptorContext <TRequest, TResponse>(context.Method, context.Host, callOptions); }