public NotificationConsumer(IMessageHandler messageHandler, IChannelWrapper channelWrapper) { _messageHandler = messageHandler; _channelWrapper = channelWrapper; Listen(); }
public static async Task RunCustomMetadataAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); { // step 1: test unary call var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var call = client.UnaryCallAsync(request, headers: CreateTestMetadata()); await call.ResponseAsync; var responseHeaders = await call.ResponseHeadersAsync; var responseTrailers = call.GetTrailers(); Assert.AreEqual("test_initial_metadata_value", responseHeaders.GetValue("x-grpc-test-echo-initial")); CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.GetValueBytes("x-grpc-test-echo-trailing-bin")); } { // step 2: test full duplex call var request = new StreamingOutputCallRequest { ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }; var call = client.FullDuplexCall(headers: CreateTestMetadata()); await call.RequestStream.WriteAsync(request); await call.RequestStream.CompleteAsync(); await call.ResponseStream.ToListAsync(); var responseHeaders = await call.ResponseHeadersAsync; var responseTrailers = call.GetTrailers(); Assert.AreEqual("test_initial_metadata_value", responseHeaders.GetValue("x-grpc-test-echo-initial")); CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.GetValueBytes("x-grpc-test-echo-trailing-bin")); } }
public static async Task RunJwtTokenCreds(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, }; // not setting credentials here because they were set on channel already var response = await client.UnaryCallAsync(request); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); }
public static async Task RunPerRpcCredsAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var oauthScope = options.OAuthScope !; var googleCredential = await GoogleCredential.GetApplicationDefaultAsync(); var credentials = googleCredential.ToCallCredentials(); var request = new SimpleRequest { FillUsername = true, }; var response = await client.UnaryCallAsync(request, new CallOptions(credentials : credentials)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); }
public static async Task RunClientStreamingAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var bodySizes = new List <int> { 27182, 8, 1828, 45904 }.Select((size) => new StreamingInputCallRequest { Payload = CreateZerosPayload(size) }); using (var call = client.StreamingInputCall()) { await call.RequestStream.WriteAllAsync(bodySizes); var response = await call.ResponseAsync; Assert.AreEqual(74922, response.AggregatedPayloadSize); } }
public static async Task RunCancelAfterBeginAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var cts = new CancellationTokenSource(); using (var call = client.StreamingInputCall(cancellationToken: cts.Token)) { // TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it. await Task.Delay(1000); cts.Cancel(); var ex = await Assert.ThrowsAsync <RpcException>(() => call.ResponseAsync); Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } }
public static async Task RunClientCompressedUnary(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var probeRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true // lie about compression }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var e = await ExceptionAssert.ThrowsAsync <RpcException>(async() => await client.UnaryCallAsync(probeRequest, CreateClientCompressionMetadata(false))); Assert.AreEqual(StatusCode.InvalidArgument, e.Status.StatusCode); var compressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response1 = await client.UnaryCallAsync(compressedRequest, CreateClientCompressionMetadata(true)); Assert.AreEqual(314159, response1.Payload.Body.Length); var uncompressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = false }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response2 = await client.UnaryCallAsync(uncompressedRequest, CreateClientCompressionMetadata(false)); Assert.AreEqual(314159, response2.Payload.Body.Length); }
public static async Task RunOAuth2AuthTokenAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var oauthScope = options.OAuthScope !; ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); var oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = await client.UnaryCallAsync(request, new CallOptions(credentials : credentials)); Assert.IsFalse(string.IsNullOrEmpty(response.OauthScope)); Assert.IsTrue(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); }
public static async Task RunServerStreamingAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var bodySizes = new List <int> { 31415, 9, 2653, 58979 }; var request = new StreamingOutputCallRequest { ResponseParameters = { bodySizes.Select((size) => new ResponseParameters { Size = size }) } }; using (var call = client.StreamingOutputCall(request)) { var responseList = await call.ResponseStream.ToListAsync(); CollectionAssert.AreEqual(bodySizes, responseList.Select((item) => item.Payload.Body.Length).ToList()); } }
public static async Task RunComputeEngineCreds(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var defaultServiceAccount = options.DefaultServiceAccount !; var oauthScope = options.OAuthScope !; var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; // not setting credentials here because they were set on channel already var response = await client.UnaryCallAsync(request); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.IsFalse(string.IsNullOrEmpty(response.OauthScope)); Assert.IsTrue(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(defaultServiceAccount, response.Username); }
protected virtual IChannelWrapper <I> CreateProxy <I>(string endpointOverrideAddress) where I : class { IChannelWrapper <I> result = null; var key = typeof(I).FullName; if (_proxyCache.ContainsKey(key)) { lock (_lockObj) { var cache = _proxyCache[key]; cache.RemoveAll(p => p.IsFaulted); if (cache.Where(p => p.InUse == false).Count() > 0) { result = cache.First() as IChannelWrapper <I>; result.InUse = true; } } } if (result == null) { result = CreateProxyInternal <I>(endpointOverrideAddress); if (result.Instance != null) { var factoryProp = result.Instance.GetType().GetProperty("Factory"); if (factoryProp != null && factoryProp.PropertyType.Name == typeof(IProxyFactory).Name) { factoryProp.SetValue(result.Instance, this, new object[] { }); } } result.InUse = true; } return(result); }
public IChannelPool CreateSubscriptionChannelPool(ushort prefechCount) { if (subsCh is null) { subsCh = connection.CreateChannel(); subsCh.BasicQos(0, prefechCount, false); subsCh.QueueDeclare( config.Queue, durable: true, exclusive: false, autoDelete: false, arguments: new Dictionary <string, object> { ["x-dead-letter-exchange"] = "", ["x-dead-letter-routing-key"] = "_q_dead" }); } IChannelPool pool = channelPoolFactory.CreateChannelPool(subsCh); subscriptionWrapChannel = pool.GetChannelWrapper(); return(pool); }
public ConsumerFactory(IChannelWrapper channel, IConsumerBinder consumerBinder) { this.channel = channel; this.consumerBinder = consumerBinder; }
/// <summary> /// Configure an endpoint from a setting /// </summary> protected virtual IChannelWrapper <I> ConfigureEndpointFromSetting <I>(ClientEndpoint endpoint) where I : class { IChannelWrapper <I> result = null; if (!string.IsNullOrWhiteSpace(endpoint.Implementation)) { Type t = Type.GetType(endpoint.Implementation); if (t == null) { throw new InvalidOperationException( string.Format( "Unable to create service type, your configuration for endpoint.Implementation is probably wrong or you need to add a reference to an assembly. Configured as {0}.", endpoint.Implementation)); } if (endpoint.UseWcf) { result = CreateInProcWrapper <I>(t); } else { result = new MockChannelWrapper <I>() { Instance = Activator.CreateInstance(t) as I }; } } else if (!string.IsNullOrWhiteSpace(endpoint.Address)) { if (string.IsNullOrWhiteSpace(endpoint.ChannelFactory)) { IServiceHelperAttribute configureHelper = new DefaultServiceHelperAttribute(); Binding binding = null; ClientProxy <I> proxy = null; EndpointIdentity identity = null; var attributes = typeof(I).GetCustomAttributes(false); foreach (var attribute in attributes) { if (attribute is IServiceHelperAttribute) { configureHelper = attribute as IServiceHelperAttribute; identity = configureHelper.CreateIdentity(); } } if (endpoint.Address.StartsWith("net.tcp://")) { binding = new NetTcpBinding() { MaxBufferPoolSize = int.MaxValue, MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, }; MaxSetter.SetMaxes(binding); } else if (endpoint.Address.StartsWith("http://") || endpoint.Address.StartsWith("https://")) { binding = new WS2007HttpBinding(SecurityMode.None) { MaxBufferPoolSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, }; MaxSetter.SetMaxes(binding); MaxSetter.SetTimeouts <I>(binding); } else if (endpoint.Address.StartsWith("net.msmq://")) { binding = new NetMsmqBinding() { MaxBufferPoolSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, }; } else if (endpoint.Address.StartsWith("net.pipe://")) { binding = new NetNamedPipeBinding() { MaxBufferPoolSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, }; } configureHelper.ConfigureClientBinding(binding, typeof(I)); proxy = new ClientProxy <I>( binding, new EndpointAddress(new Uri(endpoint.Address), configureHelper.CreateIdentity())); configureHelper.ConfigureClientCredentials(proxy.ClientCredentials, typeof(I)); result = proxy; } else { var cfType = Type.GetType(endpoint.ChannelFactory); if (cfType == null) { throw new ConfigurationErrorsException("ChannelFactory is invalid"); } var cf = Activator.CreateInstance(cfType) as ICustomChannelFactory; if (cf == null) { throw new ConfigurationErrorsException("Could not create custom channel factory."); } result = cf.CreateChannel <I>(endpoint); } } if (result != null) { result.CacheCount = endpoint.CacheCount; } return(result); }
protected virtual void CloseProxy <I>(IChannelWrapper <I> proxy, bool abort) { var key = typeof(I).FullName; if (abort) { proxy.Abort(); } if (proxy.CacheCount > 0) { lock (_lockObj) { if (!_proxyCache.ContainsKey(key)) { _proxyCache.Add(key, new List <ICachableChannel>()); } var cache = _proxyCache[key]; if (cache.Where(p => p.CacheKey == key).Count() > 0) { // found in cache var proxyCached = cache.Where(p => p.CacheKey == key).First(); proxy.InUse = false; if (abort) { cache.Remove(proxyCached); } } else if (!abort) { // not in cache and not aborted if (proxy.CacheCount > cache.Count) { proxy.InUse = false; cache.Add(proxy); } else { // no room to cache, kill it try { proxy.Close(); } catch { proxy.Abort(); } } } } } else if (!abort) { // never cache this proxy try { proxy.Close(); } catch { proxy.Abort(); } } }
protected virtual HandleExceptionAction HandleCommunicationException <I>(CommunicationException ex, IChannelWrapper <I> wrapper) { LogException("Communication exception while proxying a call. ", ex); return(HandleExceptionAction.ThrowException); }
protected virtual HandleExceptionAction HandleTimeoutException <I>(TimeoutException ex, IChannelWrapper <I> wrapper) { LogException("Timeout exception while proxying a call. ", ex); return(HandleExceptionAction.ThrowException); }
private void Send(string message, IChannelWrapper channelWrapper) { var messageBodyBytes = Encoding.UTF8.GetBytes(message); channelWrapper.Channel.BasicPublish(Settings.ExchangeName, Settings.RoutingKey, null, messageBodyBytes); }
public PollingConsumer() { _channelWrapper = ObjectFactory.GetInstance<IChannelWrapper>(); _thread = new Thread(Start); _thread.Start(_channelWrapper.Channel); }
private TClient CreateClient <TClient>(IChannelWrapper channel) where TClient : ClientBase { return((TClient)Activator.CreateInstance(typeof(TClient), channel.Channel) !); }
private async Task RunTestCaseAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); switch (options.TestCase) { case "empty_unary": RunEmptyUnary(client); break; case "large_unary": RunLargeUnary(client); break; case "client_streaming": await RunClientStreamingAsync(client); break; case "server_streaming": await RunServerStreamingAsync(client); break; case "ping_pong": await RunPingPongAsync(client); break; case "empty_stream": await RunEmptyStreamAsync(client); break; case "compute_engine_creds": RunComputeEngineCreds(client, options.DefaultServiceAccount !, options.OAuthScope !); break; case "jwt_token_creds": RunJwtTokenCreds(client); break; case "oauth2_auth_token": await RunOAuth2AuthTokenAsync(client, options.OAuthScope !); break; case "per_rpc_creds": await RunPerRpcCredsAsync(client, options.OAuthScope !); break; case "cancel_after_begin": await RunCancelAfterBeginAsync(client); break; case "cancel_after_first_response": await RunCancelAfterFirstResponseAsync(client); break; case "timeout_on_sleeping_server": await RunTimeoutOnSleepingServerAsync(client); break; case "custom_metadata": await RunCustomMetadataAsync(client); break; case "status_code_and_message": await RunStatusCodeAndMessageAsync(client); break; case "unimplemented_service": RunUnimplementedService(CreateClient <UnimplementedService.UnimplementedServiceClient>(channel)); break; case "special_status_message": await RunSpecialStatusMessageAsync(client); break; case "unimplemented_method": RunUnimplementedMethod(client); break; case "client_compressed_unary": RunClientCompressedUnary(client); break; case "client_compressed_streaming": await RunClientCompressedStreamingAsync(client); break; case "server_compressed_unary": await RunServerCompressedUnary(client); break; case "server_compressed_streaming": await RunServerCompressedStreamingAsync(client); break; default: throw new ArgumentException("Unknown test case " + options.TestCase); } }
/// <summary> /// Proxy a call to WCF /// </summary> public virtual void Call <I>(WcfCall <I> call, string endpointOverrideAddress) where I : class { IChannelWrapper <I> wrapper = null; bool abort = true; try { bool skipCall = false; wrapper = CreateProxy <I>(endpointOverrideAddress); if (wrapper.IsRealProxy && wrapper.CacheCount > 0) { // retry one time try { // turn off every call logging //Log(string.Format("Calling {0} with cached proxy", typeof(I).Name)); call.Invoke(wrapper.Instance); skipCall = true; } catch (Exception ex) { LogException("First call exception with a cached proxy", ex); CloseProxy <I>(wrapper, true); wrapper = CreateProxy <I>(endpointOverrideAddress); } } if (!skipCall) { call.Invoke(wrapper.Instance); abort = false; } if (wrapper != null) { wrapper.LastUse = DateTime.Now; } } catch (CommunicationException cex) { if (HandleCommunicationException <I>(cex, wrapper) == HandleExceptionAction.ThrowException) { throw; } } catch (TimeoutException tex) { if (HandleTimeoutException <I>(tex, wrapper) == HandleExceptionAction.ThrowException) { throw; } } catch (Exception ex) { if (HandleException <I>(ex, wrapper) == HandleExceptionAction.ThrowException) { throw; } } finally { if (wrapper != null) { try { CloseProxy <I>(wrapper, abort); } catch { } } } }