/// <summary>
        /// </summary>
        /// <param name="connectionInfo"></param>
        /// <exception cref="InvalidOperationException">Thrown if the <see cref="ConnectionInfo"/> has already been retrieved.</exception>
        public void InitConnectionInfo(RpcConnectionInfo connectionInfo)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }

            lock (this.syncRoot)
            {
                if (!Equals(this.connectionInfo, connectionInfo))
                {
                    if (this.connectionInfoRetrieved)
                    {
                        throw new InvalidOperationException("Cannot change ConnectionInfo after it has been retrieved.");
                    }

                    if (this.serverId != RpcServerId.Empty)
                    {
                        if (connectionInfo.ServerId == RpcServerId.Empty)
                        {
                            this.connectionInfo = connectionInfo.SetServerId(this.serverId);
                        }
                        else if (this.serverId != connectionInfo.ServerId)
                        {
                            throw new InvalidOperationException("Cannot change server id after it has been assigned.");
                        }
                    }
                    else
                    {
                        this.connectionInfo = connectionInfo;
                        this.serverId       = connectionInfo.ServerId;
                    }
                }
            }
        }
 public LightweightRpcServer(
     IServiceProvider?serviceProvider      = null,
     IRpcServerOptions?options             = null,
     LightweightOptions?lightweightOptions = null,
     ILoggerFactory?loggerFactory          = null)
     : this(RpcServerId.NewId(), null, serviceProvider, options, lightweightOptions, loggerFactory)
 {
 }
 public LightweightRpcServer(
     RpcServerId serverId,
     IRpcServiceDefinitionsProvider?definitionsProvider = null,
     IServiceProvider?serviceProvider      = null,
     IRpcServerOptions?options             = null,
     LightweightOptions?lightweightOptions = null,
     ILoggerFactory?loggerFactory          = null)
     : this(new RpcServicePublisher(definitionsProvider ?? new RpcServiceDefinitionsBuilder(), serverId),
            serviceProvider, options, lightweightOptions, loggerFactory)
 {
 }
예제 #4
0
        public InprocRpcConnector(RpcServerId serverId, IRpcClientOptions?options = null)
        {
            var requestPipe  = new Pipe(new PipeOptions(null, readerScheduler: PipeScheduler.Inline, useSynchronizationContext: false));
            var responsePipe = new Pipe(new PipeOptions(null, readerScheduler: PipeScheduler.Inline, useSynchronizationContext: false));

            this.EndPoint = new InprocRpcEndPoint(new DuplexPipe(requestPipe.Reader, responsePipe.Writer));

            this.Connection = new InprocRpcConnection(
                new RpcConnectionInfo("Direct", new Uri("direct://localhost"), serverId),
                new DuplexPipe(responsePipe.Reader, requestPipe.Writer),
                options);
        }
예제 #5
0
        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;
            }
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="connectionInfo"></param>
        public RpcConnectionInfo TryInitConnectionInfo(RpcConnectionInfo connectionInfo)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }

            lock (this.syncRoot)
            {
                if (!Equals(this.connectionInfo, connectionInfo))
                {
                    if (this.connectionInfo == null)
                    {
                        this.connectionInfo = connectionInfo;
                    }
                    else
                    {
                        // We already have a connection info. If it's missing a server id, let's update server id
                        // if provided.
                        if (this.serverId == RpcServerId.Empty)
                        {
                            if (connectionInfo.ServerId != RpcServerId.Empty)
                            {
                                this.connectionInfo = this.connectionInfo.SetServerId(connectionInfo.ServerId);
                                this.serverId       = connectionInfo.ServerId;
                            }
                        }
                        else
                        {
                            if (connectionInfo.ServerId != RpcServerId.Empty && connectionInfo.ServerId != this.serverId)
                            {
                                throw new InvalidOperationException("Server id of provided connection does not match already assigned server id.");
                            }
                        }
                    }
                }

                return(this.connectionInfo !);
            }
        }
        private static IRpcServerHost CreateNetGrpcServer(
            IRpcServiceDefinitionsProvider serviceDefinitionsProvider,
            RpcServerId serverId,
            RpcServerOptions options,
            Action <IServiceCollection> configureServices)
        {
            var hostBuilder = WebHost.CreateDefaultBuilder()
                              .ConfigureKestrel(options =>
            {
                options.ListenLocalhost(GrpcCoreFullStackTestsBase.GrpcTestPort, listenOptions =>
                {
                    listenOptions.UseHttps(TestCertificates.ServerPFXPath, "1111");
                    //listenOptions.UseHttps(certPath, "1111", o =>
                    //{
                    //    o.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
                    //});
                    listenOptions.Protocols = HttpProtocols.Http2;
                });
            })
                              .ConfigureLogging(b => ConfigureLogging(b))
                              .ConfigureServices(s =>
            {
                s.AddSingleton(serviceDefinitionsProvider ?? new RpcServiceDefinitionsBuilder());
                s.Configure <RpcServicePublisherOptions>(o => o.ServerId = serverId);
                s.AddSingleton <IOptions <RpcServerOptions> >(new OptionsWrapper <RpcServerOptions>(options));

                configureServices?.Invoke(s);
            })
                              .UseStartup <NetStartup>();

            var host = hostBuilder.Build();

            var rpcServer = (NetGrpcServer)host.Services.GetService(typeof(NetGrpcServer));

            return(new NetGrpcTestServer(host, rpcServer));
        }
