package org.glassfish.grizzly.http2;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.CloseListener;
import org.glassfish.grizzly.CloseReason;
import org.glassfish.grizzly.CloseType;
import org.glassfish.grizzly.Closeable;
import org.glassfish.grizzly.CompletionHandler;
import org.glassfish.grizzly.Grizzly;
import org.glassfish.grizzly.GrizzlyFuture;
import org.glassfish.grizzly.ICloseType;
import org.glassfish.grizzly.OutputSink;
import org.glassfish.grizzly.WriteHandler;
import org.glassfish.grizzly.attributes.Attribute;
import org.glassfish.grizzly.attributes.AttributeBuilder;
import org.glassfish.grizzly.attributes.AttributeHolder;
import org.glassfish.grizzly.attributes.AttributeStorage;
import org.glassfish.grizzly.http.HttpContent;
import org.glassfish.grizzly.http.HttpHeader;
import org.glassfish.grizzly.http.HttpRequestPacket;
import org.glassfish.grizzly.http.HttpResponsePacket;
import org.glassfish.grizzly.http2.Termination.TerminationType;
import org.glassfish.grizzly.impl.FutureImpl;
import org.glassfish.grizzly.memory.Buffers;
import org.glassfish.grizzly.memory.CompositeBuffer;
import org.glassfish.grizzly.memory.CompositeBuffer.DisposeOrder;
import org.glassfish.grizzly.utils.Futures;
import org.glassfish.grizzly.http2.frames.ErrorCode;
import static org.glassfish.grizzly.http2.Termination.CLOSED_BY_PEER_STRING;
import static org.glassfish.grizzly.http2.Termination.LOCAL_CLOSE_TERMINATION;
import static org.glassfish.grizzly.http2.Termination.PEER_CLOSE_TERMINATION;
import static org.glassfish.grizzly.http2.Termination.RESET_TERMINATION;
import static org.glassfish.grizzly.http2.Termination.UNEXPECTED_FRAME_TERMINATION;
public class Http2Stream implements AttributeStorage, OutputSink, Closeable {
public enum State {
IDLE,
OPEN,
RESERVED_LOCAL,
RESERVED_REMOTE,
HALF_CLOSED_LOCAL,
HALF_CLOSED_REMOTE,
CLOSED
}
private static final Logger LOGGER = Grizzly.logger(Http2Stream.class);
public static final String HTTP2_STREAM_ATTRIBUTE =
HttpRequestPacket.READ_ONLY_ATTR_PREFIX + Http2Stream.class.getName();
public static final String HTTP2_PARENT_STREAM_ATTRIBUTE =
HttpRequestPacket.READ_ONLY_ATTR_PREFIX + "parent." + Http2Stream.class.getName();
static final int UPGRADE_STREAM_ID = 1;
private static final Attribute<Http2Stream> HTTP_RQST_HTTP2_STREAM_ATTR =
AttributeBuilder.DEFAULT_ATTRIBUTE_BUILDER.createAttribute("http2.request.stream");
State state = State.IDLE;
private final HttpRequestPacket request;
private final int streamId;
private final int parentStreamId;
private final int priority;
private final boolean exclusive;
private final Http2Session http2Session;
private final AttributeHolder attributes =
AttributeBuilder.DEFAULT_ATTRIBUTE_BUILDER.createSafeAttributeHolder();
final StreamInputBuffer inputBuffer;
final StreamOutputSink outputSink;
static final AtomicIntegerFieldUpdater<Http2Stream> unackedReadBytesUpdater =
AtomicIntegerFieldUpdater.newUpdater(Http2Stream.class, "unackedReadBytes");
@SuppressWarnings("unused")
private volatile int unackedReadBytes;
private static final AtomicReferenceFieldUpdater<Http2Stream, CloseReason> closeReasonUpdater =
AtomicReferenceFieldUpdater.newUpdater(Http2Stream.class, CloseReason.class, "closeReason");
@SuppressWarnings("unused")
private volatile CloseReason closeReason;
private volatile GrizzlyFuture<CloseReason> closeFuture;
private final Queue<CloseListener> closeListeners =
new ConcurrentLinkedQueue<>();
private static final AtomicIntegerFieldUpdater<Http2Stream> completeFinalizationCounterUpdater =
AtomicIntegerFieldUpdater.newUpdater(Http2Stream.class, "completeFinalizationCounter");
@SuppressWarnings("unused")
private volatile int completeFinalizationCounter;
volatile boolean isProcessingComplete;
private int ;
public static Http2Stream (final HttpHeader httpHeader) {
final HttpRequestPacket request;
if (httpHeader.isRequest()) {
assert httpHeader instanceof HttpRequestPacket;
request = (HttpRequestPacket) httpHeader;
} else {
assert httpHeader instanceof HttpResponsePacket;
request = ((HttpResponsePacket) httpHeader).getRequest();
}
if (request != null) {
return HTTP_RQST_HTTP2_STREAM_ATTR.get(request);
}
return null;
}
protected Http2Stream(final Http2Session http2Session,
final HttpRequestPacket request,
final int streamId, final int parentStreamId,
final boolean exclusive, final int priority) {
this.http2Session = http2Session;
this.request = request;
this.streamId = streamId;
this.parentStreamId = parentStreamId;
this.exclusive = exclusive;
this.priority = priority;
this.state = State.IDLE;
inputBuffer = new DefaultInputBuffer(this);
outputSink = new DefaultOutputSink(this);
HTTP_RQST_HTTP2_STREAM_ATTR.set(request, this);
}
protected Http2Stream(final Http2Session http2Session,
final HttpRequestPacket request,
final int priority) {
this.http2Session = http2Session;
this.request = request;
this.streamId = UPGRADE_STREAM_ID;
this.parentStreamId = 0;
this.priority = priority;
this.exclusive = false;
inputBuffer = http2Session.isServer()
? new UpgradeInputBuffer(this)
: new DefaultInputBuffer(this);
outputSink = http2Session.isServer()
? new DefaultOutputSink(this)
: new UpgradeOutputSink(http2Session);
HTTP_RQST_HTTP2_STREAM_ATTR.set(request, this);
}
Http2Session getHttp2Session() {
return http2Session;
}
public int getPeerWindowSize() {
return http2Session.getPeerStreamWindowSize();
}
public int getLocalWindowSize() {
return http2Session.getLocalStreamWindowSize();
}
public int getUnflushedWritesCount() {
return outputSink.getUnflushedWritesCount() ;
}
public HttpRequestPacket getRequest() {
return request;
}
public HttpResponsePacket getResponse() {
return request.getResponse();
}
@SuppressWarnings("unused")
public boolean isPushEnabled() {
return http2Session.isPushEnabled();
}
public int getId() {
return streamId;
}
@SuppressWarnings("unused")
public int getParentStreamId() {
return parentStreamId;
}
@SuppressWarnings("unused")
public int getPriority() {
return priority;
}
public boolean isPushStream() {
return (streamId & 1) == 0;
}
public boolean isLocallyInitiatedStream() {
return http2Session.isLocallyInitiatedStream(streamId);
}
@Override
public boolean isOpen() {
return completeFinalizationCounter < 2;
}
@Override
public void assertOpen() throws IOException {
if (!isOpen()) {
final CloseReason cr = this.closeReason;
assert cr != null;
throw new IOException("closed", cr.getCause());
}
}
@Override
public AttributeHolder getAttributes() {
return attributes;
}
@Override
@Deprecated
public boolean canWrite(int length) {
return canWrite();
}
@Override
public boolean canWrite() {
return outputSink.canWrite();
}
@Override
@Deprecated
public void notifyCanWrite(final WriteHandler handler, final int length) {
notifyCanWrite(handler);
}
@Override
public void notifyCanWrite(final WriteHandler writeHandler) {
outputSink.notifyWritePossible(writeHandler);
}
StreamOutputSink getOutputSink() {
return outputSink;
}
@Override
public GrizzlyFuture<Closeable> terminate() {
final FutureImpl<Closeable> future = Futures.createSafeFuture();
close0(Futures.toCompletionHandler(future), CloseType.LOCALLY, null, false);
return future;
}
@Override
public void terminateSilently() {
close0(null, CloseType.LOCALLY, null, false);
}
@Override
public void terminateWithReason(final IOException cause) {
close0(null, CloseType.LOCALLY, cause, false);
}
@Override
public GrizzlyFuture<Closeable> close() {
final FutureImpl<Closeable> future = Futures.createSafeFuture();
close0(Futures.toCompletionHandler(future), CloseType.LOCALLY, null, true);
return future;
}
@Override
public void closeSilently() {
close0(null, CloseType.LOCALLY, null, true);
}
@Override
public void close(final CompletionHandler<Closeable> completionHandler) {
close0(completionHandler, CloseType.LOCALLY, null, true);
}
@Override
public void closeWithReason(final IOException cause) {
close0(null, CloseType.LOCALLY, cause, false);
}
void close0(
final CompletionHandler<Closeable> completionHandler,
final CloseType closeType,
final IOException cause,
final boolean isCloseOutputGracefully) {
if (closeReason != null) {
return;
}
if (closeReasonUpdater.compareAndSet(this, null,
new CloseReason(closeType, cause))) {
final Termination termination = closeType == CloseType.LOCALLY ?
LOCAL_CLOSE_TERMINATION :
PEER_CLOSE_TERMINATION;
inputBuffer.terminate(termination);
if (isCloseOutputGracefully) {
outputSink.close();
} else {
outputSink.terminate(termination);
}
notifyCloseListeners();
if (completionHandler != null) {
completionHandler.completed(this);
}
}
}
void closedRemotely() {
inputBuffer.terminate(
new Termination(TerminationType.PEER_CLOSE, CLOSED_BY_PEER_STRING, true) {
@Override
public void doTask() {
close0(null, CloseType.REMOTELY, null, false);
}
});
}
void resetRemotely() {
if (closeReasonUpdater.compareAndSet(this, null,
new CloseReason(CloseType.REMOTELY, null))) {
onReset();
inputBuffer.terminate(RESET_TERMINATION);
outputSink.terminate(RESET_TERMINATION);
}
}
void onProcessingComplete() {
isProcessingComplete = true;
close();
}
@Override
@SuppressWarnings("unchecked")
public void addCloseListener(final CloseListener closeListener) {
CloseReason cr = closeReason;
if (cr == null) {
closeListeners.add(closeListener);
cr = closeReason;
if (cr != null && closeListeners.remove(closeListener)) {
try {
closeListener.onClosed(this, cr.getType());
} catch (IOException ignored) {
}
}
} else {
try {
closeListener.onClosed(this, cr.getType());
} catch (IOException ignored) {
}
}
}
@Override
public boolean removeCloseListener(final CloseListener closeListener) {
return closeListeners.remove(closeListener);
}
@SuppressWarnings("Duplicates")
@Override
public GrizzlyFuture<CloseReason> closeFuture() {
if (closeFuture == null) {
synchronized (this) {
if (closeFuture == null) {
final CloseReason cr = closeReason;
if (cr == null) {
final FutureImpl<CloseReason> f
= Futures.createSafeFuture();
addCloseListener(new org.glassfish.grizzly.CloseListener() {
@Override
public void onClosed(Closeable closeable, @SuppressWarnings("deprecation") ICloseType type)
throws IOException {
final CloseReason cr = closeReason;
assert cr != null;
f.result(cr);
}
});
closeFuture = f;
} else {
closeFuture = Futures.createReadyFuture(cr);
}
}
}
}
return closeFuture;
}
void onInputClosed() {
if (completeFinalizationCounterUpdater.incrementAndGet(this) == 2) {
closeStream();
}
}
void onOutputClosed() {
if (completeFinalizationCounterUpdater.incrementAndGet(this) == 2) {
closeStream();
}
}
int () {
return inboundHeaderFramesCounter;
}
void (final boolean isEOS) throws Http2StreamException {
inboundHeaderFramesCounter++;
switch (inboundHeaderFramesCounter) {
case 1:
onReceiveHeaders();
if (isEOS) {
onReceiveEndOfStream();
}
break;
case 2: {
if (isEOS) {
break;
}
}
default: {
inputBuffer.close(UNEXPECTED_FRAME_TERMINATION);
throw new Http2StreamException(getId(),
ErrorCode.PROTOCOL_ERROR, "Unexpected headers frame");
}
}
}
void (final boolean isEOS) {
onSendHeaders();
if (isEOS) {
onSendEndOfStream();
}
}
private Buffer cachedInputBuffer;
private boolean cachedIsLast;
IOException assertCanAcceptData(final boolean fin) {
if (isPushStream() && isLocallyInitiatedStream()) {
return new Http2StreamException(getId(),
ErrorCode.PROTOCOL_ERROR,
"Data frame received on a push-stream");
}
final Http2Stream.State state = getState();
if (state == State.HALF_CLOSED_REMOTE || getState() == State.CLOSED) {
close0(null, CloseType.LOCALLY,
new IOException("Received DATA frame on " + state + " stream."), false);
return ((fin)
? new Http2SessionException(ErrorCode.STREAM_CLOSED)
: new Http2StreamException(getId(),
ErrorCode.STREAM_CLOSED,
"Received DATA frame on " + state + " stream."));
}
if (inboundHeaderFramesCounter != 1) {
close0(null, CloseType.LOCALLY,
new IOException("DATA frame came before HEADERS frame."), false);
return new Http2StreamException(getId(),
ErrorCode.PROTOCOL_ERROR, "DATA frame came before HEADERS frame.");
}
return null;
}
IOException (final boolean fin) {
final Http2Stream.State state = getState();
if (state == State.HALF_CLOSED_REMOTE || getState() == State.CLOSED) {
close0(null, CloseType.LOCALLY,
new IOException("Received HEADER frame on " + state + " stream."), false);
return ((fin)
? new Http2SessionException(ErrorCode.STREAM_CLOSED)
: new Http2StreamException(getId(),
ErrorCode.STREAM_CLOSED,
"Received HEADER frame on " + state + " stream."));
}
return null;
}
void offerInputData(final Buffer data, final boolean isLast) {
final boolean isFirstBufferCached = (cachedInputBuffer == null);
cachedIsLast |= isLast;
cachedInputBuffer = Buffers.appendBuffers(
http2Session.getMemoryManager(),
cachedInputBuffer, data);
if (isFirstBufferCached) {
http2Session.streamsToFlushInput.add(this);
}
}
void flushInputData() {
final Buffer cachedInputBufferLocal = cachedInputBuffer;
final boolean cachedIsLastLocal = cachedIsLast;
cachedInputBuffer = null;
cachedIsLast = false;
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "{0} streamId={1}: flushInputData cachedInputBufferLocal={2}",
new Object[]{Thread.currentThread().getName(), getId(),
cachedInputBufferLocal != null
? cachedInputBufferLocal.toString()
: null});
}
if (cachedInputBufferLocal != null) {
if (cachedInputBufferLocal.isComposite()) {
((CompositeBuffer) cachedInputBufferLocal).allowInternalBuffersDispose(true);
cachedInputBufferLocal.allowBufferDispose(true);
((CompositeBuffer) cachedInputBufferLocal).disposeOrder(DisposeOrder.LAST_TO_FIRST);
}
final int size = cachedInputBufferLocal.remaining();
if (!inputBuffer.offer(cachedInputBufferLocal, cachedIsLastLocal)) {
http2Session.ackConsumedData(size);
}
}
}
HttpContent pollInputData() throws IOException {
return inputBuffer.poll();
}
private void closeStream() {
http2Session.deregisterStream();
}
HttpHeader () {
return (isLocallyInitiatedStream() ^ isPushStream()) ?
request.getResponse() :
request;
}
HttpHeader () {
return (!isLocallyInitiatedStream() ^ isPushStream()) ?
request.getResponse() :
request;
}
@SuppressWarnings("unchecked")
private void notifyCloseListeners() {
final CloseReason cr = closeReason;
CloseListener closeListener;
while ((closeListener = closeListeners.poll()) != null) {
try {
closeListener.onClosed(this, cr.getType());
} catch (IOException ignored) {
}
}
}
State getState() {
synchronized (this) {
return state;
}
}
boolean isClosed() {
synchronized (this) {
return (state == State.CLOSED);
}
}
boolean isIdle() {
synchronized (this) {
return (state == State.IDLE);
}
}
boolean canSendFrames() {
synchronized (this) {
return (state != State.CLOSED && state != State.HALF_CLOSED_LOCAL);
}
}
boolean canReceiveFrames() {
synchronized (this) {
return (state != State.CLOSED && state != State.HALF_CLOSED_REMOTE);
}
}
void onSendPushPromise() {
synchronized (this) {
if (state == State.IDLE) {
state = State.RESERVED_LOCAL;
}
}
}
void onReceivePushPromise() {
synchronized (this) {
if (state == State.IDLE) {
state = State.RESERVED_REMOTE;
}
}
}
private void () {
synchronized (this) {
switch (state) {
case IDLE:
state = State.OPEN;
break;
case RESERVED_LOCAL:
state = State.HALF_CLOSED_REMOTE;
break;
}
}
}
private void () {
synchronized (this) {
switch (state) {
case IDLE:
state = State.OPEN;
break;
case RESERVED_REMOTE:
state = State.HALF_CLOSED_LOCAL;
break;
}
}
}
private void onSendEndOfStream() {
synchronized (this) {
switch (state) {
case OPEN:
state = State.HALF_CLOSED_LOCAL;
break;
case HALF_CLOSED_REMOTE:
state = State.CLOSED;
break;
}
}
}
private void onReceiveEndOfStream() {
synchronized (this) {
switch (state) {
case OPEN:
state = State.HALF_CLOSED_REMOTE;
break;
case HALF_CLOSED_LOCAL:
state = State.CLOSED;
break;
}
}
}
private void onReset() {
synchronized (this) {
switch (state) {
case OPEN:
case RESERVED_LOCAL:
case RESERVED_REMOTE:
case HALF_CLOSED_LOCAL:
case HALF_CLOSED_REMOTE:
state = State.CLOSED;
break;
}
}
}
}