src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/ExchangeImpl.java
branchhttp-client-branch
changeset 56089 42208b2f224e
parent 56088 38fac6d0521d
child 56090 5c7fb702948a
equal deleted inserted replaced
56088:38fac6d0521d 56089:42208b2f224e
     1 /*
       
     2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package jdk.incubator.http.internal;
       
    27 
       
    28 import java.io.IOException;
       
    29 import java.lang.System.Logger.Level;
       
    30 import java.util.concurrent.CompletableFuture;
       
    31 import java.util.concurrent.Executor;
       
    32 import java.util.function.Function;
       
    33 import jdk.incubator.http.HttpResponse;
       
    34 import jdk.incubator.http.internal.common.MinimalFuture;
       
    35 import static jdk.incubator.http.HttpClient.Version.HTTP_1_1;
       
    36 import jdk.incubator.http.internal.common.Utils;
       
    37 
       
    38 /**
       
    39  * Splits request so that headers and body can be sent separately with optional
       
    40  * (multiple) responses in between (e.g. 100 Continue). Also request and
       
    41  * response always sent/received in different calls.
       
    42  *
       
    43  * Synchronous and asynchronous versions of each method are provided.
       
    44  *
       
    45  * Separate implementations of this class exist for HTTP/1.1 and HTTP/2
       
    46  *      Http1Exchange   (HTTP/1.1)
       
    47  *      Stream          (HTTP/2)
       
    48  *
       
    49  * These implementation classes are where work is allocated to threads.
       
    50  */
       
    51 abstract class ExchangeImpl<T> {
       
    52 
       
    53     static final boolean DEBUG = Utils.DEBUG; // Revisit: temporary dev flag.
       
    54     private static final System.Logger DEBUG_LOGGER =
       
    55             Utils.getDebugLogger("ExchangeImpl"::toString, DEBUG);
       
    56 
       
    57     final Exchange<T> exchange;
       
    58 
       
    59     ExchangeImpl(Exchange<T> e) {
       
    60         // e == null means a http/2 pushed stream
       
    61         this.exchange = e;
       
    62     }
       
    63 
       
    64     final Exchange<T> getExchange() {
       
    65         return exchange;
       
    66     }
       
    67 
       
    68 
       
    69     /**
       
    70      * Returns the {@link HttpConnection} instance to which this exchange is
       
    71      * assigned.
       
    72      */
       
    73     abstract HttpConnection connection();
       
    74 
       
    75     /**
       
    76      * Initiates a new exchange and assigns it to a connection if one exists
       
    77      * already. connection usually null.
       
    78      */
       
    79     static <U> CompletableFuture<? extends ExchangeImpl<U>>
       
    80     get(Exchange<U> exchange, HttpConnection connection)
       
    81     {
       
    82         if (exchange.version() == HTTP_1_1) {
       
    83             DEBUG_LOGGER.log(Level.DEBUG, "get: HTTP/1.1: new Http1Exchange");
       
    84             return createHttp1Exchange(exchange, connection);
       
    85         } else {
       
    86             Http2ClientImpl c2 = exchange.client().client2(); // TODO: improve
       
    87             HttpRequestImpl request = exchange.request();
       
    88             CompletableFuture<Http2Connection> c2f = c2.getConnectionFor(request);
       
    89             DEBUG_LOGGER.log(Level.DEBUG, "get: Trying to get HTTP/2 connection");
       
    90             return c2f.handle((h2c, t) -> createExchangeImpl(h2c, t, exchange, connection))
       
    91                     .thenCompose(Function.identity());
       
    92         }
       
    93     }
       
    94 
       
    95     private static <U> CompletableFuture<? extends ExchangeImpl<U>>
       
    96     createExchangeImpl(Http2Connection c,
       
    97                        Throwable t,
       
    98                        Exchange<U> exchange,
       
    99                        HttpConnection connection)
       
   100     {
       
   101         DEBUG_LOGGER.log(Level.DEBUG, "handling HTTP/2 connection creation result");
       
   102         boolean secure = exchange.request().secure();
       
   103         if (t != null) {
       
   104             DEBUG_LOGGER.log(Level.DEBUG,
       
   105                              "handling HTTP/2 connection creation failed: %s",
       
   106                              (Object)t);
       
   107             t = Utils.getCompletionCause(t);
       
   108             if (t instanceof Http2Connection.ALPNException) {
       
   109                 Http2Connection.ALPNException ee = (Http2Connection.ALPNException)t;
       
   110                 AbstractAsyncSSLConnection as = ee.getConnection();
       
   111                 DEBUG_LOGGER.log(Level.DEBUG, "downgrading to HTTP/1.1 with: %s", as);
       
   112                 CompletableFuture<? extends ExchangeImpl<U>> ex =
       
   113                         createHttp1Exchange(exchange, as);
       
   114                 return ex;
       
   115             } else {
       
   116                 DEBUG_LOGGER.log(Level.DEBUG, "HTTP/2 connection creation failed "
       
   117                                   + "with unexpected exception: %s", (Object)t);
       
   118                 return MinimalFuture.failedFuture(t);
       
   119             }
       
   120         }
       
   121         if (secure && c== null) {
       
   122             DEBUG_LOGGER.log(Level.DEBUG, "downgrading to HTTP/1.1 ");
       
   123             CompletableFuture<? extends ExchangeImpl<U>> ex =
       
   124                     createHttp1Exchange(exchange, null);
       
   125             return ex;
       
   126         }
       
   127         if (c == null) {
       
   128             // no existing connection. Send request with HTTP 1 and then
       
   129             // upgrade if successful
       
   130             DEBUG_LOGGER.log(Level.DEBUG, "new Http1Exchange, try to upgrade");
       
   131             return createHttp1Exchange(exchange, connection)
       
   132                     .thenApply((e) -> {
       
   133                         exchange.h2Upgrade();
       
   134                         return e;
       
   135                     });
       
   136         } else {
       
   137             DEBUG_LOGGER.log(Level.DEBUG, "creating HTTP/2 streams");
       
   138             Stream<U> s = c.createStream(exchange);
       
   139             CompletableFuture<? extends ExchangeImpl<U>> ex = MinimalFuture.completedFuture(s);
       
   140             return ex;
       
   141         }
       
   142     }
       
   143 
       
   144     private static <T> CompletableFuture<Http1Exchange<T>>
       
   145     createHttp1Exchange(Exchange<T> ex, HttpConnection as)
       
   146     {
       
   147         try {
       
   148             return MinimalFuture.completedFuture(new Http1Exchange<>(ex, as));
       
   149         } catch (Throwable e) {
       
   150             return MinimalFuture.failedFuture(e);
       
   151         }
       
   152     }
       
   153 
       
   154     /* The following methods have separate HTTP/1.1 and HTTP/2 implementations */
       
   155 
       
   156     abstract CompletableFuture<ExchangeImpl<T>> sendHeadersAsync();
       
   157 
       
   158     /** Sends a request body, after request headers have been sent. */
       
   159     abstract CompletableFuture<ExchangeImpl<T>> sendBodyAsync();
       
   160 
       
   161     abstract CompletableFuture<T> readBodyAsync(HttpResponse.BodyHandler<T> handler,
       
   162                                                 boolean returnConnectionToPool,
       
   163                                                 Executor executor);
       
   164 
       
   165     /**
       
   166      * Ignore/consume the body.
       
   167      */
       
   168     abstract CompletableFuture<Void> ignoreBody();
       
   169 
       
   170     /** Gets the response headers. Completes before body is read. */
       
   171     abstract CompletableFuture<Response> getResponseAsync(Executor executor);
       
   172 
       
   173 
       
   174     /** Cancels a request.  Not currently exposed through API. */
       
   175     abstract void cancel();
       
   176 
       
   177     /**
       
   178      * Cancels a request with a cause.  Not currently exposed through API.
       
   179      */
       
   180     abstract void cancel(IOException cause);
       
   181 
       
   182     /**
       
   183      * Called when the exchange is released, so that cleanup actions may be
       
   184      * performed - such as deregistering callbacks.
       
   185      * Typically released is called during upgrade, when an HTTP/2 stream
       
   186      * takes over from an Http1Exchange, or when a new exchange is created
       
   187      * during a multi exchange before the final response body was received.
       
   188      */
       
   189     abstract void released();
       
   190 
       
   191     /**
       
   192      * Called when the exchange is completed, so that cleanup actions may be
       
   193      * performed - such as deregistering callbacks.
       
   194      * Typically, completed is called at the end of the exchange, when the
       
   195      * final response body has been received (or an error has caused the
       
   196      * completion of the exchange).
       
   197      */
       
   198     abstract void completed();
       
   199 
       
   200     /**
       
   201      * Returns true if this exchange was canceled.
       
   202      * @return true if this exchange was canceled.
       
   203      */
       
   204     abstract boolean isCanceled();
       
   205 
       
   206     /**
       
   207      * Returns the cause for which this exchange was canceled, if available.
       
   208      * @return the cause for which this exchange was canceled, if available.
       
   209      */
       
   210     abstract Throwable getCancelCause();
       
   211 }