Пример #1
0
        private InProcRemoteHostClient(Workspace workspace, InProcRemoteServices inprocServices, Stream stream) :
            base(workspace)
        {
            _inprocServices = inprocServices;

            _rpc = new JsonRpc(stream, stream, target: this);
            _rpc.JsonSerializer.Converters.Add(AggregateJsonConverter.Instance);

            // handle disconnected situation
            _rpc.Disconnected += OnRpcDisconnected;

            _rpc.StartListening();
        }
    private async Task <(JsonRpc JsonRpc, WebSocket WebSocket)> EstablishWebSocket()
    {
        IWebHostBuilder webHostBuilder = WebHost.CreateDefaultBuilder(Array.Empty <string>())
                                         .UseStartup <AspNetStartup>();
        var testServer = new TestServer(webHostBuilder);
        var testClient = testServer.CreateWebSocketClient();
        var webSocket  = await testClient.ConnectAsync(testServer.BaseAddress, this.TimeoutToken);

        var rpc = new JsonRpc(new WebSocketMessageHandler(webSocket));

        rpc.StartListening();
        return(rpc, webSocket);
    }
Пример #3
0
        public Server(Stream?sender, Stream?receiver)
        {
            waitForInit = new ManualResetEvent(false);

            rpc = new JsonRpc(sender, receiver, this);
            rpc.StartListening();

            disconnectEvent   = new ManualResetEvent(false);
            rpc.Disconnected += (s, e) => disconnectEvent.Set();

            sourceFiles = new Dictionary <Uri, SourceFile>();

            waitForInit.Set();
        }
Пример #4
0
        /// <summary> Connects an asynchronous. </summary>
        /// <remarks> 19.09.2020. </remarks>
        /// <param name="token"> A token that allows processing to be cancelled. </param>
        /// <returns> An asynchronous result. </returns>
        public async Task ConnectAsync(CancellationToken token)
        {
            if (_socket != null && _socket.State == WebSocketState.Open)
            {
                return;
            }

            if (_socket == null || _socket.State != WebSocketState.None)
            {
                _jsonRpc?.Dispose();
                _socket?.Dispose();
                _socket = new ClientWebSocket();
            }

            _connectTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
            var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, _connectTokenSource.Token);
            await _socket.ConnectAsync(_uri, linkedTokenSource.Token);

            linkedTokenSource.Dispose();
            _connectTokenSource.Dispose();
            _connectTokenSource = null;
            Logger.Debug("Connected to Websocket.");

            var formatter = new JsonMessageFormatter();

            formatter.JsonSerializer.Converters.Add(_hashTypeConverter);
            formatter.JsonSerializer.Converters.Add(_extrinsicJsonConverter);
            formatter.JsonSerializer.Converters.Add(_extrinsicStatusJsonConverter);

            _jsonRpc = new JsonRpc(new WebSocketMessageHandler(_socket, formatter));
            _jsonRpc.TraceSource.Listeners.Add(new NLogTraceListener());
            _jsonRpc.TraceSource.Switch.Level = SourceLevels.All;
            _jsonRpc.AddLocalRpcTarget(Listener, new JsonRpcTargetOptions()
            {
                AllowNonPublicInvocation = false
            });
            _jsonRpc.StartListening();
            Logger.Debug("Listening to websocket.");

            var result = await State.GetMetaDataAsync(token);

            var metaDataParser = new MetaDataParser(_uri.OriginalString, result);

            MetaData = metaDataParser.MetaData;
            Logger.Debug("MetaData parsed.");

            GenesisHash = await Chain.GetBlockHashAsync(0, token);

            Logger.Debug("Genesis hash parsed.");
        }
        private ServiceHubRemoteHostClient(
            Workspace workspace, HubClient hubClient, HostGroup hostGroup, Stream stream) :
            base(workspace)
        {
            _hubClient = hubClient;
            _hostGroup = hostGroup;

            _rpc = new JsonRpc(stream, stream, target: this);

            // handle disconnected situation
            _rpc.Disconnected += OnRpcDisconnected;

            _rpc.StartListening();
        }
