public async Task Singletons_ShouldReturn_Published() { var server = new LightweightRpcServer(); var connectionInfo = new RpcConnectionInfo(new Uri("test://test")); var endPoint = new TestDiscoveryEndPoint(connectionInfo); server.AddEndPoint(endPoint); server.PublishSingleton <ISimpleService>(); server.PublishSingleton <ISimpleService2>(); server.Start(); try { var clientId = Guid.NewGuid(); var listener = endPoint.Listeners.First(); var response = await listener.SendReceiveDatagramAsync <RpcDiscoveryRequest, RpcPublishedSingletonsResponse>( ServiceDiscoveryOperations.GetPublishedSingletons, new RpcDiscoveryRequest(clientId), this.serializer); Assert.NotNull(response); Assert.AreEqual(clientId, response.ClientId); Assert.AreEqual(2, response.Services.Length); } finally { await server.ShutdownAsync(); } }
public LightweightServerServiceDefinition Build(LightweightRpcServer server) { var binder = new Binder(); this.GenerateOperationHandlers(server, binder); return(new LightweightServerServiceDefinition(this.ServiceInfo.FullName, binder.GetMethodStubs())); }
public async Task DualServer_DiscoveryClient_BeforeServerStart_Should_Discover() { var server = new LightweightRpcServer(); var endPoint = new TcpRpcEndPoint("localhost", "127.0.0.1", ClientServerTestsBase.TcpTestPort, false); var discoveryEndPoint = new LightweightDiscoveryEndPoint(endPoint.GetConnectionInfo(server.ServerId)); server.AddEndPoint(endPoint); server.AddEndPoint(discoveryEndPoint); var server2 = new LightweightRpcServer(); var endPoint2 = new TcpRpcEndPoint("localhost", "127.0.0.1", ClientServerTestsBase.TcpTestPort + 1, false); var discoveryEndPoint2 = new LightweightDiscoveryEndPoint(endPoint2.GetConnectionInfo(server2.ServerId)); server2.AddEndPoint(endPoint2); server2.AddEndPoint(discoveryEndPoint2); server.PublishSingleton <ISimpleService>(); server2.PublishSingleton <ISimpleService2>(); var discoveryClient = new LightweightDiscoveryClient(loggerFactory.CreateLogger <LightweightDiscoveryClient>()); var eventDiscoveredServices = new List <DiscoveredService>(); bool serviceLost = false; discoveryClient.ServiceDiscovered += (s, e) => eventDiscoveredServices.Add(e.DiscoveredService); discoveryClient.ServiceLost += (s, e) => serviceLost = true; using var discoveryCts = new CancellationTokenSource(); var discoveryTask = discoveryClient.FindServicesAsync(discoveryCts.Token); await Task.Delay(100); server.Start(); server2.Start(); try { await Task.Delay(2000); Assert.IsFalse(serviceLost); var discoveredServices = discoveryClient.DiscoveredServices; Assert.AreEqual(2, discoveredServices.Count); Assert.AreEqual(2, eventDiscoveredServices.Count); discoveryCts.Cancel(); await discoveryTask.DefaultTimeout(); } finally { await server.ShutdownAsync(); await server2.ShutdownAsync(); } }
public void GlobalSetup() { var serverId = RpcServerId.NewId(); var definitionsProvider = new RpcServiceDefinitionsBuilder(); // var serializer = new JsonRpcSerializer(); var serializer = new ProtobufRpcSerializer(RuntimeTypeModel.Create()); var serverOptions = new RpcServerOptions { Serializer = serializer }; this.clientOptions = new RpcClientOptions { Serializer = serializer }.AsImmutable(); switch (this.ConnectionType) { //case RpcConnectionType.LightweightInproc: // { // var connector = new InprocRpcConnector(clientOptions); // this.server = new LightweightRpcServer(serverId, definitionsProvider, null, serverOptions); // this.server.AddEndPoint(connector.EndPoint); // this.server.ServicePublisher.PublishSingleton<ISimpleService>(new SimpleServiceImpl()); // this.server.Start(); // //this.clientConnection = connector.Connection; // //clientService = this.clientConnection.GetServiceSingleton<ISimpleServiceClient>(); // break; // } case RpcConnectionType.LightweightTcp: { this.server = new LightweightRpcServer(serverId, definitionsProvider, null, serverOptions); this.server.AddEndPoint(new TcpRpcEndPoint("127.0.0.1", 50051, false)); this.server.ServicePublisher.PublishSingleton <ISimpleService>(new SimpleServiceImpl()); this.server.Start(); this.connectionInfo = new RpcConnectionInfo(new Uri("lightweight.tcp://localhost:50051")); break; } case RpcConnectionType.LightweightNamedPipe: { this.server = new LightweightRpcServer(serverId, definitionsProvider, null, serverOptions); this.server.AddEndPoint(new NamedPipeRpcEndPoint("RpcBenchmark")); this.server.ServicePublisher.PublishSingleton <ISimpleService>(new SimpleServiceImpl()); this.server.Start(); this.connectionInfo = new RpcConnectionInfo(new Uri($"{WellKnownRpcSchemes.LightweightPipe}://./RpcBenchmark")); break; } } }
public static async Task Main(string[] args) { // This example shows how to explicitly setup a gRPC RPC server and a lightweight RPC server // with a common service publisher. // // In a real scenario, it is probably more suitable to use the .NET generic host // (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host). // // The NetGrpcServer example shows what a host setup could look like. Console.WriteLine("Initializing gRPC server and lightweight RPC server."); var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); var definitionsBuilder = new RpcServiceDefinitionsBuilder(); var rpcPublisher = new RpcServicePublisher(definitionsBuilder); RegisterServiceDefinitions(definitionsBuilder); PublishServices(rpcPublisher); var grpcServer = new GrpcServer(rpcPublisher, serviceProvider); grpcServer.AddEndPoint(CreateGrpcEndPoint(50051)); var lightweightServer = new LightweightRpcServer(rpcPublisher, serviceProvider); var sslOptions = new SslServerOptions(new X509Certificate2(TestCertificates.ServerPFXPath, "1111")); lightweightServer.AddEndPoint( new TcpRpcEndPoint("127.0.0.1", 50052, false, sslOptions)); Console.WriteLine("Starting gRPC server and lightweight RPC server."); // Once the gRPC server is started, it is no longer possible to register service definitions. grpcServer.Start(); lightweightServer.Start(); Console.WriteLine("gRPC server and lightweight RPC server are running, press any key to shutdown."); Console.ReadKey(); Console.WriteLine("Shutting down servers."); await Task.WhenAll(grpcServer.ShutdownAsync(), lightweightServer.ShutdownAsync()); Console.WriteLine("Ended"); }
public async Task Multicast_Singletons_ShouldReturn_Published() { var server = new LightweightRpcServer(); var connectionInfo = new RpcConnectionInfo(new Uri("test://test")); var endPoint = new LightweightDiscoveryEndPoint(connectionInfo); server.AddEndPoint(endPoint); server.PublishSingleton <ISimpleService>(); server.PublishSingleton <ISimpleService2>(); server.Start(); try { using var client = new UdpClient(AddressFamily.InterNetwork); client.Client.Bind(new IPEndPoint(IPAddress.Any, 0)); client.JoinMulticastGroup(LightweightDiscoveryEndPoint.DefaultMulticastAddress); // Receive early var receiveTask = client.ReceiveAsync(); // Build request byte[] requestData = LightweightStubHelper.GetRequestData(ServiceDiscoveryOperations.GetPublishedSingletons, 0, new RpcRequest(), this.serializer); // Send it var discoveryEp = new System.Net.IPEndPoint(LightweightDiscoveryEndPoint.DefaultMulticastAddress, LightweightDiscoveryEndPoint.DefaultDiscoveryPort); var bytesSent = await client.SendAsync(requestData, requestData.Length, discoveryEp); Assert.AreEqual(requestData.Length, bytesSent); // Wait for response var receiveRes = await receiveTask.DefaultTimeout(); var response = LightweightStubHelper.GetResponseFromData <RpcPublishedSingletonsResponse>(serializer, receiveRes.Buffer); Assert.NotNull(response); // And check it Assert.NotNull(response); Assert.AreEqual(2, response.Services.Length); } finally { await server.ShutdownAsync(); } }
public async Task ServerEndPoint_Should_CreateStartAndStop_Listener() { var server = new LightweightRpcServer(); var connectionInfo = new RpcConnectionInfo(new Uri("test://test")); var endPoint = new TestDiscoveryEndPoint(connectionInfo); server.AddEndPoint(endPoint); server.Start(); TestDiscoveryListener listener = endPoint.Listeners.FirstOrDefault(); Assert.NotNull(listener); Assert.IsTrue(listener.IsListening); await server.ShutdownAsync(); Assert.IsTrue(listener.IsStopped); server.Dispose(); Assert.IsTrue(listener.IsDisposed); }
public async Task AccountNegotiateTest(string accountKey) { string userName = Environment.GetEnvironmentVariable(FormattableString.Invariant($"RPC_{accountKey}_NAME")); string userPw = Environment.GetEnvironmentVariable(FormattableString.Invariant($"RPC_{accountKey}_PASSWORD")); string expectedIdentity = Environment.GetEnvironmentVariable(FormattableString.Invariant($"RPC_{accountKey}_IDENTITY")); Assert.IsNotEmpty(userName); Assert.IsNotEmpty(userPw); Assert.IsNotEmpty(expectedIdentity); LightweightRpcServer server = CreateServer(); using var _ = server.PublishSingleton <INegotiateService>(); server.Start(); try { var connection = new TcpRpcConnection(new RpcConnectionInfo(new Uri("lightweight.tcp://localhost:50052")), new NegotiateClientOptions { Credential = new NetworkCredential(userName, userPw) }); await connection.ConnectAsync(default).ContextFree();
public void OneTimeTearDown() { server.Dispose(); server = null; binder = null; }
public void OneTimeSetUp() { server = new LightweightRpcServer(); binder = new TestLightweightMethodBinder(); }
public ServiceDiscovery(LightweightRpcServer server, IRpcSerializer discoverySerializer) { this.server = server; this.discoverySerializer = discoverySerializer; }
/// <summary> /// TODO: Use factories instead of using this.connnectionType. /// </summary> /// <param name="serviceDefinitionsProvider"></param> /// <param name="proxyDefinitionsProvider"></param> /// <returns></returns> protected (IRpcServerHost, IRpcChannel) CreateServerAndConnection( IRpcServiceDefinitionsProvider serviceDefinitionsProvider = null, Action <RpcServerOptions> configServerOptions = null, Action <RpcClientOptions> configClientOptions = null, Action <IServiceCollection> configureServices = null) { var rpcServerId = RpcServerId.NewId(); var serverOptions = new RpcServerOptions { Serializer = this.serializer }; var clientOptions = new RpcClientOptions { Serializer = this.serializer }; configServerOptions?.Invoke(serverOptions); configClientOptions?.Invoke(clientOptions); IServiceProvider services = GetServiceProvider(configureServices); switch (this.ConnectionType) { case RpcConnectionType.LightweightTcp: case RpcConnectionType.LightweightSslTcp: { var host = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, this.LightweightOptions, loggerFactory: services.GetService <ILoggerFactory>()); SslServerOptions sslServerOptions = null; if (this.ConnectionType == RpcConnectionType.LightweightSslTcp) { sslServerOptions = new SslServerOptions(new X509Certificate2(TestCertificates.ServerPFXPath, "1111")); } host.AddEndPoint(new TcpRpcEndPoint("127.0.0.1", TcpTestPort, false, sslServerOptions)); SslClientOptions sslClientOptions = null; if (this.ConnectionType == RpcConnectionType.LightweightSslTcp) { sslClientOptions = new SslClientOptions { RemoteCertificateValidationCallback = this.ValidateTestCertificate }; } var connection = new TcpRpcConnection( new RpcConnectionInfo("TCP", new Uri($"lightweight.tcp://127.0.0.1:{TcpTestPort}"), rpcServerId), sslClientOptions, clientOptions.AsImmutable(), this.LightweightOptions); return(host, connection); } case RpcConnectionType.LightweightNamedPipe: { var server = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, this.LightweightOptions, loggerFactory: services.GetService <ILoggerFactory>()); server.AddEndPoint(new NamedPipeRpcEndPoint("testpipe")); var connection = new NamedPipeRpcConnection( new RpcConnectionInfo(new Uri("lightweight.pipe://./testpipe")), clientOptions.AsImmutable(), this.LightweightOptions); return(server, connection); } case RpcConnectionType.LightweightInproc: { Pipe requestPipe = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.ThreadPool)); Pipe responsePipe = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.Inline)); var host = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, loggerFactory: services.GetService <ILoggerFactory>()); host.AddEndPoint(new InprocRpcEndPoint(new DirectDuplexPipe(requestPipe.Reader, responsePipe.Writer))); var connection = new InprocRpcConnection(new RpcConnectionInfo("Direct", new Uri("direct:localhost"), rpcServerId), new DirectDuplexPipe(responsePipe.Reader, requestPipe.Writer), clientOptions.AsImmutable()); return(host, connection); } case RpcConnectionType.Grpc: { var host = new GrpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions); host.AddEndPoint(GrpcCoreFullStackTestsBase.CreateEndPoint()); var connection = new GrpcConnection( new RpcConnectionInfo("TCP", new Uri($"grpc://localhost:{GrpcCoreFullStackTestsBase.GrpcTestPort}"), rpcServerId), TestCertificates.GrpcSslCredentials, clientOptions.AsImmutable()); return(host, connection); } #if PLAT_NET_GRPC case RpcConnectionType.NetGrpc: { var server = CreateNetGrpcServer(serviceDefinitionsProvider, rpcServerId, serverOptions, configureServices); //var host = new GrpcServer(rpcServerId, serviceDefinitionsBuilder, null, options); //host.AddEndPoint(GrpcCoreFullStackTestsBase.CreateEndPoint()); var handler = new System.Net.Http.HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => { return(true); }; var channelOptions = new GrpcNet.Client.GrpcChannelOptions() { HttpClient = new System.Net.Http.HttpClient(handler), DisposeHttpClient = true }; var connection = new NetGrpcConnection( new RpcConnectionInfo("net-grpc", new Uri($"grpc://localhost:{GrpcCoreFullStackTestsBase.GrpcTestPort}"), rpcServerId), clientOptions.AsImmutable(), channelOptions); return(server, connection); } #endif } throw new NotSupportedException(); }
public async Task SimpleServiceServerTest() { Pipe requestPipe = new Pipe(); Pipe responsePipe = new Pipe(); var serializer = new ProtobufRpcSerializer(); var serviceImpl = new TestBlockingSimpleServiceImpl(); var hostMock = new Mock <IRpcServerCore>(); var serviceImplProviderMock = new Mock <IRpcServiceActivator>(); serviceImplProviderMock.Setup(p => p.GetActivatedService <ISimpleService>(It.IsAny <IServiceProvider>(), It.IsAny <RpcObjectId>())).Returns(new ActivatedService <ISimpleService>(serviceImpl, null)); hostMock.Setup(p => p.ServiceActivator).Returns(serviceImplProviderMock.Object); hostMock.Setup(p => p.CallInterceptors).Returns(ImmutableArrayList <RpcServerCallInterceptor> .Empty); var serviceRegistrator = new RpcServiceDefinitionsBuilder(); serviceRegistrator.RegisterService <ISimpleService>(); _ = RpcServerId.NewId(); using (var host = new LightweightRpcServer(Mock.Of <IRpcServicePublisher>(), serviceImplProviderMock.Object, serviceRegistrator, null, new RpcServerOptions { Serializer = serializer })) { host.AddEndPoint(new InprocRpcEndPoint(new DirectDuplexPipe(requestPipe.Reader, responsePipe.Writer))); host.Start(); var objectId = RpcObjectId.NewId(); var requestFrame = new LightweightRpcFrame(RpcFrameType.UnaryRequest, 1, "SciTech.Rpc.Tests.SimpleService.Add", ImmutableArray <KeyValuePair <string, ImmutableArray <byte> > > .Empty); using (var frameWriter = new BufferWriterStreamImpl()) { var writeState = requestFrame.BeginWrite(frameWriter); var request = new RpcObjectRequest <int, int>(objectId, 5, 6); serializer.Serialize(frameWriter, request, request.GetType()); int frameLength = checked ((int)frameWriter.Length); LightweightRpcFrame.EndWrite(frameLength, writeState); frameWriter.CopyTo(requestPipe.Writer); } await requestPipe.Writer.FlushAsync(); RpcResponse <int> response = null; while (response == null) { var readResult = await responsePipe.Reader.ReadAsync(); if (!readResult.IsCanceled) { var buffer = readResult.Buffer; if (LightweightRpcFrame.TryRead(ref buffer, LightweightRpcFrame.DefaultMaxFrameLength, out var responseFrame) == RpcFrameState.Full) { Assert.AreEqual(requestFrame.RpcOperation, responseFrame.RpcOperation); Assert.AreEqual(requestFrame.MessageNumber, responseFrame.MessageNumber); response = (RpcResponse <int>)serializer.Deserialize(responseFrame.Payload, typeof(RpcResponse <int>)); responsePipe.Reader.AdvanceTo(buffer.Start); } else { if (readResult.IsCompleted) { break; } responsePipe.Reader.AdvanceTo(buffer.Start, buffer.End); } }