Example usage for io.netty.handler.codec.http2 Http2Error CANCEL

List of usage examples for io.netty.handler.codec.http2 Http2Error CANCEL

Introduction

In this page you can find the example usage for io.netty.handler.codec.http2 Http2Error CANCEL.

Prototype

Http2Error CANCEL

To view the source code for io.netty.handler.codec.http2 Http2Error CANCEL.

Click Source Link

Usage

From source file:com.linecorp.armeria.client.http.HttpRequestSubscriber.java

License:Apache License

private void failAndRespond(Throwable cause) {
    fail(cause);//from w w  w . j  a  v a2  s .c o m

    final Channel ch = ctx.channel();
    final Http2Error error;
    if (response.isOpen()) {
        response.close(cause);
        error = Http2Error.INTERNAL_ERROR;
    } else if (cause instanceof WriteTimeoutException) {
        error = Http2Error.CANCEL;
    } else {
        Exceptions.logIfUnexpected(logger, ch, HttpSession.get(ch).protocol(),
                "a request publisher raised an exception", cause);
        error = Http2Error.INTERNAL_ERROR;
    }

    if (ch.isActive()) {
        encoder.writeReset(ctx, id, streamId(), error);
        ctx.flush();
    }
}

From source file:com.linecorp.armeria.client.Http2ResponseDecoder.java

License:Apache License

@Override
HttpResponseWrapper addResponse(int id, @Nullable HttpRequest req, DecodedHttpResponse res,
        RequestLogBuilder logBuilder, long responseTimeoutMillis, long maxContentLength) {

    final HttpResponseWrapper resWrapper = super.addResponse(id, req, res, logBuilder, responseTimeoutMillis,
            maxContentLength);/* www.  j av a  2 s  .c  o m*/

    resWrapper.completionFuture().whenCompleteAsync((unused, cause) -> {
        if (cause != null) {
            // Ensure that the resWrapper is closed.
            // This is needed in case the response is aborted by the client.
            resWrapper.close(cause);

            // We are not closing the connection but just send a RST_STREAM,
            // so we have to remove the response manually.
            removeResponse(id);

            // Reset the stream.
            final int streamId = idToStreamId(id);
            if (conn.streamMayHaveExisted(streamId)) {
                final ChannelHandlerContext ctx = channel().pipeline().lastContext();
                encoder.writeRstStream(ctx, streamId, Http2Error.CANCEL.code(), ctx.newPromise());
                ctx.flush();
            }
        } else {
            // Ensure that the resWrapper is closed.
            // This is needed in case the response is aborted by the client.
            resWrapper.close();
        }
    }, channel().eventLoop());
    return resWrapper;
}

From source file:com.linecorp.armeria.client.HttpRequestSubscriber.java

License:Apache License

private void failAndRespond(Throwable cause) {
    fail(cause);/*from ww  w.  jav a 2s. c o  m*/

    final Channel ch = ctx.channel();
    final Http2Error error;
    if (response.isOpen()) {
        response.close(cause);
        error = Http2Error.INTERNAL_ERROR;
    } else if (cause instanceof WriteTimeoutException || cause instanceof AbortedStreamException) {
        error = Http2Error.CANCEL;
    } else {
        Exceptions.logIfUnexpected(logger, ch, HttpSession.get(ch).protocol(),
                "a request publisher raised an exception", cause);
        error = Http2Error.INTERNAL_ERROR;
    }

    if (ch.isActive()) {
        encoder.writeReset(ctx, id, streamId(), error);
        ctx.flush();
    }
}

From source file:com.linecorp.armeria.server.http.HttpResponseSubscriber.java

License:Apache License

@Override
public void onError(Throwable cause) {
    if (cause instanceof ServiceUnavailableException) {
        failAndRespond(cause, HttpStatus.SERVICE_UNAVAILABLE, Http2Error.CANCEL);
    } else if (cause instanceof ResourceNotFoundException) {
        failAndRespond(cause, HttpStatus.NOT_FOUND, Http2Error.CANCEL);
    } else {//  www.java2  s  .c  o m
        logger.warn("{} Unexpected exception from a service or a response publisher: {}", ctx.channel(),
                service, cause);

        failAndRespond(cause, HttpStatus.INTERNAL_SERVER_ERROR, Http2Error.INTERNAL_ERROR);
    }
}

From source file:com.linecorp.armeria.server.HttpResponseSubscriber.java

License:Apache License