예제 #8
0
 protected RpcServerHostBase(RpcServerId serverId, IRpcServiceDefinitionsProvider definitionsProvider, IRpcServerOptions?options, ILoggerFactory?loggerFactory = null) :
     this(new RpcServicePublisher(definitionsProvider, serverId), options, loggerFactory)
 {
 }
 public abstract RpcConnectionInfo GetConnectionInfo(RpcServerId serverId);
예제 #10
0
 public override RpcConnectionInfo GetConnectionInfo(RpcServerId serverId)
 {
     return(new RpcConnectionInfo(this.DisplayName, new Uri($"lightweight.tcp://{this.HostName}:{this.Port}"), serverId));
 }
 public override RpcConnectionInfo GetConnectionInfo(RpcServerId serverId)
 {
     return(connectionInfo.SetServerId(serverId));
 }
예제 #12
0
 public GrpcServer(RpcServerId serverId, IRpcServiceDefinitionsProvider?definitionsProvider = null, IServiceProvider?serviceProvider = null, RpcServerOptions?options = null)
     : this(new RpcServicePublisher(definitionsProvider ?? new RpcServiceDefinitionsBuilder(), serverId), serviceProvider, options)
 {
 }
예제 #13
0
        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);
                        }
                    }
 public override RpcConnectionInfo GetConnectionInfo(RpcServerId serverId)
 => this.connectionInfo.SetServerId(serverId);
 public override RpcConnectionInfo GetConnectionInfo(RpcServerId serverId)
 {
     return(new RpcConnectionInfo(this.DisplayName, this.uri, serverId));
 }
 public RpcConnectionInfo GetConnectionInfo(RpcServerId serverId)
 {
     return(new RpcConnectionInfo(this.DisplayName, new Uri($"{GrpcScheme}://{this.HostName}:{this.Port}"), serverId));
 }
        /// <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();
        }
예제 #18
0
 public override RpcConnectionInfo GetConnectionInfo(RpcServerId serverId)
 {
     return(new RpcConnectionInfo(serverId));
 }
 public override RpcConnectionInfo GetConnectionInfo(RpcServerId serverId)
 {
     return(new RpcConnectionInfo("Direct", new Uri("direct://localhost"), serverId));
 }
예제 #20
0
        public void RefObjOfTypeToRefObjTest()
        {
            var ms = new MemoryStream();

            ToStream(ms, false, new RpcObjectRef <ISimpleService>(new RpcConnectionInfo("Test", null, RpcServerId.NewId()), RpcObjectId.NewId(), null));
            string text = Encoding.UTF8.GetString(ms.GetBuffer());

            var ms2 = new MemoryStream();

            ToStream(ms2, true, new RpcObjectRef <ISimpleService>(new RpcConnectionInfo("Test", null, RpcServerId.NewId()), RpcObjectId.NewId(), null));

            ms.Seek(0, SeekOrigin.Begin);
            var ref1 = FromStream(typeof(RpcObjectRef <IBlockingService>), false, ms);

            ms2.Seek(0, SeekOrigin.Begin);
            var ref2 = FromStream(typeof(RpcObjectRef <IBlockingService>), true, ms2);


            Assert.IsTrue(text.Length > 0);
        }
 public RpcServicePublisher(IRpcServiceDefinitionsProvider serviceDefinitionsProvider, RpcServerId serverId = default)
 {
     this.DefinitionsProvider = serviceDefinitionsProvider ?? throw new ArgumentNullException(nameof(serviceDefinitionsProvider));
     this.serverId            = serverId;
 }