1 /*
  2  * Copyright (c) 2018, 2023, 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.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 /*
 25  * @test
 26  * @bug 8196389
 27  * @summary Should HttpClient support SETTINGS_MAX_CONCURRENT_STREAMS from the server
 28  * @library /test/lib /test/jdk/java/net/httpclient/lib
 29  * @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
 30  * @run testng/othervm MaxStreams
 31  */
 32 
 33 import java.io.IOException;
 34 import java.io.InputStream;
 35 import java.io.OutputStream;
 36 import java.net.InetAddress;
 37 import java.net.InetSocketAddress;
 38 import java.net.URI;
 39 import java.util.List;
 40 import java.util.LinkedList;
 41 import java.util.Properties;
 42 import java.util.concurrent.atomic.AtomicInteger;
 43 import java.util.concurrent.CompletableFuture;
 44 import java.util.concurrent.CompletionException;
 45 import java.util.concurrent.CountDownLatch;
 46 import java.util.concurrent.Executors;
 47 import java.util.concurrent.ExecutorService;
 48 import javax.net.ssl.SSLContext;
 49 import java.net.http.HttpClient;
 50 import java.net.http.HttpRequest;
 51 import java.net.http.HttpResponse;
 52 import java.net.http.HttpResponse.BodyHandler;
 53 import java.net.http.HttpResponse.BodyHandlers;
 54 import jdk.httpclient.test.lib.http2.Http2TestServer;
 55 import jdk.httpclient.test.lib.http2.Http2TestExchange;
 56 import jdk.httpclient.test.lib.http2.Http2Handler;
 57 import jdk.test.lib.net.SimpleSSLContext;
 58 import org.testng.annotations.AfterTest;
 59 import org.testng.annotations.BeforeTest;
 60 import org.testng.annotations.DataProvider;
 61 import org.testng.annotations.Test;
 62 import static java.nio.charset.StandardCharsets.UTF_8;
 63 import static java.net.http.HttpResponse.BodyHandlers.discarding;
 64 import static org.testng.Assert.assertEquals;
 65 import static org.testng.Assert.assertFalse;
 66 import static org.testng.Assert.fail;
 67 
 68 public class MaxStreams {
 69 
 70     Http2TestServer http2TestServer;   // HTTP/2 ( h2c )
 71     Http2TestServer https2TestServer;   // HTTP/2 ( h2 )
 72     final Http2FixedHandler handler = new Http2FixedHandler();
 73     SSLContext ctx;
 74     String http2FixedURI;
 75     String https2FixedURI;
 76     ExecutorService exec;
 77 
 78     // we send an initial warm up request, then MAX_STREAMS+1 requests
 79     // in parallel. The last of them should hit the limit.
 80     // Then we wait for all the responses and send a further request
 81     // which should succeed. The server should see (and respond to)
 82     // MAX_STREAMS+2 requests per test run.
 83 
 84     static final int MAX_STREAMS = 10;
 85     static final String RESPONSE = "Hello world";
 86 
 87     @DataProvider(name = "uris")
 88     public Object[][] variants() {
 89         return new Object[][]{
 90                 {http2FixedURI},
 91                 {https2FixedURI},
 92                 {http2FixedURI},
 93                 {https2FixedURI}
 94         };
 95     }
 96 
 97 
 98     @Test(dataProvider = "uris")
 99     void testAsString(String uri) throws Exception {
100         CountDownLatch latch = new CountDownLatch(1);
101         handler.setLatch(latch);
102         HttpClient client = HttpClient.newBuilder().sslContext(ctx).build();
103         List<CompletableFuture<HttpResponse<String>>> responses = new LinkedList<>();
104 
105         HttpRequest request = HttpRequest.newBuilder(URI.create(uri))
106                                          .version(HttpClient.Version.HTTP_2)
107                                          .GET()
108                                          .build();
109         // send warmup to ensure we only have one Http2Connection
110         System.err.println("Sending warmup request");
111         HttpResponse<String> warmup = client.send(request, BodyHandlers.ofString());
112         if (warmup.statusCode() != 200 || !warmup.body().equals(RESPONSE))
113             throw new RuntimeException();
114 
115         for (int i=0;i<MAX_STREAMS+1; i++) {
116             System.err.println("Sending request " + i);
117             responses.add(client.sendAsync(request, BodyHandlers.ofString()));
118         }
119 
120         // wait until we get local exception before allow server to proceed
121         try {
122             System.err.println("Waiting for first exception");
123             CompletableFuture.anyOf(responses.toArray(new CompletableFuture<?>[0])).join();
124         } catch (Exception ee) {
125             System.err.println("Expected exception 1 " + ee);
126         }
127 
128         latch.countDown();
129 
130         // check the first MAX_STREAMS requests succeeded
131         try {
132             System.err.println("Waiting for second exception");
133             CompletableFuture.allOf(responses.toArray(new CompletableFuture<?>[0])).join();
134             System.err.println("Did not get Expected exception 2 ");
135         } catch (Exception ee) {
136             System.err.println("Expected exception 2 " + ee);
137         }
138         int count = 0;
139         int failures = 0;
140         for (CompletableFuture<HttpResponse<String>> cf : responses) {
141             HttpResponse<String> r = null;
142             try {
143                 count++;
144                 r = cf.join();
145                 if (r.statusCode() != 200 || !r.body().equals(RESPONSE))
146                     throw new RuntimeException();
147             } catch (Throwable t) {
148                 failures++;
149                 System.err.printf("Failure %d at count %d\n", failures, count);
150                 System.err.println(t);
151                 t.printStackTrace();
152             }
153         }
154         if (failures != 1) {
155             String msg = "Expected 1 failure. Got " + failures;
156             throw new RuntimeException(msg);
157         }
158 
159         System.err.println("Sending last request");
160         // make sure it succeeds now as number of streams == 0 now
161         HttpResponse<String> warmdown = client.send(request, BodyHandlers.ofString());
162         if (warmdown.statusCode() != 200 || !warmdown.body().equals(RESPONSE))
163             throw new RuntimeException();
164         System.err.println("Test OK");
165     }
166 
167     @BeforeTest
168     public void setup() throws Exception {
169         ctx = (new SimpleSSLContext()).get();
170         exec = Executors.newCachedThreadPool();
171 
172         InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
173 
174         Properties props = new Properties();
175         props.setProperty("http2server.settings.max_concurrent_streams", Integer.toString(MAX_STREAMS));
176         http2TestServer = new Http2TestServer("localhost", false, 0, exec, 10, props, null);
177         http2TestServer.addHandler(handler, "/http2/fixed");
178         http2FixedURI = "http://" + http2TestServer.serverAuthority()+ "/http2/fixed";
179         http2TestServer.start();
180 
181         https2TestServer = new Http2TestServer("localhost", true, 0, exec, 10, props, ctx);
182         https2TestServer.addHandler(handler, "/https2/fixed");
183         https2FixedURI = "https://" + https2TestServer.serverAuthority()+ "/https2/fixed";
184         https2TestServer.start();
185     }
186 
187     @AfterTest
188     public void teardown() throws Exception {
189         System.err.println("Stopping test server now");
190         http2TestServer.stop();
191     }
192 
193     class Http2FixedHandler implements Http2Handler {
194         final AtomicInteger counter = new AtomicInteger(0);
195         volatile CountDownLatch latch;
196 
197         synchronized void setLatch(CountDownLatch latch) {
198             this.latch = latch;
199         }
200 
201         synchronized CountDownLatch getLatch() {
202             return latch;
203         }
204 
205         @Override
206         public void handle(Http2TestExchange t) throws IOException {
207             try (InputStream is = t.getRequestBody();
208                  OutputStream os = t.getResponseBody()) {
209 
210                 is.readAllBytes();
211                 int c = counter.getAndIncrement();
212                 if (c > 0 && c <= MAX_STREAMS) {
213                     // Wait for latch.
214                     try {
215                         // don't send any replies until all requests are sent
216                         System.err.println("Latch await");
217                         getLatch().await();
218                         System.err.println("Latch resume");
219                     } catch (InterruptedException ee) {}
220                 } else if (c == MAX_STREAMS + 1) {
221                     // client issues MAX_STREAMS + 3 requests in total
222                     // but server should only see MAX_STREAMS + 2 in total. One is rejected by client
223                     // counter c captured before increment so final value is MAX_STREAMS + 1
224                     System.err.println("Counter reset");
225                     counter.set(0);
226                 }
227                 t.sendResponseHeaders(200, RESPONSE.length());
228                 os.write(RESPONSE.getBytes());
229             }
230         }
231     }
232 }