示例#1
0
        private void OnStreamClose(Task copyAsyncTask)
        {
            _memory.Return(_block);

            if (copyAsyncTask.IsFaulted)
            {
                SocketInput.AbortAwaiting();
                Service.Logger.Log(copyAsyncTask.Exception);
            }
            else if (copyAsyncTask.IsCanceled)
            {
                SocketInput.AbortAwaiting();
                Service.Logger.Log(LogLevel.Error, "FilteredStreamAdapter.CopyToAsync canceled.");
            }
            else if (_aborted)
            {
                SocketInput.AbortAwaiting();
            }

            try
            {
                SocketInput.IncomingFin();
            }
            catch (Exception ex)
            {
                Service.Logger.Log(ex);
            }
        }
示例#2
0
        public void LeadingWhitespaceIsNotIncludedInHeaderValue(string rawHeaders)
        {
            var trace = new KestrelTrace(new TestKestrelTrace());
            var ltp   = new LoggingThreadPool(trace);

            using (var pool = new MemoryPool())
                using (var socketInput = new SocketInput(pool, ltp))
                {
                    var connectionContext = new ConnectionContext()
                    {
                        DateHeaderValueManager = new DateHeaderValueManager(),
                        ServerAddress          = ServerAddress.FromUrl("http://localhost:5000")
                    };
                    var frame = new Frame <object>(application: null, context: connectionContext);
                    frame.InitializeHeaders();

                    var headerArray = Encoding.ASCII.GetBytes(rawHeaders);
                    socketInput.IncomingData(headerArray, 0, headerArray.Length);

                    var success = frame.TakeMessageHeaders(socketInput, (FrameRequestHeaders)frame.RequestHeaders);

                    Assert.True(success);
                    Assert.Equal(1, frame.RequestHeaders.Count);
                    Assert.Equal("value", frame.RequestHeaders["Header"]);

                    // Assert TakeMessageHeaders consumed all the input
                    var scan = socketInput.ConsumingStart();
                    Assert.True(scan.IsEnd);
                }
        }
    private void OnOutputDragDroppedTo(SocketInput target)
    {
        //  if sockets connected already
        //  do nothing
        if (_currentDraggingSocket.HasConnection() && target.HasConnection())
        {
            if (_currentDraggingSocket.connection == target.connection)
            {
                _currentDraggingSocket = null;
                drawer.CancelDrag();

                return;
            }
        }

        if (target != null)
        {
            //  check if input allows multiple connection
            if (target.HasConnection())
            {
                //  disconnect old connection
                if (target.connectionType != ConnectionType.Multiple)
                {
                    Disconnect(target.connection);
                }
            }

            Connect(target, _currentDraggingSocket);
        }

        _currentDraggingSocket = null;
        drawer.CancelDrag();
    }
    public override void OnDisconnect(SocketInput input, IOutput output)
    {
        _receivedOutputs.Remove(output);
        output.ValueUpdated -= OnConnectedValueUpdated;

        OnConnectedValueUpdated();
    }
    public override void OnConnection(SocketInput input, IOutput output)
    {
        _receivedOutputs.Add(output);
        output.ValueUpdated += OnConnectedValueUpdated;

        OnConnectedValueUpdated();
    }
        public void ConsumingOutOfOrderFailsGracefully()
        {
            var defultIter = new MemoryPoolIterator();

            // Calling ConsumingComplete without a preceding calling to ConsumingStart fails
            using (var socketInput = new SocketInput(null, null))
            {
                Assert.Throws <InvalidOperationException>(() => socketInput.ConsumingComplete(defultIter, defultIter));
            }

            // Calling ConsumingComplete twice in a row fails
            using (var socketInput = new SocketInput(null, null))
            {
                socketInput.ConsumingStart();
                socketInput.ConsumingComplete(defultIter, defultIter);
                Assert.Throws <InvalidOperationException>(() => socketInput.ConsumingComplete(defultIter, defultIter));
            }

            // Calling ConsumingStart twice in a row fails
            using (var socketInput = new SocketInput(null, null))
            {
                socketInput.ConsumingStart();
                Assert.Throws <InvalidOperationException>(() => socketInput.ConsumingStart());
            }
        }
