package jdk.internal.net.http;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodySubscriber;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Executor;
import java.util.concurrent.Flow;
import jdk.internal.net.http.common.Demand;
import jdk.internal.net.http.common.Log;
import jdk.internal.net.http.common.FlowTube;
import jdk.internal.net.http.common.Logger;
import jdk.internal.net.http.common.SequentialScheduler;
import jdk.internal.net.http.common.MinimalFuture;
import jdk.internal.net.http.common.Utils;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static jdk.internal.net.http.common.Utils.wrapWithExtraDetail;
class Http1Exchange<T> extends ExchangeImpl<T> {
final Logger debug = Utils.getDebugLogger(this::dbgString, Utils.DEBUG);
final HttpRequestImpl request;
final Http1Request requestAction;
private volatile Http1Response<T> response;
final HttpConnection connection;
final HttpClientImpl client;
final Executor executor;
private final Http1AsyncReceiver asyncReceiver;
private volatile boolean upgraded;
private Throwable failed;
private final List<CompletableFuture<?>> operations;
private final Object lock = new Object();
final ConcurrentLinkedDeque<DataPair> outgoing = new ConcurrentLinkedDeque<>();
private final Http1Publisher writePublisher = new Http1Publisher();
private final CompletableFuture<ExchangeImpl<T>> = new MinimalFuture<>();
private final CompletableFuture<ExchangeImpl<T>> bodySentCF = new MinimalFuture<>();
private volatile Http1BodySubscriber bodySubscriber;
enum State { INITIAL,
HEADERS,
BODY,
ERROR,
COMPLETING,
COMPLETED }
private State state = State.INITIAL;
static class DataPair {
Throwable throwable;
List<ByteBuffer> data;
DataPair(List<ByteBuffer> data, Throwable throwable){
this.data = data;
this.throwable = throwable;
}
@Override
public String toString() {
return "DataPair [data=" + data + ", throwable=" + throwable + "]";
}
}
static abstract class Http1BodySubscriber implements Flow.Subscriber<ByteBuffer> {
final MinimalFuture<Flow.Subscription> whenSubscribed = new MinimalFuture<>();
private volatile Flow.Subscription subscription;
volatile boolean complete;
private final Logger debug;
Http1BodySubscriber(Logger debug) {
assert debug != null;
this.debug = debug;
}
static final List<ByteBuffer> COMPLETED = List.of(ByteBuffer.allocate(0));
final void request(long n) {
if (debug.on())
debug.log("Http1BodySubscriber requesting %d, from %s",
n, subscription);
subscription.request(n);
}
abstract String currentStateMessage();
final boolean isSubscribed() {
return subscription != null;
}
final void setSubscription(Flow.Subscription subscription) {
this.subscription = subscription;
whenSubscribed.complete(subscription);
}
final void cancelSubscription() {
try {
subscription.cancel();
} catch(Throwable t) {
String msg = "Ignoring exception raised when canceling BodyPublisher subscription";
if (debug.on()) debug.log("%s: %s", msg, t);
Log.logError("{0}: {1}", msg, (Object)t);
}
}
static Http1BodySubscriber completeSubscriber(Logger debug) {
return new Http1BodySubscriber(debug) {
@Override public void onSubscribe(Flow.Subscription subscription) { error(); }
@Override public void onNext(ByteBuffer item) { error(); }
@Override public void onError(Throwable throwable) { error(); }
@Override public void onComplete() { error(); }
@Override String currentStateMessage() { return null; }
private void error() {
throw new InternalError("should not reach here");
}
};
}
}
@Override
public String toString() {
return "HTTP/1.1 " + request.toString();
}
HttpRequestImpl request() {
return request;
}
Http1Exchange(Exchange<T> exchange, HttpConnection connection)
throws IOException
{
super(exchange);
this.request = exchange.request();
this.client = exchange.client();
this.executor = exchange.executor();
this.operations = new LinkedList<>();
operations.add(headersSentCF);
operations.add(bodySentCF);
if (connection != null) {
this.connection = connection;
} else {
InetSocketAddress addr = request.getAddress();
this.connection = HttpConnection.getConnection(addr, client, request, HTTP_1_1);
}
this.requestAction = new Http1Request(request, this);
this.asyncReceiver = new Http1AsyncReceiver(executor, this);
}
@Override
HttpConnection connection() {
return connection;
}
private void connectFlows(HttpConnection connection) {
FlowTube tube = connection.getConnectionFlow();
if (debug.on()) debug.log("%s connecting flows", tube);
tube.connectFlows(writePublisher,
asyncReceiver.subscriber());
}
@Override
CompletableFuture<ExchangeImpl<T>> () {
if (debug.on()) debug.log("Sending headers only");
asyncReceiver.setRetryOnError(true);
if (response == null) {
response = new Http1Response<>(connection, this, asyncReceiver);
}
if (debug.on()) debug.log("response created in advance");
CompletableFuture<Void> connectCF;
if (!connection.connected()) {
if (debug.on()) debug.log("initiating connect async");
connectCF = connection.connectAsync(exchange)
.thenCompose(unused -> connection.finishConnect());
Throwable cancelled;
synchronized (lock) {
if ((cancelled = failed) == null) {
operations.add(connectCF);
}
}
if (cancelled != null) {
if (client.isSelectorThread()) {
executor.execute(() ->
connectCF.completeExceptionally(cancelled));
} else {
connectCF.completeExceptionally(cancelled);
}
}
} else {
connectCF = new MinimalFuture<>();
connectCF.complete(null);
}
return connectCF
.thenCompose(unused -> {
CompletableFuture<Void> cf = new MinimalFuture<>();
try {
asyncReceiver.whenFinished.whenComplete((r,t) -> {
if (t != null) {
if (debug.on())
debug.log("asyncReceiver finished (failed=%s)", (Object)t);
if (!headersSentCF.isDone())
headersSentCF.completeAsync(() -> this, executor);
}
});
connectFlows(connection);
if (debug.on()) debug.log("requestAction.headers");
List<ByteBuffer> data = requestAction.headers();
synchronized (lock) {
state = State.HEADERS;
}
if (debug.on()) debug.log("setting outgoing with headers");
assert outgoing.isEmpty() : "Unexpected outgoing:" + outgoing;
appendToOutgoing(data);
cf.complete(null);
return cf;
} catch (Throwable t) {
if (debug.on()) debug.log("Failed to send headers: %s", t);
headersSentCF.completeExceptionally(t);
bodySentCF.completeExceptionally(t);
connection.close();
cf.completeExceptionally(t);
return cf;
} })
.thenCompose(unused -> headersSentCF);
}
private void cancelIfFailed(Flow.Subscription s) {
asyncReceiver.whenFinished.whenCompleteAsync((r,t) -> {
if (debug.on())
debug.log("asyncReceiver finished (failed=%s)", (Object)t);
if (t != null) {
s.cancel();
bodySentCF.complete(this);
}
}, executor);
}
@Override
CompletableFuture<ExchangeImpl<T>> sendBodyAsync() {
assert headersSentCF.isDone();
if (debug.on()) debug.log("sendBodyAsync");
try {
bodySubscriber = requestAction.continueRequest();
if (debug.on()) debug.log("bodySubscriber is %s",
bodySubscriber == null ? null : bodySubscriber.getClass());
if (bodySubscriber == null) {
bodySubscriber = Http1BodySubscriber.completeSubscriber(debug);
appendToOutgoing(Http1BodySubscriber.COMPLETED);
} else {
bodySubscriber.whenSubscribed
.thenAccept((s) -> cancelIfFailed(s))
.thenAccept((s) -> requestMoreBody());
}
} catch (Throwable t) {
cancelImpl(t);
bodySentCF.completeExceptionally(t);
}
return Utils.wrapForDebug(debug, "sendBodyAsync", bodySentCF);
}
@Override
CompletableFuture<Response> getResponseAsync(Executor executor) {
if (debug.on()) debug.log("reading headers");
CompletableFuture<Response> cf = response.readHeadersAsync(executor);
Throwable cause;
synchronized (lock) {
operations.add(cf);
cause = failed;
failed = null;
}
if (cause != null) {
Log.logTrace("Http1Exchange: request [{0}/timeout={1}ms]"
+ "\n\tCompleting exceptionally with {2}\n",
request.uri(),
request.timeout().isPresent() ?
(request.timeout().get().getSeconds() * 1000
+ request.timeout().get().getNano() / 1000000) : -1,
cause);
boolean acknowledged = cf.completeExceptionally(cause);
if (debug.on())
debug.log(acknowledged ? ("completed response with " + cause)
: ("response already completed, ignoring " + cause));
}
return Utils.wrapForDebug(debug, "getResponseAsync", cf);
}
@Override
CompletableFuture<T> readBodyAsync(BodyHandler<T> handler,
boolean returnConnectionToPool,
Executor executor)
{
BodySubscriber<T> bs = handler.apply(new ResponseInfoImpl(response.responseCode(),
response.responseHeaders(),
HTTP_1_1));
CompletableFuture<T> bodyCF = response.readBody(bs,
returnConnectionToPool,
executor);
return bodyCF;
}
@Override
CompletableFuture<Void> ignoreBody() {
return response.ignoreBody(executor);
}
@Override
public void nullBody(HttpResponse<T> resp, Throwable t) {
response.nullBody(resp, t);
}
ByteBuffer drainLeftOverBytes() {
synchronized (lock) {
asyncReceiver.stop();
return asyncReceiver.drain(Utils.EMPTY_BYTEBUFFER);
}
}
void released() {
Http1Response<T> resp = this.response;
if (resp != null) resp.completed();
asyncReceiver.clear();
}
void completed() {
Http1Response<T> resp = this.response;
if (resp != null) resp.completed();
}
@Override
void cancel() {
cancelImpl(new IOException("Request cancelled"));
}
@Override
void cancel(IOException cause) {
cancelImpl(cause);
}
private void cancelImpl(Throwable cause) {
LinkedList<CompletableFuture<?>> toComplete = null;
int count = 0;
Throwable error;
synchronized (lock) {
if ((error = failed) == null) {
failed = error = cause;
}
if (debug.on()) {
debug.log(request.uri() + ": " + error);
}
if (requestAction != null && requestAction.finished()
&& response != null && response.finished()) {
return;
}
writePublisher.writeScheduler.stop();
if (operations.isEmpty()) {
Log.logTrace("Http1Exchange: request [{0}/timeout={1}ms] no pending operation."
+ "\n\tCan''t cancel yet with {2}",
request.uri(),
request.timeout().isPresent() ?
(request.timeout().get().getSeconds() * 1000
+ request.timeout().get().getNano() / 1000000) : -1,
cause);
} else {
for (CompletableFuture<?> cf : operations) {
if (!cf.isDone()) {
if (toComplete == null) toComplete = new LinkedList<>();
toComplete.add(cf);
count++;
}
}
operations.clear();
}
}
try {
Log.logError("Http1Exchange.cancel: count=" + count);
if (toComplete != null) {
Executor exec = client.isSelectorThread()
? executor
: this::runInline;
Throwable x = error;
while (!toComplete.isEmpty()) {
CompletableFuture<?> cf = toComplete.poll();
exec.execute(() -> {
if (cf.completeExceptionally(x)) {
if (debug.on())
debug.log("%s: completed cf with %s", request.uri(), x);
}
});
}
}
} finally {
if (!upgraded)
connection.close();
}
}
void upgraded() {
upgraded = true;
}
private void runInline(Runnable run) {
assert !client.isSelectorThread();
run.run();
}
boolean isCanceled() {
synchronized (lock) {
return failed != null;
}
}
Throwable getCancelCause() {
synchronized (lock) {
return failed;
}
}
void appendToOutgoing(Throwable throwable) {
appendToOutgoing(new DataPair(null, throwable));
}
void appendToOutgoing(List<ByteBuffer> item) {
appendToOutgoing(new DataPair(item, null));
}
private void appendToOutgoing(DataPair dp) {
if (debug.on()) debug.log("appending to outgoing " + dp);
outgoing.add(dp);
writePublisher.writeScheduler.runOrSchedule();
}
private boolean hasOutgoing() {
return !outgoing.isEmpty();
}
private void requestMoreBody() {
try {
if (debug.on()) debug.log("requesting more request body from the subscriber");
bodySubscriber.request(1);
} catch (Throwable t) {
if (debug.on()) debug.log("Subscription::request failed", t);
cancelImpl(t);
bodySentCF.completeExceptionally(t);
}
}
private void cancelUpstreamSubscription() {
final Executor exec = client.theExecutor();
if (debug.on()) debug.log("cancelling upstream publisher");
if (bodySubscriber != null) {
exec.execute(bodySubscriber::cancelSubscription);
} else if (debug.on()) {
debug.log("bodySubscriber is null");
}
}
private DataPair getOutgoing() {
final Executor exec = client.theExecutor();
final DataPair dp = outgoing.pollFirst();
if (writePublisher.cancelled) {
cancelUpstreamSubscription();
headersSentCF.completeAsync(() -> this, exec);
bodySentCF.completeAsync(() -> this, exec);
return null;
}
if (dp == null)
return null;
if (dp.throwable != null) {
synchronized (lock) {
state = State.ERROR;
}
exec.execute(() -> {
headersSentCF.completeExceptionally(dp.throwable);
bodySentCF.completeExceptionally(dp.throwable);
connection.close();
});
return dp;
}
switch (state) {
case HEADERS:
synchronized (lock) {
state = State.BODY;
}
if (debug.on()) debug.log("initiating completion of headersSentCF");
headersSentCF.completeAsync(() -> this, exec);
break;
case BODY:
if (dp.data == Http1BodySubscriber.COMPLETED) {
synchronized (lock) {
state = State.COMPLETING;
}
if (debug.on()) debug.log("initiating completion of bodySentCF");
bodySentCF.completeAsync(() -> this, exec);
} else {
exec.execute(this::requestMoreBody);
}
break;
case INITIAL:
case ERROR:
case COMPLETING:
case COMPLETED:
default:
assert false : "Unexpected state:" + state;
}
return dp;
}
final class Http1Publisher implements FlowTube.TubePublisher {
final Logger debug = Utils.getDebugLogger(this::dbgString);
volatile Flow.Subscriber<? super List<ByteBuffer>> subscriber;
volatile boolean cancelled;
final Http1WriteSubscription subscription = new Http1WriteSubscription();
final Demand demand = new Demand();
final SequentialScheduler writeScheduler =
SequentialScheduler.synchronizedScheduler(new WriteTask());
@Override
public void subscribe(Flow.Subscriber<? super List<ByteBuffer>> s) {
assert state == State.INITIAL;
Objects.requireNonNull(s);
assert subscriber == null;
subscriber = s;
if (debug.on()) debug.log("got subscriber: %s", s);
s.onSubscribe(subscription);
}
volatile String dbgTag;
String dbgString() {
String tag = dbgTag;
Object flow = connection.getConnectionFlow();
if (tag == null && flow != null) {
dbgTag = tag = "Http1Publisher(" + flow + ")";
} else if (tag == null) {
tag = "Http1Publisher(?)";
}
return tag;
}
@SuppressWarnings("fallthrough")
private boolean checkRequestCancelled() {
if (exchange.multi.requestCancelled()) {
if (debug.on()) debug.log("request cancelled");
if (subscriber == null) {
if (debug.on()) debug.log("no subscriber yet");
return true;
}
switch (state) {
case BODY:
cancelUpstreamSubscription();
case HEADERS:
Throwable cause = getCancelCause();
if (cause == null) cause = new IOException("Request cancelled");
subscriber.onError(cause);
writeScheduler.stop();
return true;
}
}
return false;
}
final class WriteTask implements Runnable {
@Override
public void run() {
assert state != State.COMPLETED : "Unexpected state:" + state;
if (debug.on()) debug.log("WriteTask");
if (cancelled) {
if (debug.on()) debug.log("handling cancellation");
writeScheduler.stop();
getOutgoing();
return;
}
if (checkRequestCancelled()) return;
if (subscriber == null) {
if (debug.on()) debug.log("no subscriber yet");
return;
}
if (debug.on()) debug.log(() -> "hasOutgoing = " + hasOutgoing());
while (hasOutgoing() && demand.tryDecrement()) {
DataPair dp = getOutgoing();
if (dp == null)
break;
if (dp.throwable != null) {
if (debug.on()) debug.log("onError");
writeScheduler.stop();
} else {
List<ByteBuffer> data = dp.data;
if (data == Http1BodySubscriber.COMPLETED) {
synchronized (lock) {
assert state == State.COMPLETING : "Unexpected state:" + state;
state = State.COMPLETED;
}
if (debug.on())
debug.log("completed, stopping %s", writeScheduler);
writeScheduler.stop();
} else {
if (checkRequestCancelled()) return;
if (debug.on())
debug.log("onNext with " + Utils.remaining(data) + " bytes");
subscriber.onNext(data);
}
}
}
}
}
final class Http1WriteSubscription implements Flow.Subscription {
@Override
public void request(long n) {
if (cancelled)
return;
demand.increase(n);
if (debug.on())
debug.log("subscription request(%d), demand=%s", n, demand);
writeScheduler.runOrSchedule(client.theExecutor());
}
@Override
public void cancel() {
if (debug.on()) debug.log("subscription cancelled");
if (cancelled)
return;
cancelled = true;
writeScheduler.runOrSchedule(client.theExecutor());
}
}
}
HttpClient client() {
return client;
}
String dbgString() {
return "Http1Exchange";
}
}