Пример #6
0
        public InProcLanguageServer(Stream inputStream, Stream outputStream, LanguageServerProtocol protocol,
                                    Workspace workspace, IDiagnosticService diagnosticService, string?clientName, bool supportsHover)
        {
            _protocol      = protocol;
            _workspace     = workspace;
            _supportsHover = supportsHover;

            _jsonRpc = new JsonRpc(outputStream, inputStream, this);
            _jsonRpc.StartListening();

            _diagnosticService = diagnosticService;
            _clientName        = clientName;
            _diagnosticService.DiagnosticsUpdated += DiagnosticService_DiagnosticsUpdated;
        }
Пример #7
0
        async Task ExecuteServerAsync(ServerOptions opts)
        {
            m_requesters = new ConcurrentDictionary <int, IRequest>();
            m_listener   = new TcpListener(IPAddress.Parse(opts.Host), opts.Port);
            m_listener.Start();

            while (true)
            {
                try
                {
                    var conn = await m_listener.AcceptTcpClientAsync();

                    _ = Task.Run(async() =>
                    {
                        int id = Interlocked.Increment(ref s_counter);
                        try
                        {
                            var rpc          = new JsonRpc(conn.GetStream());
                            m_requesters[id] = rpc.Attach <IRequest>();

                            rpc.AddLocalRpcTarget(new Responser(id, this));

                            // Initiate JSON-RPC message processing.
                            rpc.StartListening();

                            await rpc.Completion;
                        }
                        catch (Exception) { }
                        finally
                        {
                            m_requesters.TryRemove(id, out IRequest requester);
                            conn.Close();

                            if (m_requesters.IsEmpty)
                            {
                                m_listener.Stop();
                            }

                            ((IDisposable)requester)?.Dispose();
                        }
                    });
                }
                catch (ObjectDisposedException)
                {
                    // This happens when Stop is called and we're waiting for connection.
                    break;
                }
            }
        }
Пример #8
0
    public async Task AttachSecondProxy()
    {
        var streams   = FullDuplexStream.CreateStreams();
        var server    = new Server();
        var serverRpc = JsonRpc.Attach(streams.Item2, server);

        var clientRpc = new JsonRpc(streams.Item1, streams.Item1);
        var client1   = clientRpc.Attach <IServer>();
        var client2   = clientRpc.Attach <IServer2>();

        clientRpc.StartListening();

        Assert.Equal(3, await client1.AddAsync(1, 2));
        Assert.Equal(6, await client2.MultiplyAsync(2, 3));
    }
Пример #9
0
        private async Task HandleClientAsync(Stream serverStream, CancellationToken cancellationToken = default)
        {
            using JsonRpc server = GetRpcServer(serverStream, _resolveAssemblyReferenceTaskHandler);
            server.StartListening();

            try
            {
                await server.Completion.WithCancellation(cancellationToken).ConfigureAwait(false);
            }
            catch (ConnectionLostException)
            {
                // Some problem with connection, let's ignore it.
                // All other exceptions are issue though
            }
        }
Пример #10
0
            public async Task Dispatch()
            {
                using (Rpc){
                    Rpc.CancelLocallyInvokedMethodsWhenConnectionIsClosed = true;
                    Rpc.StartListening();
                    // Attach api
                    var otherSide = Rpc.Attach <Api.IHandlers>();
                    while (true)
                    {
                        try{
                            // Call and response
                            Console.WriteLine(await otherSide.Ping());
                            await otherSide.Hello(new Api.Models.Hello {
                                name = "C#"
                            });

                            var result = await otherSide.SubscribeTick();

                            await Task.Delay(5000);

                            var result2 = await otherSide.UnsubscribeTick(result);

                            Console.WriteLine(JsonConvert.SerializeObject(result2));
                            await Rpc.Completion;     // throws exceptions - closed connection,etc.
                            if (Rpc.Completion.Exception == null)
                            {
                                break;
                            }
                        }catch (Exception e) {
                            if (e is WebSocketException || e is ConnectionLostException)
                            {
                                Console.WriteLine(e.Message.ToString());
                                Console.WriteLine("================================================");
                                break;
                            }
                            if (e is RemoteRpcException)
                            {
                                Console.WriteLine(e.Message.ToString());
                                Console.WriteLine("================================================");
                                break;
                            }
                        }
                    }

                    // Missing: WS close
                    this.Manager.Connections.TryRemove(this.Id, out OpenSocket value);
                }
            }