示例#7
0
        private void OnStreamClose(Task copyAsyncTask)
        {
            _memory.Return(_block);

            if (copyAsyncTask.IsFaulted)
            {
                SocketInput.AbortAwaiting();
                _log.LogError(0, copyAsyncTask.Exception, "FilteredStreamAdapter.CopyToAsync");
            }
            else if (copyAsyncTask.IsCanceled)
            {
                SocketInput.AbortAwaiting();
                _log.LogError("FilteredStreamAdapter.CopyToAsync canceled.");
            }
            else if (_aborted)
            {
                SocketInput.AbortAwaiting();
            }

            try
            {
                _socketInputStream.Dispose();
            }
            catch (Exception ex)
            {
                _log.LogError(0, ex, "FilteredStreamAdapter.OnStreamClose");
            }
        }
示例#8
0
        public void EmptyHeaderValuesCanBeParsed(string rawHeaders, int numHeaders)
        {
            var trace = new KestrelTrace(new TestKestrelTrace());
            var ltp   = new LoggingThreadPool(trace);

            using (var pool = new MemoryPool())
                using (var socketInput = new SocketInput(pool, ltp))
                {
                    var connectionContext = new ConnectionContext()
                    {
                        DateHeaderValueManager = new DateHeaderValueManager(),
                        ServerAddress          = ServerAddress.FromUrl("http://localhost:5000")
                    };
                    var frame            = new Frame <object>(application: null, context: connectionContext);
                    var headerCollection = new FrameRequestHeaders();

                    var headerArray = Encoding.ASCII.GetBytes(rawHeaders);
                    socketInput.IncomingData(headerArray, 0, headerArray.Length);

                    var success = frame.TakeMessageHeaders(socketInput, headerCollection);

                    Assert.True(success);
                    Assert.Equal(numHeaders, headerCollection.Count());

                    // Assert TakeMessageHeaders consumed all the input
                    var scan = socketInput.ConsumingStart();
                    Assert.True(scan.IsEnd);
                }
        }
 //  event handlers
 private void OnInputSocketClicked(SocketInput input, PointerEventData eventData)
 {
     if (eventData.button == PointerEventData.InputButton.Right)
     {
         connections.Where(conn => conn.input == input)
         .ToList()
         .ForEach(conn => Disconnect(conn));
     }
 }
示例#10
0
        private async Task FilterInputAsync(MemoryPoolBlock block)
        {
            int bytesRead;

            while ((bytesRead = await _filteredStream.ReadAsync(block.Array, block.Data.Offset, block.Data.Count)) != 0)
            {
                SocketInput.IncomingData(block.Array, block.Data.Offset, bytesRead);
            }
        }
 public void IncomingCompleteCallsBufferSizeControlAdd(Mock <IBufferSizeControl> mockBufferSizeControl)
 {
     using (var memory = new MemoryPool())
         using (var socketInput = new SocketInput(memory, null, mockBufferSizeControl?.Object))
         {
             socketInput.IncomingComplete(5, null);
             mockBufferSizeControl?.Verify(b => b.Add(5));
         }
 }
 public void IncomingDataCallsBufferSizeControlAdd(Mock <IBufferSizeControl> mockBufferSizeControl)
 {
     using (var memory = new MemoryPool())
         using (var socketInput = new SocketInput(memory, null, mockBufferSizeControl?.Object))
         {
             socketInput.IncomingData(new byte[5], 0, 5);
             mockBufferSizeControl?.Verify(b => b.Add(5));
         }
 }
        public FilteredStreamAdapter(
            string connectionId,
            Stream filteredStream,
            MemoryPool memory,
            IKestrelTrace logger,
            IThreadPool threadPool,
            IBufferSizeControl bufferSizeControl)
        {
            SocketInput  = new SocketInput(memory, threadPool, bufferSizeControl);
            SocketOutput = new StreamSocketOutput(connectionId, filteredStream, memory, logger);

            _filteredStream = filteredStream;
        }
示例#14
0
        /// <summary>
        /// Creates a new connection from the listener context.
        /// </summary>
        /// <param name="context">The listener context to use.</param>
        /// <param name="socket">The socket handle.</param>
        internal Connection(ListenerContext context, UvStreamHandle socket) : base(context)
        {
            _socket           = socket;
            socket.Connection = this;

            ConnectionId = ConnectionId.NewConnectionId();

            _rawSocketInput  = new SocketInput(Memory, ThreadPool);
            _rawSocketOutput = new SocketOutput(Thread, _socket, Memory, this, ConnectionId, ThreadPool, WriteReqPool);

            this.Expires = Timer.Now + TimeSpan.FromMinutes(1);
            this.ConnectionManager.Register(this);
        }
