Пример #1
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.");
        }
Пример #2
0
 public void Dispose()
 {
     sourceFiles.Clear();
     rpc.Dispose();
     disconnectEvent.Dispose();
     waitForInit?.Dispose();
 }
Пример #3
0
        public void Dispose()
        {
            OnDisposed();

            _rpc.Dispose();
            _stream.Dispose();
        }
Пример #4
0
        public void Dispose()
        {
            Rpc.Dispose();
            Dispose(false);

            Logger.TraceInformation($"{DebugInstanceString} Service instance disposed");
        }
 protected override void OnDisconnected()
 {
     // we are asked to disconnect. unsubscribe and dispose to disconnect.
     // there are 2 ways to get disconnected. one is Roslyn decided to disconnect with RemoteHost (ex, cancellation or recycle OOP) and
     // the other is external thing disconnecting remote host from us (ex, user killing OOP process).
     // the Disconnected event we subscribe is to detect #2 case. and this method is for #1 case. so when we are willingly disconnecting
     // we don't need the event, otherwise, Disconnected event will be called twice.
     _rpc.Disconnected -= OnRpcDisconnected;
     _rpc.Dispose();
 }
    public void IsDisposedReturnsTrueWhenJsonRpcIsDisposed()
    {
        JsonRpc jsonRpc = ((IJsonRpcClientProxy)this.clientRpc).JsonRpc;

        jsonRpc.Dispose();

        var disposableClient = (IDisposableObservable)this.clientRpc;

        Assert.True(disposableClient.IsDisposed);
    }
Пример #7
0
 public virtual void Dispose()
 {
     try
     {
         _stream?.Dispose();
         _rpc?.Dispose();
     }
     catch
     {
         // this shouldn't throw but it does in netcore
     }
 }
Пример #8
0
 protected override void OnStopped()
 {
     // we are asked to stop. unsubscribe and dispose to disconnect.
     // there are 2 ways to get disconnected. one is Roslyn decided to disconnect with RemoteHost (ex, cancellation or recycle OOP) and
     // the other is external thing disconnecting remote host from us (ex, user killing OOP process).
     // the Disconnected event we subscribe is to detect #2 case. and this method is for #1 case. so when we are willingly disconnecting
     // we don't need the event, otherwise, Disconnected event will be called twice.
     UnregisterGlobalOperationNotifications();
     UnregisterPersistentStorageLocationServiceChanges();
     _rpc.Disconnected -= OnRpcDisconnected;
     _rpc.Dispose();
     _connectionManager.Shutdown();
 }
Пример #9
0
 private void ExitImpl()
 {
     try
     {
         ShutdownRequestQueue();
         _jsonRpc.Dispose();
     }
     catch (Exception e) when(FatalError.ReportAndCatch(e))
     {
         // Swallow exceptions thrown by disposing our JsonRpc object. Disconnected events can potentially throw their own exceptions so
         // we purposefully ignore all of those exceptions in an effort to shutdown gracefully.
     }
 }
Пример #10
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             m_cts.Dispose();
             m_JsonRpc.Dispose();
             m_TcpClient.Close();
         }
         disposedValue = true;
     }
 }
 public void Dispose()
 {
     try
     {
         if (!_jsonRpc.IsDisposed)
         {
             _jsonRpc.Dispose();
         }
     }
     catch (Exception)
     {
         // Swallow exceptions thrown by disposing our JsonRpc object. Disconnected events can potentially throw their own exceptions so
         // we purposefully ignore all of those exceptions in an effort to shutdown gracefully.
     }
 }
        public Task ExitAsync(CancellationToken _)
        {
            try
            {
                ShutdownRequestQueue();
                _jsonRpc.Dispose();
            }
            catch (Exception e) when(FatalError.ReportAndCatch(e))
            {
                // Swallow exceptions thrown by disposing our JsonRpc object. Disconnected events can potentially throw their own exceptions so
                // we purposefully ignore all of those exceptions in an effort to shutdown gracefully.
            }

            return(Task.CompletedTask);
        }
