public override Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress) { var ch = _channel; if (!ch.Open) { return(CreateClosedChannelExceptionTask()); } try { if (ch._connectPromise is object) { ThrowHelper.ThrowInvalidOperationException_ConnAttempt(); } ch._connectPromise = ch.NewPromise(remoteAddress); // Schedule connect timeout. TimeSpan connectTimeout = ch.Configuration.ConnectTimeout; if (connectTimeout > TimeSpan.Zero) { ch._connectCancellationTask = ch.EventLoop .Schedule(CancelConnectAction, ch, remoteAddress, connectTimeout); } ch.DoConnect(remoteAddress, localAddress); return(ch._connectPromise.Task); } catch (Exception ex) { CloseIfClosed(); return(TaskUtil.FromException(AnnotateConnectException(ex, remoteAddress))); } }
/// <summary> /// Creates a new instance. /// </summary> /// <param name="channel">channel the <see cref="IChannel"/> associated with this future</param> /// <param name="fireException"></param> public VoidChannelPromise(IChannel channel, bool fireException) { if (channel is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.channel); } _channel = channel; _fireException = fireException; _task = new Lazy <Task>(() => TaskUtil.FromException(Error), LazyThreadSafetyMode.ExecutionAndPublication); }
/// <summary> /// Creates a new instance. /// </summary> /// <param name="channel">channel the <see cref="IChannel"/> associated with this future</param> /// <param name="fireException"></param> public VoidChannelPromise(IChannel channel, bool fireException) { if (channel is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.channel); } _channel = channel; _fireException = fireException; Task = TaskUtil.FromException(Error); }
public Task <EndPoint> ResolveAsync(EndPoint address) { if (_success) { return(Task.FromResult(address)); } else { return(TaskUtil.FromException <EndPoint>(new System.Net.Sockets.SocketException())); } }
//public AbstractSocketChannel Channel => (AbstractSocketChannel)this.channel; //public TChannel Channel => this.channel; public sealed override Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress) { // todo: handle cancellation var ch = _channel; if (!ch.Open) { return(CreateClosedChannelExceptionTask()); } try { if (ch._connectPromise is object) { ThrowHelper.ThrowInvalidOperationException_ConnAttemptAlreadyMade(); } bool wasActive = _channel.Active; if (ch.DoConnect(remoteAddress, localAddress)) { FulfillConnectPromise(ch._connectPromise, wasActive); return(TaskUtil.Completed); } else { ch._connectPromise = ch.NewPromise(remoteAddress); // Schedule connect timeout. TimeSpan connectTimeout = ch.Configuration.ConnectTimeout; if (connectTimeout > TimeSpan.Zero) { ch._connectCancellationTask = ch.EventLoop.Schedule( ConnectTimeoutAction, _channel, remoteAddress, connectTimeout); } _ = ch._connectPromise.Task.ContinueWith(CloseSafeOnCompleteAction, ch, TaskContinuationOptions.OnlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously); return(ch._connectPromise.Task); } } catch (Exception ex) { CloseIfClosed(); return(TaskUtil.FromException(AnnotateConnectException(ex, remoteAddress))); } }
public Task BindAsync(EndPoint localAddress) { AssertEventLoop(); var ch = _channel; // TODO: cancellation support if (/*!promise.setUncancellable() || */ !ch.Open) { return(CreateClosedChannelExceptionTask()); } //// See: https://github.com/netty/netty/issues/576 //if (bool.TrueString.Equals(this.channel.Configuration.getOption(ChannelOption.SO_BROADCAST)) && // localAddress is IPEndPoint && // !((IPEndPoint)localAddress).Address.getAddress().isAnyLocalAddress() && // !Environment.OSVersion.Platform == PlatformID.Win32NT && !Environment.isRoot()) //{ // // Warn a user about the fact that a non-root user can't receive a // // broadcast packet on *nix if the socket is bound on non-wildcard address. // logger.Warn( // "A non-root user can't receive a broadcast packet if the socket " + // "is not bound to a wildcard address; binding to a non-wildcard " + // "address (" + localAddress + ") anyway as requested."); //} bool wasActive = ch.Active; try { ch.DoBind(localAddress); } catch (Exception t) { CloseIfClosed(); return(TaskUtil.FromException(t)); } if (!wasActive && ch.Active) { InvokeLater(() => ch._pipeline.FireChannelActive()); } return(TaskUtil.Completed); }
protected virtual Task HandleRespondException(ExceptionInformation exceptionInfo, IPipeContext context) { _logger.Info("An unhandled exception occured when remote tried to handle request.\n Message: {exceptionMessage}\n Stack Trace: {stackTrace}", exceptionInfo.Message, exceptionInfo.StackTrace); if (HandlerFunc != null) { return(HandlerFunc(exceptionInfo, context)); } var exception = new MessageHandlerException(exceptionInfo.Message) { InnerExceptionType = exceptionInfo.ExceptionType, InnerStackTrace = exceptionInfo.StackTrace, InnerMessage = exceptionInfo.InnerMessage }; return(TaskUtil.FromException(exception)); }
/// <summary> /// If the pool implementation supports asynchronous close, then use it to avoid a blocking close call in case /// the ChannelPoolMap operations are called from an EventLoop. /// </summary> /// <param name="pool">the ChannelPool to be closed</param> /// <returns></returns> private static Task PoolCloseAsyncIfSupported(IChannelPool pool) { if (pool is SimpleChannelPool simpleChannelPool) { return(simpleChannelPool.CloseAsync()); } else { try { pool.Close(); return(TaskUtil.Completed); } catch (Exception exc) { return(TaskUtil.FromException(exc)); } } }
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); } if ((uint)offset > SharedConstants.TooBigOrNegative) { ThrowHelper.ThrowArgumentOutOfRangeException_NeedNonNegNum(ExceptionArgument.offset); } if ((uint)count > SharedConstants.TooBigOrNegative) { ThrowHelper.ThrowArgumentOutOfRangeException_NeedNonNegNum(ExceptionArgument.count); } if ((uint)buffer.Length < (uint)(offset + count)) { ThrowHelper.ThrowArgumentException_InvalidOffLen(); } EnsureNotClosed(); EnsureWriteable(); // If cancellation is already requested, bail early if (cancellationToken.IsCancellationRequested) { return(TaskUtil.FromCanceled(cancellationToken)); } try { _ = _buffer.WriteBytes(buffer, offset, count); return(TaskUtil.Completed); } //catch (OperationCanceledException oce) //{ // return Task.FromCancellation<VoidTaskResult>(oce); //} catch (Exception exception) { return(TaskUtil.FromException(exception)); } }
public override Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(TaskUtil.FromCanceled <int>(cancellationToken)); } try { var readNum = Read(buffer, offset, count); return(Task.FromResult(readNum)); } //catch (OperationCanceledException oce) //{ // return Task.FromCancellation<int>(oce); //} catch (Exception ex2) { return(TaskUtil.FromException <int>(ex2)); } }
/// <summary> /// Release all buffers in the queue and complete all listeners and promises. /// </summary> public void ReleaseAndFailAll(Exception cause) { ReleaseAndCompleteAll(TaskUtil.FromException(cause)); }
public override Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress) { return(TaskUtil.FromException(new NotSupportedException())); }
public override void Initialize(IChannel channel) { base.Initialize(channel); _err = TaskUtil.FromException(new NotSupportedException()); }
public Http2ConnectionHandlerTest() { _connection = new Mock <IHttp2Connection>(); _remoteFlow = new Mock <IHttp2RemoteFlowController>(); _localFlow = new Mock <IHttp2LocalFlowController>(); _remote = new Mock <IHttp2ConnectionEndpoint <IHttp2RemoteFlowController> >(); _remoteFlowController = new Mock <IHttp2RemoteFlowController>(); _local = new Mock <IHttp2ConnectionEndpoint <IHttp2LocalFlowController> >(); _localFlowController = new Mock <IHttp2LocalFlowController>(); _ctx = new Mock <IChannelHandlerContext>(); _executor = new Mock <IEventExecutor>(); _channel = new Mock <IChannel>(); _pipeline = new Mock <IChannelPipeline>(); _stream = new Mock <IHttp2Stream>(); _decoder = new Mock <IHttp2ConnectionDecoder>(); _encoder = new Mock <IHttp2ConnectionEncoder>(); _frameWriter = new Mock <IHttp2FrameWriter>(); _channel.Setup(x => x.Metadata).Returns(new ChannelMetadata(false)); var config = new DefaultChannelConfiguration(_channel.Object); _channel.Setup(x => x.Configuration).Returns(config); _promise = new TaskCompletionSource(); _voidPromise = new TaskCompletionSource(); var fakeException = new Http2RuntimeException("Fake exception"); _future = TaskUtil.FromException(fakeException); _encoder.Setup(x => x.Connection).Returns(_connection.Object); _decoder.Setup(x => x.Connection).Returns(_connection.Object); _encoder.Setup(x => x.FrameWriter).Returns(_frameWriter.Object); _encoder.Setup(x => x.FlowController).Returns(_remoteFlow.Object); _decoder.Setup(x => x.FlowController).Returns(_localFlow.Object); _frameWriter .Setup(x => x.WriteGoAwayAsync( It.IsAny <IChannelHandlerContext>(), It.IsAny <int>(), It.IsAny <Http2Error>(), It.IsAny <IByteBuffer>(), It.IsAny <IPromise>())) .Returns <IChannelHandlerContext, int, Http2Error, IByteBuffer, IPromise>((ctx, id, err, buf, p) => { _goAwayDebugCap = buf.ToString(Encoding.UTF8); buf.Release(); return(_future); }); _channel.Setup(x => x.IsActive).Returns(true); _channel.Setup(x => x.Pipeline).Returns(_pipeline.Object); _connection.Setup(x => x.Remote).Returns(_remote.Object); _remote.Setup(x => x.FlowController).Returns(_remoteFlowController.Object); _connection.Setup(x => x.Local).Returns(_local.Object); _local.Setup(x => x.FlowController).Returns(_localFlowController.Object); _connection .Setup(x => x.ForEachActiveStream(It.IsAny <IHttp2StreamVisitor>())) .Returns <IHttp2StreamVisitor>(visitor => { if (!visitor.Visit(_stream.Object)) { return(_stream.Object); } return(null); }); _connection .Setup(x => x.ForEachActiveStream(It.IsAny <Func <IHttp2Stream, bool> >())) .Returns <Func <IHttp2Stream, bool> >(visitor => { if (!visitor(_stream.Object)) { return(_stream.Object); } return(null); }); _connection.Setup(x => x.Stream(It.Is <int>(v => v == NON_EXISTANT_STREAM_ID))).Returns(default(IHttp2Stream)); _connection.Setup(x => x.NumActiveStreams).Returns(1); _connection.Setup(x => x.Stream(It.Is <int>(v => v == STREAM_ID))).Returns(_stream.Object); _connection .Setup(x => x.GoAwaySent( It.IsAny <int>(), It.IsAny <Http2Error>(), It.IsAny <IByteBuffer>())) .Returns(true); _stream.Setup(x => x.Open(It.IsAny <bool>())).Returns(_stream.Object); _encoder .Setup(x => x.WriteSettingsAsync( It.Is <IChannelHandlerContext>(v => v == _ctx.Object), It.IsAny <Http2Settings>(), It.Is <IPromise>(v => v == _promise))) .Returns(_future); _ctx.Setup(x => x.Allocator).Returns(UnpooledByteBufferAllocator.Default); _ctx.Setup(x => x.Channel).Returns(_channel.Object); _ctx.Setup(x => x.NewPromise()).Returns(_promise); _ctx.Setup(x => x.VoidPromise()).Returns(_voidPromise); _ctx.Setup(x => x.WriteAsync(It.IsAny <object>())).Returns(_future); _ctx.Setup(x => x.Executor).Returns(_executor.Object); _ctx .Setup(x => x.FireChannelRead(It.IsAny <object>())) .Returns <object>(msg => { ReferenceCountUtil.Release(msg); return(_ctx.Object); }); }