Пример #11
0
    public async Task RPCMethodNameSubstitutionByOptions()
    {
        var streams = FullDuplexStream.CreateStreams();

        this.serverStream = streams.Item1;
        this.clientStream = streams.Item2;

        var camelCaseOptions = new JsonRpcProxyOptions {
            MethodNameTransform = CommonMethodNameTransforms.CamelCase
        };
        var prefixOptions = new JsonRpcProxyOptions {
            MethodNameTransform = CommonMethodNameTransforms.Prepend("ns.")
        };

        // Construct two client proxies with conflicting method transforms to prove that each instance returned retains its unique options.
        var clientRpc = new JsonRpc(this.clientStream, this.clientStream);
        var clientRpcWithCamelCase = clientRpc.Attach <IServer3>(camelCaseOptions);
        var clientRpcWithPrefix    = clientRpc.Attach <IServer3>(prefixOptions);

        clientRpc.StartListening();

        // Construct the server to only respond to one set of method names for now to confirm that the client is sending the right one.
        this.serverRpc = new JsonRpc(this.serverStream, this.serverStream);
        this.serverRpc.AddLocalRpcTarget(this.server, new JsonRpcTargetOptions {
            MethodNameTransform = camelCaseOptions.MethodNameTransform
        });
        this.serverRpc.StartListening();

        Assert.Equal("Hi!", await clientRpcWithCamelCase.SayHiAsync());                                             // "sayHiAsync"
        await Assert.ThrowsAsync <RemoteMethodNotFoundException>(() => clientRpcWithPrefix.SayHiAsync());           // "ns.SayHiAsync"

#if !NETCOREAPP1_0                                                                                                  // skip attribute-based renames where not supported
        Assert.Equal("ANDREW", await clientRpcWithCamelCase.ARoseByAsync("andrew"));                                // "anotherName"
        await Assert.ThrowsAsync <RemoteMethodNotFoundException>(() => clientRpcWithPrefix.ARoseByAsync("andrew")); // "ns.AnotherName"
#endif

        // Prepare the server to *ALSO* accept method names with a prefix.
        this.serverRpc.AllowModificationWhileListening = true;
        this.serverRpc.AddLocalRpcTarget(this.server, new JsonRpcTargetOptions {
            MethodNameTransform = prefixOptions.MethodNameTransform
        });

        // Retry with our second client proxy to send messages which the server should now accept.
        Assert.Equal("Hi!", await clientRpcWithPrefix.SayHiAsync());              // "ns.SayHiAsync"
#if !NETCOREAPP1_0                                                                // skip attribute-based renames where not supported
        Assert.Equal("ANDREW", await clientRpcWithPrefix.ARoseByAsync("andrew")); // "ns.AnotherName"
#endif
    }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
     app.Use(async(context, next) =>
     {
         if (context.WebSockets.IsWebSocketRequest)
         {
             var webSocket = await context.WebSockets.AcceptWebSocketAsync();
             using (var rpc = new JsonRpc(new WebSocketMessageHandler(webSocket), new EchoServer(webSocket)))
             {
                 rpc.StartListening();
                 await rpc.Completion;
             }
         }
         await next();
     });
 }
Пример #13
0
        private ServiceHubRemoteHostClient(
            Workspace workspace, HubClient hubClient, HostGroup hostGroup, Stream stream) :
            base(workspace)
        {
            _hubClient = hubClient;
            _hostGroup = hostGroup;
            _timeout   = TimeSpan.FromMilliseconds(workspace.Options.GetOption(RemoteHostOptions.RequestServiceTimeoutInMS));

            _rpc = new JsonRpc(stream, stream, target: this);
            _rpc.JsonSerializer.Converters.Add(AggregateJsonConverter.Instance);

            // handle disconnected situation
            _rpc.Disconnected += OnRpcDisconnected;

            _rpc.StartListening();
        }