Пример #13
0
        public Task ExitAsync(CancellationToken _)
        {
            Contract.ThrowIfFalse(_shuttingDown, "Shutdown has not been called yet.");

            try
            {
                _jsonRpc.Dispose();
            }
            catch (Exception e) when(FatalError.ReportWithoutCrash(e))
            {
                // Swallow exceptions thrown by disposing our JsonRpc object. Disconnected events can potentially throw their own exceptions so
                // we purposefully ignore all of those exceptions in an effort to shutdown gracefully.
            }

            return(Task.CompletedTask);
        }
Пример #14
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();
            };
        }
Пример #15
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            m_ConnectionCheckCancellationTokenSource.Cancel();
            if (m_ConnectionCheckTask != null)
            {
                if (m_ConnectionCheckTask.Status == TaskStatus.RanToCompletion
                    || m_ConnectionCheckTask.Status == TaskStatus.Faulted
                    || m_ConnectionCheckTask.Status == TaskStatus.Canceled)
                    m_ConnectionCheckTask.Dispose();
            }

            m_JsonRpc.Dispose();
            m_Stream.Dispose();
            m_TcpClient.Dispose();
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
Пример #16
0
        public void Dispose()
        {
            if (_disposed)
            {
                // guard us from double disposing. this can happen in unit test
                // due to how we create test mock service hub stream that tied to
                // remote host service
                return;
            }

            _disposed = true;
            _rpc.Dispose();

            Dispose(disposing: true);

            Logger.TraceInformation($"{DebugInstanceString} Service instance disposed");
        }
 void Dispose()
 {
     try {
         if (jsonRpc != null)
         {
             jsonRpc.Dispose();
             jsonRpc = null;
         }
         if (connection != null)
         {
             connection.Dispose();
             connection = null;
         }
     } catch (IOException ex) {
         // Ignore.
         LanguageClientLoggingService.LogError("JsonRpc.Dispose error.", ex);
     }
 }
Пример #18
0
    public async Task SendMessageWithEncoding(string encodingName)
    {
        var messageHandler = new HeaderDelimitedMessageHandler(this.clientStream, this.clientStream);
        var rpcClient      = new JsonRpc(messageHandler);

        messageHandler.Encoding = Encoding.GetEncoding(encodingName);
        await rpcClient.NotifyAsync("Foo").WithCancellation(this.TimeoutToken);

        rpcClient.Dispose();

        MemoryStream seekableServerStream = await this.GetSeekableServerStream();

        int    bytesRead   = 0;
        var    reader      = new StreamReader(seekableServerStream, Encoding.ASCII);
        var    headerLines = new List <string>();
        string?line;

        while ((line = await reader.ReadLineAsync().WithCancellation(this.TimeoutToken)) != string.Empty)
        {
            Assumes.NotNull(line);
            headerLines.Add(line);
            bytesRead += line.Length + 2; // + CRLF
        }

        bytesRead += 2; // final CRLF
        this.Logger.WriteLine(string.Join(Environment.NewLine, headerLines));

        // utf-8 headers may not be present because they are the default, per the protocol spec.
        if (encodingName != "utf-8")
        {
            Assert.Contains(headerLines, l => l.Contains($"charset={encodingName}"));
        }

        // Because the first StreamReader probably read farther (to fill its buffer) than the end of the headers,
        // we need to reposition the stream at the start of the content to create a new StreamReader.
        seekableServerStream.Position = bytesRead;
        reader = new StreamReader(seekableServerStream, Encoding.GetEncoding(encodingName));
        string json = await reader.ReadToEndAsync().WithCancellation(this.TimeoutToken);

        Assert.Equal('{', json[0]);
    }
 protected override void OnDisconnected()
 {
     _rpc.Dispose();
 }
Пример #20
0
 protected void Disconnect()
 {
     _rpc.Dispose();
 }
Пример #21
0
 public void Dispose()
 {
     _rpc.Disconnected -= OnDisconnected;
     _rpc.Dispose();
 }
 public void Dispose()
 {
     _jsonRpc.Dispose();
 }
Пример #23
0
 public void Dispose()
 {
     rpc?.Dispose();
     this.connection?.Dispose();
 }
 public void Disconnect()
 {
     _jsonRpc.Dispose();
     _pipeStream.Dispose();
 }
 public void Dispose()
 {
     _rpc.Dispose();
     _process.Kill(true);
     _process.Dispose();
 }
Пример #26
0
 public virtual void Dispose()
 {
     _stream?.Dispose();
     _rpc?.Dispose();
 }