package io.netty.handler.stream;

import g.a.a.a.a;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelProgressivePromise;
import io.netty.channel.ChannelPromise;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayDeque;
import java.util.Queue;

/* JADX INFO: loaded from: classes.dex */
public class ChunkedWriteHandler extends ChannelDuplexHandler {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) ChunkedWriteHandler.class);
    private volatile ChannelHandlerContext ctx;
    private PendingWrite currentWrite;
    private final Queue<PendingWrite> queue = new ArrayDeque();

    public static final class PendingWrite {
        public final Object msg;
        public final ChannelPromise promise;

        public PendingWrite(Object obj, ChannelPromise channelPromise) {
            this.msg = obj;
            this.promise = channelPromise;
        }

        public void fail(Throwable th) {
            ReferenceCountUtil.release(this.msg);
            this.promise.tryFailure(th);
        }

        public void progress(long j2, long j3) {
            ChannelPromise channelPromise = this.promise;
            if (channelPromise instanceof ChannelProgressivePromise) {
                ((ChannelProgressivePromise) channelPromise).tryProgress(j2, j3);
            }
        }

        public void success(long j2) {
            if (this.promise.isDone()) {
                return;
            }
            progress(j2, j2);
            this.promise.trySuccess();
        }
    }

    public ChunkedWriteHandler() {
    }

    @Deprecated
    public ChunkedWriteHandler(int i2) {
        if (i2 <= 0) {
            throw new IllegalArgumentException(a.n("maxPendingWrites: ", i2, " (expected: > 0)"));
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void closeInput(ChunkedInput<?> chunkedInput) {
        try {
            chunkedInput.close();
        } catch (Throwable th) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to close a chunked input.", th);
            }
        }
    }

    private void discard(Throwable th) {
        while (true) {
            PendingWrite pendingWritePoll = this.currentWrite;
            if (pendingWritePoll == null) {
                pendingWritePoll = this.queue.poll();
            } else {
                this.currentWrite = null;
            }
            if (pendingWritePoll == null) {
                return;
            }
            Object obj = pendingWritePoll.msg;
            if (obj instanceof ChunkedInput) {
                ChunkedInput chunkedInput = (ChunkedInput) obj;
                try {
                    if (chunkedInput.isEndOfInput()) {
                        pendingWritePoll.success(chunkedInput.length());
                    } else {
                        if (th == null) {
                            th = new ClosedChannelException();
                        }
                        pendingWritePoll.fail(th);
                    }
                    closeInput(chunkedInput);
                } catch (Exception e2) {
                    pendingWritePoll.fail(e2);
                    logger.warn(ChunkedInput.class.getSimpleName() + ".isEndOfInput() failed", (Throwable) e2);
                    closeInput(chunkedInput);
                }
            } else {
                if (th == null) {
                    th = new ClosedChannelException();
                }
                pendingWritePoll.fail(th);
            }
        }
    }

    private void doFlush(ChannelHandlerContext channelHandlerContext) {
        Object chunk;
        ChannelFutureListener channelFutureListener;
        final Channel channel = channelHandlerContext.channel();
        if (!channel.isActive()) {
            discard(null);
            return;
        }
        ByteBufAllocator byteBufAllocatorAlloc = channelHandlerContext.alloc();
        boolean z2 = true;
        while (true) {
            if (!channel.isWritable()) {
                break;
            }
            if (this.currentWrite == null) {
                this.currentWrite = this.queue.poll();
            }
            final PendingWrite pendingWrite = this.currentWrite;
            if (pendingWrite == null) {
                break;
            }
            final Object obj = pendingWrite.msg;
            if (obj instanceof ChunkedInput) {
                final ChunkedInput chunkedInput = (ChunkedInput) obj;
                try {
                    chunk = chunkedInput.readChunk(byteBufAllocatorAlloc);
                    try {
                        boolean zIsEndOfInput = chunkedInput.isEndOfInput();
                        if (chunk == null ? !zIsEndOfInput : false) {
                            break;
                        }
                        if (chunk == null) {
                            chunk = Unpooled.EMPTY_BUFFER;
                        }
                        ChannelFuture channelFutureWrite = channelHandlerContext.write(chunk);
                        if (zIsEndOfInput) {
                            this.currentWrite = null;
                            channelFutureListener = new ChannelFutureListener() { // from class: io.netty.handler.stream.ChunkedWriteHandler.2
                                @Override // io.netty.util.concurrent.GenericFutureListener
                                public void operationComplete(ChannelFuture channelFuture) {
                                    pendingWrite.progress(chunkedInput.progress(), chunkedInput.length());
                                    pendingWrite.success(chunkedInput.length());
                                    ChunkedWriteHandler.closeInput(chunkedInput);
                                }
                            };
                        } else if (channel.isWritable()) {
                            channelFutureListener = new ChannelFutureListener() { // from class: io.netty.handler.stream.ChunkedWriteHandler.3
                                @Override // io.netty.util.concurrent.GenericFutureListener
                                public void operationComplete(ChannelFuture channelFuture) {
                                    if (channelFuture.isSuccess()) {
                                        pendingWrite.progress(chunkedInput.progress(), chunkedInput.length());
                                    } else {
                                        ChunkedWriteHandler.closeInput((ChunkedInput) obj);
                                        pendingWrite.fail(channelFuture.cause());
                                    }
                                }
                            };
                        } else {
                            channelFutureWrite.addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelFutureListener() { // from class: io.netty.handler.stream.ChunkedWriteHandler.4
                                @Override // io.netty.util.concurrent.GenericFutureListener
                                public void operationComplete(ChannelFuture channelFuture) {
                                    if (!channelFuture.isSuccess()) {
                                        ChunkedWriteHandler.closeInput((ChunkedInput) obj);
                                        pendingWrite.fail(channelFuture.cause());
                                    } else {
                                        pendingWrite.progress(chunkedInput.progress(), chunkedInput.length());
                                        if (channel.isWritable()) {
                                            ChunkedWriteHandler.this.resumeTransfer();
                                        }
                                    }
                                }
                            });
                            channelHandlerContext.flush();
                            z2 = false;
                        }
                        channelFutureWrite.addListener((GenericFutureListener<? extends Future<? super Void>>) channelFutureListener);
                        channelHandlerContext.flush();
                        z2 = false;
                    } catch (Throwable th) {
                        th = th;
                        this.currentWrite = null;
                        if (chunk != null) {
                            ReferenceCountUtil.release(chunk);
                        }
                        pendingWrite.fail(th);
                        closeInput(chunkedInput);
                    }
                } catch (Throwable th2) {
                    th = th2;
                    chunk = null;
                }
            } else {
                this.currentWrite = null;
                channelHandlerContext.write(obj, pendingWrite.promise);
                z2 = true;
            }
            if (!channel.isActive()) {
                discard(new ClosedChannelException());
                break;
            }
        }
        if (z2) {
            channelHandlerContext.flush();
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void resumeTransfer0(ChannelHandlerContext channelHandlerContext) {
        try {
            doFlush(channelHandlerContext);
        } catch (Exception e2) {
            if (logger.isWarnEnabled()) {
                logger.warn("Unexpected exception while sending chunks.", (Throwable) e2);
            }
        }
    }

    @Override // io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelInboundHandler
    public void channelInactive(ChannelHandlerContext channelHandlerContext) {
        doFlush(channelHandlerContext);
        channelHandlerContext.fireChannelInactive();
    }

    @Override // io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelInboundHandler
    public void channelWritabilityChanged(ChannelHandlerContext channelHandlerContext) {
        if (channelHandlerContext.channel().isWritable()) {
            doFlush(channelHandlerContext);
        }
        channelHandlerContext.fireChannelWritabilityChanged();
    }

    @Override // io.netty.channel.ChannelDuplexHandler, io.netty.channel.ChannelOutboundHandler
    public void flush(ChannelHandlerContext channelHandlerContext) {
        doFlush(channelHandlerContext);
    }

    @Override // io.netty.channel.ChannelHandlerAdapter, io.netty.channel.ChannelHandler
    public void handlerAdded(ChannelHandlerContext channelHandlerContext) {
        this.ctx = channelHandlerContext;
    }

    public void resumeTransfer() {
        final ChannelHandlerContext channelHandlerContext = this.ctx;
        if (channelHandlerContext == null) {
            return;
        }
        if (channelHandlerContext.executor().inEventLoop()) {
            resumeTransfer0(channelHandlerContext);
        } else {
            channelHandlerContext.executor().execute(new Runnable() { // from class: io.netty.handler.stream.ChunkedWriteHandler.1
                @Override // java.lang.Runnable
                public void run() {
                    ChunkedWriteHandler.this.resumeTransfer0(channelHandlerContext);
                }
            });
        }
    }

    @Override // io.netty.channel.ChannelDuplexHandler, io.netty.channel.ChannelOutboundHandler
    public void write(ChannelHandlerContext channelHandlerContext, Object obj, ChannelPromise channelPromise) {
        this.queue.add(new PendingWrite(obj, channelPromise));
    }
}