@Override
public void onError(Throwable cause) {
    if (cause instanceof HttpResponseException) {
        // Timeout may occur when the aggregation of the error response takes long.
        // If timeout occurs, respond with 503 Service Unavailable.
        ((HttpResponseException) cause).httpResponse().aggregate(ctx.executor())
                .whenCompleteAsync((message, throwable) -> {
                    if (throwable != null) {
                        failAndRespond(throwable, INTERNAL_SERVER_ERROR_MESSAGE, Http2Error.CANCEL);
                    } else {
                        failAndRespond(cause, message, Http2Error.CANCEL);
                    }//from  w ww . ja v  a  2  s  . co  m
                }, ctx.executor());
    } else if (cause instanceof HttpStatusException) {
        failAndRespond(cause, AggregatedHttpMessage.of(((HttpStatusException) cause).httpStatus()),
                Http2Error.CANCEL);
    } else if (cause instanceof AbortedStreamException) {
        // One of the two cases:
        // - Client closed the connection too early.
        // - Response publisher aborted the stream.
        failAndReset((AbortedStreamException) cause);
    } else {
        logger.warn("{} Unexpected exception from a service or a response publisher: {}", ctx.channel(),
                service(), cause);

        failAndRespond(cause, INTERNAL_SERVER_ERROR_MESSAGE, Http2Error.INTERNAL_ERROR);
    }
}

From source file:com.linecorp.armeria.server.HttpResponseSubscriber.java

License:Apache License

private void failAndReset(AbortedStreamException cause) {
    final State oldState = setDone();
    subscription.cancel();// www. ja  v  a  2s  . co m

    final ChannelFuture future = responseEncoder.writeReset(ctx, req.id(), req.streamId(), Http2Error.CANCEL);

    addCallbackAndFlush(cause, oldState, future);
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

/**
 * Cancels this stream./*from ww w . j  av a 2s .  co  m*/
 */
private void cancelStream(ChannelHandlerContext ctx, CancelClientStreamCommand cmd, ChannelPromise promise) {
    NettyClientStream.TransportState stream = cmd.stream();
    PerfMark.startTask("NettyClientHandler.cancelStream", stream.tag());
    PerfMark.linkIn(cmd.getLink());
    try {
        Status reason = cmd.reason();
        if (reason != null) {
            stream.transportReportStatus(reason, true, new Metadata());
        }
        if (!cmd.stream().isNonExistent()) {
            encoder().writeRstStream(ctx, stream.id(), Http2Error.CANCEL.code(), promise);
        } else {
            promise.setSuccess();
        }
    } finally {
        PerfMark.stopTask("NettyClientHandler.cancelStream", stream.tag());
    }
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

private void forcefulClose(final ChannelHandlerContext ctx, final ForcefulCloseCommand msg,
        ChannelPromise promise) throws Exception {
    // close() already called by NettyClientTransport, so just need to clean up streams
    connection().forEachActiveStream(new Http2StreamVisitor() {
        @Override//from w ww.j a va2s.c o  m
        public boolean visit(Http2Stream stream) throws Http2Exception {
            NettyClientStream.TransportState clientStream = clientStream(stream);
            Tag tag = clientStream != null ? clientStream.tag() : PerfMark.createTag();
            PerfMark.startTask("NettyClientHandler.forcefulClose", tag);
            PerfMark.linkIn(msg.getLink());
            try {
                if (clientStream != null) {
                    clientStream.transportReportStatus(msg.getStatus(), true, new Metadata());
                    resetStream(ctx, stream.id(), Http2Error.CANCEL.code(), ctx.newPromise());
                }
                stream.close();
                return true;
            } finally {
                PerfMark.stopTask("NettyClientHandler.forcefulClose", tag);
            }
        }
    });
    promise.setSuccess();
}

From source file:io.grpc.netty.NettyClientHandlerTest.java

License:Apache License

@Test
public void cancelShouldSucceed() throws Exception {
    createStream();//from ww  w.  jav a  2  s.com
    cancelStream(Status.CANCELLED);

    verifyWrite().writeRstStream(eq(ctx()), eq(3), eq(Http2Error.CANCEL.code()), any(ChannelPromise.class));
    verify(mockKeepAliveManager, times(1)).onTransportActive(); // onStreamActive
    verify(mockKeepAliveManager, times(1)).onTransportIdle(); // onStreamClosed
    verifyNoMoreInteractions(mockKeepAliveManager);
}

From source file:io.grpc.netty.NettyClientHandlerTest.java

License:Apache License

@Test
public void cancelDeadlineExceededShouldSucceed() throws Exception {
    createStream();/*from  w  w w.  ja va  2 s.  com*/
    cancelStream(Status.DEADLINE_EXCEEDED);

    verifyWrite().writeRstStream(eq(ctx()), eq(3), eq(Http2Error.CANCEL.code()), any(ChannelPromise.class));
}