Пример #14
0
        private static JsonRpc CreateRpc(string name, Stream duplexStream)
        {
            // Create a JsonRpcMessagePackFormatter as an IJsonRpcMessageFormatter.
            var formatter = new JsonRpcMessagePackFormatter(MyCompositeResolver.Instance);

            // Create a JsonRpc that uses the IJsonRpcMessageFormatter.
            var handler = new LengthHeaderMessageHandler(duplexStream, duplexStream, formatter);
            var rpc     = new JsonRpc(handler)
            {
                TraceSource = new TraceSource(name, SourceLevels.Verbose),
            };

            rpc.AddLocalRpcTarget(new ServerObject());
            rpc.StartListening();
            return(rpc);
        }
        public async Task <IActionResult> Socket()
        {
            if (this.HttpContext.WebSockets.IsWebSocketRequest)
            {
                var socket = await this.HttpContext.WebSockets.AcceptWebSocketAsync();

                var jsonRpc = new JsonRpc(new WebSocketMessageHandler(socket), new JsonRpcServer());
                jsonRpc.StartListening();
                await jsonRpc.Completion;
                return(new EmptyResult());
            }
            else
            {
                return(new BadRequestResult());
            }
        }
        private RazorHtmlCSharpLanguageServer(
            Stream inputStream,
            Stream outputStream,
            IEnumerable <Lazy <IRequestHandler, IRequestHandlerMetadata> > requestHandlers,
            HTMLCSharpLanguageServerLogHubLoggerProvider loggerProvider) : this(requestHandlers)
        {
            _jsonRpc = CreateJsonRpc(outputStream, inputStream, target: this);

            // Facilitates activity based tracing for structured logging within LogHub
            _jsonRpc.ActivityTracingStrategy = new CorrelationManagerTracingStrategy
            {
                TraceSource = loggerProvider.GetTraceSource()
            };

            _jsonRpc.StartListening();
        }
Пример #17
0
        private ServiceHubRemoteHostClient(
            Workspace workspace,
            ConnectionManager connectionManager,
            Stream stream)
            : base(workspace)
        {
            _connectionManager = connectionManager;

            _rpc = new JsonRpc(new JsonRpcMessageHandler(stream, stream), target: this);
            _rpc.JsonSerializer.Converters.Add(AggregateJsonConverter.Instance);

            // handle disconnected situation
            _rpc.Disconnected += OnRpcDisconnected;

            _rpc.StartListening();
        }
Пример #18
0
        public async Task Connect()
        {
            this.stream = GetStream();
            await this.stream.ConnectAsync();

            rpc           = new JsonRpc(this.stream);
            this.Instance = this.rpc.Attach <T>();
            rpc.StartListening();

            rpc.Disconnected += (_, _) =>
            {
                this.stream.Dispose();
                Disconnected?.Invoke(this, null);
                rpc.Dispose();
            };
        }
Пример #19
0
    public async Task NamingTransformsAreAppliedToEvents()
    {
        var streams = FullDuplexStream.CreateStreams();

        this.serverStream = streams.Item1;
        this.clientStream = streams.Item2;

        var camelCaseOptions = new JsonRpcProxyOptions {
            EventNameTransform = CommonMethodNameTransforms.CamelCase
        };
        var prefixOptions = new JsonRpcProxyOptions {
            EventNameTransform = CommonMethodNameTransforms.Prepend("ns.")
        };

        // Construct two client proxies with conflicting method transforms to prove that each instance returned retains its unique options.
        var clientRpc = new JsonRpc(this.clientStream, this.clientStream);
        var clientRpcWithCamelCase = clientRpc.Attach <IServer>(camelCaseOptions);
        var clientRpcWithPrefix    = clientRpc.Attach <IServer>(prefixOptions);

        clientRpc.StartListening();

        // Construct the server to only respond to one set of method names for now to confirm that the client is sending the right one.
        this.serverRpc = new JsonRpc(this.serverStream, this.serverStream);
        this.serverRpc.AddLocalRpcTarget(this.server, new JsonRpcTargetOptions {
            EventNameTransform = camelCaseOptions.EventNameTransform
        });
        this.serverRpc.StartListening();

        var          tcs     = new TaskCompletionSource <EventArgs>();
        EventHandler handler = (sender, args) => tcs.SetResult(args);

        clientRpcWithCamelCase.ItHappened += handler;
        this.server.OnItHappened(EventArgs.Empty);
        var actualArgs = await tcs.Task.WithCancellation(this.TimeoutToken);

        Assert.NotNull(actualArgs);

        clientRpcWithCamelCase.ItHappened -= handler;
        clientRpcWithPrefix.ItHappened    += handler;
        tcs = new TaskCompletionSource <EventArgs>();
        this.server.OnItHappened(EventArgs.Empty);
        await Assert.ThrowsAsync <TimeoutException>(() => tcs.Task.WithTimeout(ExpectedTimeout));

        Assert.False(tcs.Task.IsCompleted);

        clientRpcWithPrefix.ItHappened -= handler;
    }