示例#15
0
        public FilteredStreamAdapter(
            ConnectionId connectionId,
            Stream filteredStream,
            MemoryPool memory,
            IThreadPool threadPool,
            IBufferSizeControl bufferSizeControl)
        {
            SocketInput  = new SocketInput(memory, threadPool, bufferSizeControl);
            SocketOutput = new StreamSocketOutput(connectionId, filteredStream, memory);

            _connectionId   = connectionId;
            _filteredStream = filteredStream;
            _memory         = memory;
        }
示例#16
0
        public FilteredStreamAdapter(
            string connectionId,
            Stream filteredStream,
            MemoryPool memory,
            IKestrelTrace logger,
            IThreadPool threadPool)
        {
            SocketInput  = new SocketInput(memory, threadPool);
            SocketOutput = new StreamSocketOutput(connectionId, filteredStream, memory, logger);

            _connectionId   = connectionId;
            _log            = logger;
            _filteredStream = filteredStream;
            _memory         = memory;
        }
示例#17
0
    public void Connect(SocketInput input, SocketOutput output)
    {
        var connection = new Connection()
        {
            id     = CreateId,
            input  = input,
            output = output
        };

        input.Connect(connection);
        output.Connect(connection);

        connections.Add(connection);
        input.parentNode.OnConnection(input, output);

        drawer.Add(connection.id, output.handle, input.handle);
    }
        public FilteredStreamAdapter(
            Stream filteredStream,
            MemoryPool2 memory,
            IKestrelTrace logger)
        {
            SocketInput  = new SocketInput(memory);
            SocketOutput = new StreamSocketOutput(filteredStream);

            _log               = logger;
            _filteredStream    = filteredStream;
            _socketInputStream = new SocketInputStream(SocketInput);

            _filteredStream.CopyToAsync(_socketInputStream).ContinueWith((task, state) =>
            {
                ((FilteredStreamAdapter)state).OnStreamClose(task);
            }, this);
        }
        public void ConsumingCompleteCallsBufferSizeControlSubtract(Mock <IBufferSizeControl> mockBufferSizeControl)
        {
            using (var kestrelEngine = new KestrelEngine(new MockLibuv(), new TestServiceContext()))
            {
                kestrelEngine.Start(1);

                using (var memory = new MemoryPool())
                    using (var socketInput = new SocketInput(memory, null, mockBufferSizeControl?.Object))
                    {
                        socketInput.IncomingData(new byte[20], 0, 20);

                        var iterator = socketInput.ConsumingStart();
                        iterator.Skip(5);
                        socketInput.ConsumingComplete(iterator, iterator);
                        mockBufferSizeControl?.Verify(b => b.Subtract(5));
                    }
            }
        }
示例#20
0
        public void EmptyHeaderValuesCanBeParsed(string rawHeaders, int numHeaders)
        {
            var socketInput      = new SocketInput(new MemoryPool2());
            var headerCollection = new FrameRequestHeaders();

            var headerArray = Encoding.ASCII.GetBytes(rawHeaders);
            var inputBuffer = socketInput.IncomingStart(headerArray.Length);

            Buffer.BlockCopy(headerArray, 0, inputBuffer.Data.Array, inputBuffer.Data.Offset, headerArray.Length);
            socketInput.IncomingComplete(headerArray.Length, null);

            var success = Frame.TakeMessageHeaders(socketInput, headerCollection);

            Assert.True(success);
            Assert.Equal(numHeaders, headerCollection.Count());

            // Assert TakeMessageHeaders consumed all the input
            var scan = socketInput.ConsumingStart();

            Assert.True(scan.IsEnd);
        }
        public async Task ReadInputAsync()
        {
            int bytesRead;

            do
            {
                var block = SocketInput.IncomingStart();

                try
                {
                    var count = block.Data.Offset + block.Data.Count - block.End;
                    bytesRead = await _filteredStream.ReadAsync(block.Array, block.End, count);
                }
                catch (Exception ex)
                {
                    SocketInput.IncomingComplete(0, ex);
                    throw;
                }

                SocketInput.IncomingComplete(bytesRead, error: null);
            } while (bytesRead != 0);
        }