Пример #20
0
    public async Task TraceListenerThrows_CausesDisconnect()
    {
        var pair      = FullDuplexStream.CreatePair();
        var serverRpc = new JsonRpc(pair.Item1)
        {
            TraceSource = new TraceSource(nameof(JsonRpc))
            {
                Switch    = { Level = SourceLevels.All },
                Listeners = { new ThrowingTraceListener() },
            },
        };

        serverRpc.StartListening();
        int bytesRead = await pair.Item2.ReadAsync(new byte[1], 0, 1, this.TimeoutToken);

        Assert.Equal(0, bytesRead);
    }
Пример #21
0
        public async Task InitializeCodeSearchServiceAsync()
        {
            if (_jsonRpc != null)
            {
                return;
            }

            string clientPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "AzDevOpsInteractiveClient.exe");

            string pipeName = $"AzDevOpsClientPipe-{Process.GetCurrentProcess().Id}";

            _clientProcess           = new Process();
            _clientProcess.StartInfo = new ProcessStartInfo(clientPath)
            {
                Arguments =
                    $@"--RootDir ""{_repoInfo.RootDir}"" " +
                    $@"--ProjectUri {_repoInfo.ProjectUri} " +
                    $@"--ProjectName ""{_repoInfo.ProjectName}"" " +
                    $@"--RepoName ""{_repoInfo.RepoName}"" " +
                    $@"--RpcPipeName ""{pipeName}"" ",
                UseShellExecute = false,
                CreateNoWindow  = true,
            };

            _logger.LogDebug($"FastCodeNav: Launching {clientPath} with arguments '{_clientProcess.StartInfo.Arguments}'");
            if (!_clientProcess.Start())
            {
                _logger.LogError($"FastCodeNav: Failed to launch {clientPath}");
                return;
            }

            _logger.LogDebug($"FastCodeNav: Connecting to search service client with PID {_clientProcess.Id}");
            var stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
            await stream.ConnectAsync();

            _logger.LogDebug($"FastCodeNav: Connected to search service client.");

            var jsonRpc      = new JsonRpc(stream);
            var jsonRpcProxy = jsonRpc.Attach <ICodeSearchService>();

            jsonRpc.StartListening();
            _jsonRpc = jsonRpc;

            _logger.LogDebug($"FastCodeNav: Issuing a warmup RPC request");
            _jsonRpc.InvokeAsync("WarmUpAsync").FireAndForget(_logger);
        }
Пример #22
0
    public async Task CallServerWithParameterObject()
    {
        var streams   = FullDuplexStream.CreateStreams();
        var server    = new Server();
        var serverRpc = JsonRpc.Attach(streams.Item2, server);

        var client    = new JsonRpc(streams.Item1, streams.Item1);
        var clientRpc = client.Attach <IServerWithParamsObject>(new JsonRpcProxyOptions {
            ServerRequiresNamedArguments = true
        });

        client.StartListening();

        int result = await clientRpc.SumOfParameterObject(1, 2);

        Assert.Equal(3, result);
    }