示例#22
0
        public void ThrowsOnHeadersNotEndingInCRLFLine(string rawHeaders)
        {
            var trace = new KestrelTrace(new TestKestrelTrace());
            var ltp   = new LoggingThreadPool(trace);

            using (var pool = new MemoryPool())
                using (var socketInput = new SocketInput(pool, ltp))
                {
                    var connectionContext = new ConnectionContext()
                    {
                        DateHeaderValueManager = new DateHeaderValueManager(),
                        ServerAddress          = ServerAddress.FromUrl("http://localhost:5000"),
                        Log = trace
                    };
                    var frame = new Frame <object>(application: null, context: connectionContext);
                    frame.InitializeHeaders();

                    var headerArray = Encoding.ASCII.GetBytes(rawHeaders);
                    socketInput.IncomingData(headerArray, 0, headerArray.Length);

                    Assert.Throws <BadHttpRequestException>(() => frame.TakeMessageHeaders(socketInput, (FrameRequestHeaders)frame.RequestHeaders));
                }
        }
        public FilteredStreamAdapter(
            Stream filteredStream,
            MemoryPool2 memory,
            IKestrelTrace logger,
            IThreadPool threadPool)
        {
            SocketInput  = new SocketInput(memory, threadPool);
            SocketOutput = new StreamSocketOutput(filteredStream, memory);

            _log               = logger;
            _filteredStream    = filteredStream;
            _socketInputStream = new SocketInputStream(SocketInput);

            var block = memory.Lease();

            // Use pooled block for copy
            _filteredStream.CopyToAsync(_socketInputStream, block).ContinueWith((task, state) =>
            {
                var returnedBlock = task.Result;
                returnedBlock.Pool.Return(returnedBlock);

                ((FilteredStreamAdapter)state).OnStreamClose(task);
            }, this);
        }
示例#24
0
 public LibuvStream(SocketInput input, ISocketOutput output)
 {
     _input  = input;
     _output = output;
 }
示例#25
0
 public virtual void OnDisconnect(SocketInput input, IOutput output)
 {
 }
 public SocketInputStream(SocketInput socketInput)
 {
     _socketInput = socketInput;
 }
        public async Task ConcurrentReadsFailGracefully()
        {
            // Arrange
            var trace = new KestrelTrace(new TestKestrelTrace());
            var ltp   = new LoggingThreadPool(trace);

            using (var memory2 = new MemoryPool())
                using (var socketInput = new SocketInput(memory2, ltp))
                {
                    var task0Threw = false;
                    var task1Threw = false;
                    var task2Threw = false;

                    var task0 = AwaitAsTaskAsync(socketInput);

                    Assert.False(task0.IsFaulted);

                    var task = task0.ContinueWith(
                        (t) =>
                    {
                        TestConcurrentFaultedTask(t);
                        task0Threw = true;
                    },
                        TaskContinuationOptions.OnlyOnFaulted);

                    Assert.False(task0.IsFaulted);

                    // Awaiting/continuing two tasks faults both

                    var task1 = AwaitAsTaskAsync(socketInput);

                    await task1.ContinueWith(
                        (t) =>
                    {
                        TestConcurrentFaultedTask(t);
                        task1Threw = true;
                    },
                        TaskContinuationOptions.OnlyOnFaulted);

                    await task;

                    Assert.True(task0.IsFaulted);
                    Assert.True(task1.IsFaulted);

                    Assert.True(task0Threw);
                    Assert.True(task1Threw);

                    // socket stays faulted

                    var task2 = AwaitAsTaskAsync(socketInput);

                    await task2.ContinueWith(
                        (t) =>
                    {
                        TestConcurrentFaultedTask(t);
                        task2Threw = true;
                    },
                        TaskContinuationOptions.OnlyOnFaulted);

                    Assert.True(task2.IsFaulted);
                    Assert.True(task2Threw);
                }
        }
示例#28
0
 public void Dispose()
 {
     SocketInput.Dispose();
 }
示例#29
0
 public virtual void OnConnection(SocketInput input, IOutput output)
 {
 }
 private async Task AwaitAsTaskAsync(SocketInput socketInput)
 {
     await socketInput;
 }