Пример #23
0
        public NeoRpcClient(Uri uri, HttpClient?httpClient = null)
        {
            var formatter = new JsonMessageFormatter();

            formatter.JsonSerializer.Converters.Add(new AccountConverter());
            formatter.JsonSerializer.Converters.Add(new BlockConverter());
            formatter.JsonSerializer.Converters.Add(new BlockHeaderConverter());
            formatter.JsonSerializer.Converters.Add(new PeersConverter());
            formatter.JsonSerializer.Converters.Add(new TransactionConverter());
            formatter.JsonSerializer.Converters.Add(new UInt256Converter());
            formatter.JsonSerializer.Converters.Add(new ValidatorConverter());

            var messageHandler = new HttpClientMessageHandler(httpClient ?? new HttpClient(), uri, formatter);

            jsonRpc = new JsonRpc(messageHandler);
            jsonRpc.StartListening();
        }
        async Task OnStartAsync()
        {
            Log("Call ActivateAsync.");

            connection = await client.ActivateAsync(CancellationToken.None);

            if (connection == null)
            {
                throw new ApplicationException("No connection returned from ActivateAsync.");
            }

            Log("JsonRpc.StartListening.");

            var target = new LanguageClientTarget(this);

            jsonRpc = new JsonRpc(connection.Writer, connection.Reader, target);

            jsonRpc.Disconnected += JsonRpcDisconnected;

            InitializeCustomClientProviders();

            var customClient = client as ILanguageClientCustomMessage;

            if (customClient != null)
            {
                Log("Adding LanguageClientCustomMessage.");

                if (customClient.CustomMessageTarget != null)
                {
                    jsonRpc.AddLocalRpcTarget(customClient.CustomMessageTarget);
                }

                await customClient.AttachForCustomMessageAsync(jsonRpc);
            }

            jsonRpc.StartListening();
            jsonRpc.JsonSerializer.NullValueHandling = NullValueHandling.Ignore;

            InitializeResult result = await Initialize();

            ServerCapabilities = result.Capabilities;
            OnServerCapabilitiesChanged();

            await SendConfigurationSettings();
        }
        public RazorHtmlCSharpLanguageServer(
            Stream inputStream,
            Stream outputStream,
            IEnumerable <Lazy <IRequestHandler, IRequestHandlerMetadata> > requestHandlers) : this(requestHandlers)
        {
            if (inputStream is null)
            {
                throw new ArgumentNullException(nameof(inputStream));
            }

            if (outputStream is null)
            {
                throw new ArgumentNullException(nameof(outputStream));
            }

            _jsonRpc = CreateJsonRpc(outputStream, inputStream, target: this);
            _jsonRpc.StartListening();
        }
Пример #26
0
            public DataPoint(
                ReferenceCodeLensProvider owner,
                ICodeLensCallbackService callbackService,
                CodeLensDescriptor descriptor,
                Stream stream)
            {
                _owner           = owner;
                _callbackService = callbackService;

                Descriptor = descriptor;

                _roslynRpc = stream.CreateStreamJsonRpc(
                    target: new RoslynCallbackTarget(Invalidate),
                    owner._client.Logger,
                    SpecializedCollections.SingletonEnumerable(AggregateJsonConverter.Instance));

                _roslynRpc.StartListening();
            }
Пример #27
0
        private ServiceHubRemoteHostClient(
            Workspace workspace,
            TraceSource logger,
            ConnectionManager connectionManager,
            Stream stream)
            : base(workspace)
        {
            _shutdownCancellationTokenSource = new CancellationTokenSource();

            _connectionManager = connectionManager;

            _rpc = stream.CreateStreamJsonRpc(target: this, logger);

            // handle disconnected situation
            _rpc.Disconnected += OnRpcDisconnected;

            _rpc.StartListening();
        }
        public async Task RunAsync(CancellationToken cancellationToken)
        {
            using var semaphore = new SemaphoreSlim(_maxConnection, _maxConnection);
            while (!cancellationToken.IsCancellationRequested)
            {
                await semaphore.WaitAsync(cancellationToken);

                try
                {
                    _logger.LogInformation("create pipe.");
                    var stream = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, _maxConnection, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                    _logger.LogInformation("wait for connection.");
                    await stream.WaitForConnectionAsync(cancellationToken);

                    _logger.LogInformation("create target.");
                    var rpc = new JsonRpc(stream);
                    try
                    {
                        var target = OnConnect(rpc);
                        rpc.AddLocalRpcTarget <T>(target, null);
                        rpc.StartListening();
                        rpc.Disconnected += (o, e) =>
                        {
                            _logger.LogInformation("disconnected. {reason} - {description}", e.Reason, e.Description);
                            semaphore.Release();
                        };
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, "create target fail.");
                        semaphore.Release();
                    }
                }
                catch (Exception e)
                {
                    if (!cancellationToken.IsCancellationRequested)
                    {
                        _logger.LogError(e, "create connection fail.");
                    }
                    semaphore.Release();
                }
            }
        }
Пример #29
0
        public InProcLanguageServer(
            AbstractInProcLanguageClient languageClient,
            Stream inputStream,
            Stream outputStream,
            AbstractRequestHandlerProvider requestHandlerProvider,
            Workspace workspace,
            IDiagnosticService?diagnosticService,
            IAsynchronousOperationListenerProvider listenerProvider,
            ILspSolutionProvider solutionProvider,
            string?clientName)
        {
            _languageClient         = languageClient;
            _requestHandlerProvider = requestHandlerProvider;
            _workspace = workspace;

            var jsonMessageFormatter = new JsonMessageFormatter();

            jsonMessageFormatter.JsonSerializer.Converters.Add(new VSExtensionConverter <TextDocumentIdentifier, VSTextDocumentIdentifier>());
            jsonMessageFormatter.JsonSerializer.Converters.Add(new VSExtensionConverter <ClientCapabilities, VSClientCapabilities>());

            _jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, jsonMessageFormatter));
            _jsonRpc.AddLocalRpcTarget(this);
            _jsonRpc.StartListening();

            _diagnosticService = diagnosticService;
            _listener          = listenerProvider.GetListener(FeatureAttribute.LanguageServer);
            _clientName        = clientName;

            _queue = new RequestExecutionQueue(solutionProvider);
            _queue.RequestServerShutdown += RequestExecutionQueue_Errored;

            // Dedupe on DocumentId.  If we hear about the same document multiple times, we only need to process that id once.
            _diagnosticsWorkQueue = new AsyncBatchingWorkQueue <DocumentId>(
                TimeSpan.FromMilliseconds(250),
                ProcessDiagnosticUpdatedBatchAsync,
                EqualityComparer <DocumentId> .Default,
                _listener,
                _queue.CancellationToken);

            if (_diagnosticService != null)
            {
                _diagnosticService.DiagnosticsUpdated += DiagnosticService_DiagnosticsUpdated;
            }
        }
Пример #30
0
        internal async Task <int> RunAsync()
        {
            Logger.LogInformation($"AzDevOpsInteractiveClient is running");

            if (_opts.WaitDebug)
            {
                while (!Debugger.IsAttached)
                {
                    Logger.LogInformation("Awaiting for an attached debugger");
                    await Task.Delay(TimeSpan.FromMilliseconds(500));
                }
            }

            try
            {
                // Create and asyncronously initialize Azure DevOps client
                var service = new AzureDevOpsCodeSearchService(LoggerFactoryInstance, _opts);
                service.InitializeAsync().FireAndForget(Logger);

                Logger.LogInformation($"Waiting for client to make a connection to pipe {_opts.RpcPipeName} for repo {_opts.ProjectUri}");
                using (var stream = new NamedPipeServerStream(_opts.RpcPipeName,
                                                              PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                {
                    await stream.WaitForConnectionAsync();

                    using (var jsonRpc = new JsonRpc(stream))
                    {
                        jsonRpc.AddLocalRpcTarget(service);
                        jsonRpc.StartListening();
                        await jsonRpc.Completion;
                    }
                }

                Logger.LogInformation($"AzDevOpsInteractiveClient is existing");
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Failure while processing RPC requests");
                return(1);
            }

            return(0);
        }