49765
|
1 |
/*
|
|
2 |
* Copyright (c) 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.
|
|
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 |
* @summary Verify that dependent synchronous actions added before the promise CF
|
|
27 |
* completes are executed either asynchronously in an executor when the
|
|
28 |
* CF later completes, or in the user thread that joins.
|
|
29 |
* @library /lib/testlibrary http2/server
|
|
30 |
* @build jdk.testlibrary.SimpleSSLContext HttpServerAdapters ThrowingPublishers
|
|
31 |
* @modules java.base/sun.net.www.http
|
|
32 |
* java.net.http/jdk.internal.net.http.common
|
|
33 |
* java.net.http/jdk.internal.net.http.frame
|
|
34 |
* java.net.http/jdk.internal.net.http.hpack
|
|
35 |
* @run testng/othervm -Djdk.internal.httpclient.debug=true DependentPromiseActionsTest
|
|
36 |
* @run testng/othervm/java.security.policy=dependent.policy
|
|
37 |
* -Djdk.internal.httpclient.debug=true DependentPromiseActionsTest
|
|
38 |
*/
|
|
39 |
|
|
40 |
import java.io.BufferedReader;
|
|
41 |
import java.io.InputStreamReader;
|
|
42 |
import java.lang.StackWalker.StackFrame;
|
|
43 |
import jdk.internal.net.http.common.HttpHeadersImpl;
|
|
44 |
import jdk.testlibrary.SimpleSSLContext;
|
|
45 |
import org.testng.annotations.AfterTest;
|
|
46 |
import org.testng.annotations.AfterClass;
|
|
47 |
import org.testng.annotations.BeforeTest;
|
|
48 |
import org.testng.annotations.DataProvider;
|
|
49 |
import org.testng.annotations.Test;
|
|
50 |
|
|
51 |
import javax.net.ssl.SSLContext;
|
|
52 |
import java.io.IOException;
|
|
53 |
import java.io.InputStream;
|
|
54 |
import java.io.OutputStream;
|
|
55 |
import java.net.URI;
|
|
56 |
import java.net.URISyntaxException;
|
|
57 |
import java.net.http.HttpClient;
|
|
58 |
import java.net.http.HttpHeaders;
|
|
59 |
import java.net.http.HttpRequest;
|
|
60 |
import java.net.http.HttpResponse;
|
|
61 |
import java.net.http.HttpResponse.BodyHandler;
|
|
62 |
import java.net.http.HttpResponse.BodyHandlers;
|
|
63 |
import java.net.http.HttpResponse.BodySubscriber;
|
|
64 |
import java.net.http.HttpResponse.PushPromiseHandler;
|
|
65 |
import java.nio.ByteBuffer;
|
|
66 |
import java.nio.charset.StandardCharsets;
|
|
67 |
import java.util.EnumSet;
|
|
68 |
import java.util.List;
|
|
69 |
import java.util.Map;
|
|
70 |
import java.util.Optional;
|
|
71 |
import java.util.concurrent.CompletableFuture;
|
|
72 |
import java.util.concurrent.CompletionException;
|
|
73 |
import java.util.concurrent.CompletionStage;
|
|
74 |
import java.util.concurrent.ConcurrentHashMap;
|
|
75 |
import java.util.concurrent.ConcurrentMap;
|
|
76 |
import java.util.concurrent.Executor;
|
|
77 |
import java.util.concurrent.Executors;
|
|
78 |
import java.util.concurrent.Flow;
|
|
79 |
import java.util.concurrent.Semaphore;
|
|
80 |
import java.util.concurrent.atomic.AtomicLong;
|
|
81 |
import java.util.concurrent.atomic.AtomicReference;
|
|
82 |
import java.util.function.Consumer;
|
|
83 |
import java.util.function.Function;
|
|
84 |
import java.util.function.Supplier;
|
|
85 |
import java.util.stream.Collectors;
|
|
86 |
import java.util.stream.Stream;
|
|
87 |
|
|
88 |
import static java.lang.System.err;
|
|
89 |
import static java.lang.System.out;
|
|
90 |
import static java.lang.String.format;
|
|
91 |
import static java.nio.charset.StandardCharsets.UTF_8;
|
|
92 |
import static org.testng.Assert.assertEquals;
|
|
93 |
import static org.testng.Assert.assertTrue;
|
|
94 |
|
|
95 |
public class DependentPromiseActionsTest implements HttpServerAdapters {
|
|
96 |
|
|
97 |
SSLContext sslContext;
|
|
98 |
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
|
|
99 |
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
|
|
100 |
String http2URI_fixed;
|
|
101 |
String http2URI_chunk;
|
|
102 |
String https2URI_fixed;
|
|
103 |
String https2URI_chunk;
|
|
104 |
|
|
105 |
static final StackWalker WALKER =
|
|
106 |
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
|
|
107 |
|
|
108 |
static final int ITERATION_COUNT = 1;
|
|
109 |
// a shared executor helps reduce the amount of threads created by the test
|
|
110 |
static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());
|
|
111 |
static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();
|
|
112 |
static volatile boolean tasksFailed;
|
|
113 |
static final AtomicLong serverCount = new AtomicLong();
|
|
114 |
static final AtomicLong clientCount = new AtomicLong();
|
|
115 |
static final long start = System.nanoTime();
|
|
116 |
public static String now() {
|
|
117 |
long now = System.nanoTime() - start;
|
|
118 |
long secs = now / 1000_000_000;
|
|
119 |
long mill = (now % 1000_000_000) / 1000_000;
|
|
120 |
long nan = now % 1000_000;
|
|
121 |
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
|
|
122 |
}
|
|
123 |
|
|
124 |
private volatile HttpClient sharedClient;
|
|
125 |
|
|
126 |
static class TestExecutor implements Executor {
|
|
127 |
final AtomicLong tasks = new AtomicLong();
|
|
128 |
Executor executor;
|
|
129 |
TestExecutor(Executor executor) {
|
|
130 |
this.executor = executor;
|
|
131 |
}
|
|
132 |
|
|
133 |
@Override
|
|
134 |
public void execute(Runnable command) {
|
|
135 |
long id = tasks.incrementAndGet();
|
|
136 |
executor.execute(() -> {
|
|
137 |
try {
|
|
138 |
command.run();
|
|
139 |
} catch (Throwable t) {
|
|
140 |
tasksFailed = true;
|
|
141 |
System.out.printf(now() + "Task %s failed: %s%n", id, t);
|
|
142 |
System.err.printf(now() + "Task %s failed: %s%n", id, t);
|
|
143 |
FAILURES.putIfAbsent("Task " + id, t);
|
|
144 |
throw t;
|
|
145 |
}
|
|
146 |
});
|
|
147 |
}
|
|
148 |
}
|
|
149 |
|
|
150 |
@AfterClass
|
|
151 |
static final void printFailedTests() {
|
|
152 |
out.println("\n=========================");
|
|
153 |
try {
|
|
154 |
out.printf("%n%sCreated %d servers and %d clients%n",
|
|
155 |
now(), serverCount.get(), clientCount.get());
|
|
156 |
if (FAILURES.isEmpty()) return;
|
|
157 |
out.println("Failed tests: ");
|
|
158 |
FAILURES.entrySet().forEach((e) -> {
|
|
159 |
out.printf("\t%s: %s%n", e.getKey(), e.getValue());
|
|
160 |
e.getValue().printStackTrace(out);
|
|
161 |
e.getValue().printStackTrace();
|
|
162 |
});
|
|
163 |
if (tasksFailed) {
|
|
164 |
System.out.println("WARNING: Some tasks failed");
|
|
165 |
}
|
|
166 |
} finally {
|
|
167 |
out.println("\n=========================\n");
|
|
168 |
}
|
|
169 |
}
|
|
170 |
|
|
171 |
private String[] uris() {
|
|
172 |
return new String[] {
|
|
173 |
http2URI_fixed,
|
|
174 |
http2URI_chunk,
|
|
175 |
https2URI_fixed,
|
|
176 |
https2URI_chunk,
|
|
177 |
};
|
|
178 |
}
|
|
179 |
|
|
180 |
static final class SemaphoreStallerSupplier
|
|
181 |
implements Supplier<SemaphoreStaller> {
|
|
182 |
@Override
|
|
183 |
public SemaphoreStaller get() {
|
|
184 |
return new SemaphoreStaller();
|
|
185 |
}
|
|
186 |
@Override
|
|
187 |
public String toString() {
|
|
188 |
return "SemaphoreStaller";
|
|
189 |
}
|
|
190 |
}
|
|
191 |
|
|
192 |
@DataProvider(name = "noStalls")
|
|
193 |
public Object[][] noThrows() {
|
|
194 |
String[] uris = uris();
|
|
195 |
Object[][] result = new Object[uris.length * 2][];
|
|
196 |
int i = 0;
|
|
197 |
for (boolean sameClient : List.of(false, true)) {
|
|
198 |
for (String uri: uris()) {
|
|
199 |
result[i++] = new Object[] {uri, sameClient};
|
|
200 |
}
|
|
201 |
}
|
|
202 |
assert i == uris.length * 2;
|
|
203 |
return result;
|
|
204 |
}
|
|
205 |
|
|
206 |
@DataProvider(name = "variants")
|
|
207 |
public Object[][] variants() {
|
|
208 |
String[] uris = uris();
|
|
209 |
Object[][] result = new Object[uris.length * 2][];
|
|
210 |
int i = 0;
|
|
211 |
Supplier<? extends Staller> s = new SemaphoreStallerSupplier();
|
|
212 |
for (Supplier<? extends Staller> staller : List.of(s)) {
|
|
213 |
for (boolean sameClient : List.of(false, true)) {
|
|
214 |
for (String uri : uris()) {
|
|
215 |
result[i++] = new Object[]{uri, sameClient, staller};
|
|
216 |
}
|
|
217 |
}
|
|
218 |
}
|
|
219 |
assert i == uris.length * 2;
|
|
220 |
return result;
|
|
221 |
}
|
|
222 |
|
|
223 |
private HttpClient makeNewClient() {
|
|
224 |
clientCount.incrementAndGet();
|
|
225 |
return HttpClient.newBuilder()
|
|
226 |
.executor(executor)
|
|
227 |
.sslContext(sslContext)
|
|
228 |
.build();
|
|
229 |
}
|
|
230 |
|
|
231 |
HttpClient newHttpClient(boolean share) {
|
|
232 |
if (!share) return makeNewClient();
|
|
233 |
HttpClient shared = sharedClient;
|
|
234 |
if (shared != null) return shared;
|
|
235 |
synchronized (this) {
|
|
236 |
shared = sharedClient;
|
|
237 |
if (shared == null) {
|
|
238 |
shared = sharedClient = makeNewClient();
|
|
239 |
}
|
|
240 |
return shared;
|
|
241 |
}
|
|
242 |
}
|
|
243 |
|
|
244 |
@Test(dataProvider = "noStalls")
|
|
245 |
public void testNoStalls(String uri, boolean sameClient)
|
|
246 |
throws Exception {
|
|
247 |
HttpClient client = null;
|
|
248 |
out.printf("%ntestNoStalls(%s, %b)%n", uri, sameClient);
|
|
249 |
for (int i=0; i< ITERATION_COUNT; i++) {
|
|
250 |
if (!sameClient || client == null)
|
|
251 |
client = newHttpClient(sameClient);
|
|
252 |
|
|
253 |
HttpRequest req = HttpRequest.newBuilder(URI.create(uri))
|
|
254 |
.build();
|
|
255 |
BodyHandler<Stream<String>> handler =
|
|
256 |
new StallingBodyHandler((w) -> {},
|
|
257 |
BodyHandlers.ofLines());
|
|
258 |
Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> pushPromises =
|
|
259 |
new ConcurrentHashMap<>();
|
|
260 |
PushPromiseHandler<Stream<String>> pushHandler = new PushPromiseHandler<>() {
|
|
261 |
@Override
|
|
262 |
public void applyPushPromise(HttpRequest initiatingRequest,
|
|
263 |
HttpRequest pushPromiseRequest,
|
|
264 |
Function<BodyHandler<Stream<String>>,
|
|
265 |
CompletableFuture<HttpResponse<Stream<String>>>>
|
|
266 |
acceptor) {
|
|
267 |
pushPromises.putIfAbsent(pushPromiseRequest, acceptor.apply(handler));
|
|
268 |
}
|
|
269 |
};
|
|
270 |
HttpResponse<Stream<String>> response =
|
|
271 |
client.sendAsync(req, BodyHandlers.ofLines(), pushHandler).get();
|
|
272 |
String body = response.body().collect(Collectors.joining("|"));
|
|
273 |
assertEquals(URI.create(body).getPath(), URI.create(uri).getPath());
|
|
274 |
for (HttpRequest promised : pushPromises.keySet()) {
|
|
275 |
out.printf("%s Received promise: %s%n\tresponse: %s%n",
|
|
276 |
now(), promised, pushPromises.get(promised).get());
|
|
277 |
String promisedBody = pushPromises.get(promised).get().body()
|
|
278 |
.collect(Collectors.joining("|"));
|
|
279 |
assertEquals(promisedBody, promised.uri().toASCIIString());
|
|
280 |
}
|
|
281 |
assertEquals(3, pushPromises.size());
|
|
282 |
}
|
|
283 |
}
|
|
284 |
|
|
285 |
@Test(dataProvider = "variants")
|
|
286 |
public void testAsStringAsync(String uri,
|
|
287 |
boolean sameClient,
|
|
288 |
Supplier<Staller> stallers)
|
|
289 |
throws Exception
|
|
290 |
{
|
|
291 |
String test = format("testAsStringAsync(%s, %b, %s)",
|
|
292 |
uri, sameClient, stallers);
|
|
293 |
testDependent(test, uri, sameClient, BodyHandlers::ofString,
|
|
294 |
this::finish, this::extractString, stallers);
|
|
295 |
}
|
|
296 |
|
|
297 |
@Test(dataProvider = "variants")
|
|
298 |
public void testAsLinesAsync(String uri,
|
|
299 |
boolean sameClient,
|
|
300 |
Supplier<Staller> stallers)
|
|
301 |
throws Exception
|
|
302 |
{
|
|
303 |
String test = format("testAsLinesAsync(%s, %b, %s)",
|
|
304 |
uri, sameClient, stallers);
|
|
305 |
testDependent(test, uri, sameClient, BodyHandlers::ofLines,
|
|
306 |
this::finish, this::extractStream, stallers);
|
|
307 |
}
|
|
308 |
|
|
309 |
@Test(dataProvider = "variants")
|
|
310 |
public void testAsInputStreamAsync(String uri,
|
|
311 |
boolean sameClient,
|
|
312 |
Supplier<Staller> stallers)
|
|
313 |
throws Exception
|
|
314 |
{
|
|
315 |
String test = format("testAsInputStreamAsync(%s, %b, %s)",
|
|
316 |
uri, sameClient, stallers);
|
|
317 |
testDependent(test, uri, sameClient, BodyHandlers::ofInputStream,
|
|
318 |
this::finish, this::extractInputStream, stallers);
|
|
319 |
}
|
|
320 |
|
|
321 |
private <T,U> void testDependent(String name, String uri, boolean sameClient,
|
|
322 |
Supplier<BodyHandler<T>> handlers,
|
|
323 |
Finisher finisher,
|
|
324 |
Extractor<T> extractor,
|
|
325 |
Supplier<Staller> stallers)
|
|
326 |
throws Exception
|
|
327 |
{
|
|
328 |
out.printf("%n%s%s%n", now(), name);
|
|
329 |
try {
|
|
330 |
testDependent(uri, sameClient, handlers, finisher, extractor, stallers);
|
|
331 |
} catch (Error | Exception x) {
|
|
332 |
FAILURES.putIfAbsent(name, x);
|
|
333 |
throw x;
|
|
334 |
}
|
|
335 |
}
|
|
336 |
|
|
337 |
private <T,U> void testDependent(String uri, boolean sameClient,
|
|
338 |
Supplier<BodyHandler<T>> handlers,
|
|
339 |
Finisher finisher,
|
|
340 |
Extractor<T> extractor,
|
|
341 |
Supplier<Staller> stallers)
|
|
342 |
throws Exception
|
|
343 |
{
|
|
344 |
HttpClient client = null;
|
|
345 |
for (Where where : EnumSet.of(Where.BODY_HANDLER)) {
|
|
346 |
if (!sameClient || client == null)
|
|
347 |
client = newHttpClient(sameClient);
|
|
348 |
|
|
349 |
HttpRequest req = HttpRequest.
|
|
350 |
newBuilder(URI.create(uri))
|
|
351 |
.build();
|
|
352 |
StallingPushPromiseHandler<T> promiseHandler =
|
|
353 |
new StallingPushPromiseHandler<>(where, handlers, stallers);
|
|
354 |
BodyHandler<T> handler = handlers.get();
|
|
355 |
System.out.println("try stalling in " + where);
|
|
356 |
CompletableFuture<HttpResponse<T>> responseCF =
|
|
357 |
client.sendAsync(req, handler, promiseHandler);
|
|
358 |
assert !responseCF.isDone();
|
|
359 |
finisher.finish(where, responseCF, promiseHandler, extractor);
|
|
360 |
}
|
|
361 |
}
|
|
362 |
|
|
363 |
enum Where {
|
|
364 |
ON_PUSH_PROMISE, BODY_HANDLER, ON_SUBSCRIBE, ON_NEXT, ON_COMPLETE, ON_ERROR, GET_BODY, BODY_CF;
|
|
365 |
public Consumer<Where> select(Consumer<Where> consumer) {
|
|
366 |
return new Consumer<Where>() {
|
|
367 |
@Override
|
|
368 |
public void accept(Where where) {
|
|
369 |
if (Where.this == where) {
|
|
370 |
consumer.accept(where);
|
|
371 |
}
|
|
372 |
}
|
|
373 |
};
|
|
374 |
}
|
|
375 |
}
|
|
376 |
|
|
377 |
static final class StallingPushPromiseHandler<T> implements PushPromiseHandler<T> {
|
|
378 |
|
|
379 |
static final class Tuple<U> {
|
|
380 |
public final CompletableFuture<HttpResponse<U>> response;
|
|
381 |
public final Staller staller;
|
|
382 |
public final AtomicReference<RuntimeException> failed;
|
|
383 |
Tuple(AtomicReference<RuntimeException> failed,
|
|
384 |
CompletableFuture<HttpResponse<U>> response,
|
|
385 |
Staller staller) {
|
|
386 |
this.response = response;
|
|
387 |
this.staller = staller;
|
|
388 |
this.failed = failed;
|
|
389 |
}
|
|
390 |
}
|
|
391 |
|
|
392 |
public final ConcurrentMap<HttpRequest, Tuple<T>> promiseMap =
|
|
393 |
new ConcurrentHashMap<>();
|
|
394 |
private final Supplier<Staller> stallers;
|
|
395 |
private final Supplier<BodyHandler<T>> handlers;
|
|
396 |
private final Where where;
|
|
397 |
private final Thread thread = Thread.currentThread(); // main thread
|
|
398 |
|
|
399 |
StallingPushPromiseHandler(Where where,
|
|
400 |
Supplier<BodyHandler<T>> handlers,
|
|
401 |
Supplier<Staller> stallers) {
|
|
402 |
this.where = where;
|
|
403 |
this.handlers = handlers;
|
|
404 |
this.stallers = stallers;
|
|
405 |
}
|
|
406 |
|
|
407 |
@Override
|
|
408 |
public void applyPushPromise(HttpRequest initiatingRequest,
|
|
409 |
HttpRequest pushPromiseRequest,
|
|
410 |
Function<BodyHandler<T>,
|
|
411 |
CompletableFuture<HttpResponse<T>>> acceptor) {
|
|
412 |
AtomicReference<RuntimeException> failed = new AtomicReference<>();
|
|
413 |
Staller staller = stallers.get();
|
|
414 |
staller.acquire();
|
|
415 |
assert staller.willStall();
|
|
416 |
try {
|
|
417 |
BodyHandler handler = new StallingBodyHandler<>(
|
|
418 |
where.select(staller), handlers.get());
|
|
419 |
CompletableFuture<HttpResponse<T>> cf = acceptor.apply(handler);
|
|
420 |
Tuple<T> tuple = new Tuple(failed, cf, staller);
|
|
421 |
promiseMap.putIfAbsent(pushPromiseRequest, tuple);
|
|
422 |
CompletableFuture<?> done = cf.whenComplete(
|
|
423 |
(r, t) -> checkThreadAndStack(thread, failed, r, t));
|
|
424 |
assert !cf.isDone();
|
|
425 |
} finally {
|
|
426 |
staller.release();
|
|
427 |
}
|
|
428 |
}
|
|
429 |
}
|
|
430 |
|
|
431 |
interface Extractor<T> {
|
|
432 |
public List<String> extract(HttpResponse<T> resp);
|
|
433 |
}
|
|
434 |
|
|
435 |
final List<String> extractString(HttpResponse<String> resp) {
|
|
436 |
return List.of(resp.body());
|
|
437 |
}
|
|
438 |
|
|
439 |
final List<String> extractStream(HttpResponse<Stream<String>> resp) {
|
|
440 |
return resp.body().collect(Collectors.toList());
|
|
441 |
}
|
|
442 |
|
|
443 |
final List<String> extractInputStream(HttpResponse<InputStream> resp) {
|
|
444 |
try (InputStream is = resp.body()) {
|
|
445 |
return new BufferedReader(new InputStreamReader(is))
|
|
446 |
.lines().collect(Collectors.toList());
|
|
447 |
} catch (IOException x) {
|
|
448 |
throw new CompletionException(x);
|
|
449 |
}
|
|
450 |
}
|
|
451 |
|
|
452 |
interface Finisher<T> {
|
|
453 |
public void finish(Where w,
|
|
454 |
CompletableFuture<HttpResponse<T>> cf,
|
|
455 |
StallingPushPromiseHandler<T> ph,
|
|
456 |
Extractor<T> extractor);
|
|
457 |
}
|
|
458 |
|
|
459 |
static Optional<StackFrame> findFrame(Stream<StackFrame> s, String name) {
|
|
460 |
return s.filter((f) -> f.getClassName().contains(name))
|
|
461 |
.filter((f) -> f.getDeclaringClass().getModule().equals(HttpClient.class.getModule()))
|
|
462 |
.findFirst();
|
|
463 |
}
|
|
464 |
|
|
465 |
static <T> void checkThreadAndStack(Thread thread,
|
|
466 |
AtomicReference<RuntimeException> failed,
|
|
467 |
T result,
|
|
468 |
Throwable error) {
|
|
469 |
if (Thread.currentThread() == thread) {
|
|
470 |
//failed.set(new RuntimeException("Dependant action was executed in " + thread));
|
|
471 |
List<StackFrame> httpStack = WALKER.walk(s -> s.filter(f -> f.getDeclaringClass()
|
|
472 |
.getModule().equals(HttpClient.class.getModule()))
|
|
473 |
.collect(Collectors.toList()));
|
|
474 |
if (!httpStack.isEmpty()) {
|
|
475 |
System.out.println("Found unexpected trace: ");
|
|
476 |
httpStack.forEach(f -> System.out.printf("\t%s%n", f));
|
|
477 |
failed.set(new RuntimeException("Dependant action has unexpected frame in " +
|
|
478 |
Thread.currentThread() + ": " + httpStack.get(0)));
|
|
479 |
|
|
480 |
} return;
|
|
481 |
} else if (System.getSecurityManager() != null) {
|
|
482 |
Optional<StackFrame> sf = WALKER.walk(s -> findFrame(s, "PrivilegedRunnable"));
|
|
483 |
if (!sf.isPresent()) {
|
|
484 |
failed.set(new RuntimeException("Dependant action does not have expected frame in "
|
|
485 |
+ Thread.currentThread()));
|
|
486 |
return;
|
|
487 |
} else {
|
|
488 |
System.out.println("Found expected frame: " + sf.get());
|
|
489 |
}
|
|
490 |
} else {
|
|
491 |
List<StackFrame> httpStack = WALKER.walk(s -> s.filter(f -> f.getDeclaringClass()
|
|
492 |
.getModule().equals(HttpClient.class.getModule()))
|
|
493 |
.collect(Collectors.toList()));
|
|
494 |
if (!httpStack.isEmpty()) {
|
|
495 |
System.out.println("Found unexpected trace: ");
|
|
496 |
httpStack.forEach(f -> System.out.printf("\t%s%n", f));
|
|
497 |
failed.set(new RuntimeException("Dependant action has unexpected frame in " +
|
|
498 |
Thread.currentThread() + ": " + httpStack.get(0)));
|
|
499 |
|
|
500 |
}
|
|
501 |
}
|
|
502 |
}
|
|
503 |
|
|
504 |
<T> void finish(Where w,
|
|
505 |
StallingPushPromiseHandler.Tuple<T> tuple,
|
|
506 |
Extractor<T> extractor) {
|
|
507 |
AtomicReference<RuntimeException> failed = tuple.failed;
|
|
508 |
CompletableFuture<HttpResponse<T>> done = tuple.response;
|
|
509 |
Staller staller = tuple.staller;
|
|
510 |
try {
|
|
511 |
HttpResponse<T> response = done.join();
|
|
512 |
List<String> result = extractor.extract(response);
|
|
513 |
URI uri = response.uri();
|
|
514 |
RuntimeException error = failed.get();
|
|
515 |
if (error != null) {
|
|
516 |
throw new RuntimeException("Test failed in "
|
|
517 |
+ w + ": " + uri, error);
|
|
518 |
}
|
|
519 |
assertEquals(result, List.of(response.request().uri().toASCIIString()));
|
|
520 |
} finally {
|
|
521 |
staller.reset();
|
|
522 |
}
|
|
523 |
}
|
|
524 |
|
|
525 |
<T> void finish(Where w,
|
|
526 |
CompletableFuture<HttpResponse<T>> cf,
|
|
527 |
StallingPushPromiseHandler<T> ph,
|
|
528 |
Extractor<T> extractor) {
|
|
529 |
HttpResponse<T> response = cf.join();
|
|
530 |
List<String> result = extractor.extract(response);
|
|
531 |
for (HttpRequest req : ph.promiseMap.keySet()) {
|
|
532 |
finish(w, ph.promiseMap.get(req), extractor);
|
|
533 |
}
|
|
534 |
assertEquals(ph.promiseMap.size(), 3,
|
|
535 |
"Expected 3 push promises for " + w + " in "
|
|
536 |
+ response.request().uri());
|
|
537 |
assertEquals(result, List.of(response.request().uri().toASCIIString()));
|
|
538 |
|
|
539 |
}
|
|
540 |
|
|
541 |
interface Staller extends Consumer<Where> {
|
|
542 |
void release();
|
|
543 |
void acquire();
|
|
544 |
void reset();
|
|
545 |
boolean willStall();
|
|
546 |
}
|
|
547 |
|
|
548 |
static final class SemaphoreStaller implements Staller {
|
|
549 |
final Semaphore sem = new Semaphore(1);
|
|
550 |
@Override
|
|
551 |
public void accept(Where where) {
|
|
552 |
sem.acquireUninterruptibly();
|
|
553 |
}
|
|
554 |
|
|
555 |
@Override
|
|
556 |
public void release() {
|
|
557 |
sem.release();
|
|
558 |
}
|
|
559 |
|
|
560 |
@Override
|
|
561 |
public void acquire() {
|
|
562 |
sem.acquireUninterruptibly();
|
|
563 |
}
|
|
564 |
|
|
565 |
@Override
|
|
566 |
public void reset() {
|
|
567 |
sem.drainPermits();
|
|
568 |
sem.release();
|
|
569 |
}
|
|
570 |
|
|
571 |
@Override
|
|
572 |
public boolean willStall() {
|
|
573 |
return sem.availablePermits() <= 0;
|
|
574 |
}
|
|
575 |
|
|
576 |
@Override
|
|
577 |
public String toString() {
|
|
578 |
return "SemaphoreStaller";
|
|
579 |
}
|
|
580 |
}
|
|
581 |
|
|
582 |
static final class StallingBodyHandler<T> implements BodyHandler<T> {
|
|
583 |
final Consumer<Where> stalling;
|
|
584 |
final BodyHandler<T> bodyHandler;
|
|
585 |
StallingBodyHandler(Consumer<Where> stalling, BodyHandler<T> bodyHandler) {
|
|
586 |
this.stalling = stalling;
|
|
587 |
this.bodyHandler = bodyHandler;
|
|
588 |
}
|
|
589 |
@Override
|
|
590 |
public BodySubscriber<T> apply(HttpResponse.ResponseInfo rinfo) {
|
|
591 |
stalling.accept(Where.BODY_HANDLER);
|
|
592 |
BodySubscriber<T> subscriber = bodyHandler.apply(rinfo);
|
|
593 |
return new StallingBodySubscriber(stalling, subscriber);
|
|
594 |
}
|
|
595 |
}
|
|
596 |
|
|
597 |
static final class StallingBodySubscriber<T> implements BodySubscriber<T> {
|
|
598 |
private final BodySubscriber<T> subscriber;
|
|
599 |
volatile boolean onSubscribeCalled;
|
|
600 |
final Consumer<Where> stalling;
|
|
601 |
StallingBodySubscriber(Consumer<Where> stalling, BodySubscriber<T> subscriber) {
|
|
602 |
this.stalling = stalling;
|
|
603 |
this.subscriber = subscriber;
|
|
604 |
}
|
|
605 |
|
|
606 |
@Override
|
|
607 |
public void onSubscribe(Flow.Subscription subscription) {
|
|
608 |
//out.println("onSubscribe ");
|
|
609 |
onSubscribeCalled = true;
|
|
610 |
stalling.accept(Where.ON_SUBSCRIBE);
|
|
611 |
subscriber.onSubscribe(subscription);
|
|
612 |
}
|
|
613 |
|
|
614 |
@Override
|
|
615 |
public void onNext(List<ByteBuffer> item) {
|
|
616 |
// out.println("onNext " + item);
|
|
617 |
assertTrue(onSubscribeCalled);
|
|
618 |
stalling.accept(Where.ON_NEXT);
|
|
619 |
subscriber.onNext(item);
|
|
620 |
}
|
|
621 |
|
|
622 |
@Override
|
|
623 |
public void onError(Throwable throwable) {
|
|
624 |
//out.println("onError");
|
|
625 |
assertTrue(onSubscribeCalled);
|
|
626 |
stalling.accept(Where.ON_ERROR);
|
|
627 |
subscriber.onError(throwable);
|
|
628 |
}
|
|
629 |
|
|
630 |
@Override
|
|
631 |
public void onComplete() {
|
|
632 |
//out.println("onComplete");
|
|
633 |
assertTrue(onSubscribeCalled, "onComplete called before onSubscribe");
|
|
634 |
stalling.accept(Where.ON_COMPLETE);
|
|
635 |
subscriber.onComplete();
|
|
636 |
}
|
|
637 |
|
|
638 |
@Override
|
|
639 |
public CompletionStage<T> getBody() {
|
|
640 |
stalling.accept(Where.GET_BODY);
|
|
641 |
try {
|
|
642 |
stalling.accept(Where.BODY_CF);
|
|
643 |
} catch (Throwable t) {
|
|
644 |
return CompletableFuture.failedFuture(t);
|
|
645 |
}
|
|
646 |
return subscriber.getBody();
|
|
647 |
}
|
|
648 |
}
|
|
649 |
|
|
650 |
|
|
651 |
@BeforeTest
|
|
652 |
public void setup() throws Exception {
|
|
653 |
sslContext = new SimpleSSLContext().get();
|
|
654 |
if (sslContext == null)
|
|
655 |
throw new AssertionError("Unexpected null sslContext");
|
|
656 |
|
|
657 |
// HTTP/2
|
|
658 |
HttpTestHandler h2_fixedLengthHandler = new HTTP_FixedLengthHandler();
|
|
659 |
HttpTestHandler h2_chunkedHandler = new HTTP_ChunkedHandler();
|
|
660 |
|
|
661 |
http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));
|
|
662 |
http2TestServer.addHandler(h2_fixedLengthHandler, "/http2/fixed");
|
|
663 |
http2TestServer.addHandler(h2_chunkedHandler, "/http2/chunk");
|
|
664 |
http2URI_fixed = "http://" + http2TestServer.serverAuthority() + "/http2/fixed/y";
|
|
665 |
http2URI_chunk = "http://" + http2TestServer.serverAuthority() + "/http2/chunk/y";
|
|
666 |
|
|
667 |
https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, 0));
|
|
668 |
https2TestServer.addHandler(h2_fixedLengthHandler, "/https2/fixed");
|
|
669 |
https2TestServer.addHandler(h2_chunkedHandler, "/https2/chunk");
|
|
670 |
https2URI_fixed = "https://" + https2TestServer.serverAuthority() + "/https2/fixed/y";
|
|
671 |
https2URI_chunk = "https://" + https2TestServer.serverAuthority() + "/https2/chunk/y";
|
|
672 |
|
|
673 |
serverCount.addAndGet(4);
|
|
674 |
http2TestServer.start();
|
|
675 |
https2TestServer.start();
|
|
676 |
}
|
|
677 |
|
|
678 |
@AfterTest
|
|
679 |
public void teardown() throws Exception {
|
|
680 |
sharedClient = null;
|
|
681 |
http2TestServer.stop();
|
|
682 |
https2TestServer.stop();
|
|
683 |
}
|
|
684 |
|
|
685 |
private static void pushPromiseFor(HttpTestExchange t, URI requestURI, String pushPath, boolean fixed)
|
|
686 |
throws IOException
|
|
687 |
{
|
|
688 |
try {
|
|
689 |
URI promise = new URI(requestURI.getScheme(),
|
|
690 |
requestURI.getAuthority(),
|
|
691 |
pushPath, null, null);
|
|
692 |
byte[] promiseBytes = promise.toASCIIString().getBytes(UTF_8);
|
|
693 |
out.printf("TestServer: %s Pushing promise: %s%n", now(), promise);
|
|
694 |
err.printf("TestServer: %s Pushing promise: %s%n", now(), promise);
|
|
695 |
HttpTestHeaders headers = HttpTestHeaders.of(new HttpHeadersImpl());
|
|
696 |
if (fixed) {
|
|
697 |
headers.addHeader("Content-length", String.valueOf(promiseBytes.length));
|
|
698 |
}
|
|
699 |
t.serverPush(promise, headers, promiseBytes);
|
|
700 |
} catch (URISyntaxException x) {
|
|
701 |
throw new IOException(x.getMessage(), x);
|
|
702 |
}
|
|
703 |
}
|
|
704 |
|
|
705 |
static class HTTP_FixedLengthHandler implements HttpTestHandler {
|
|
706 |
@Override
|
|
707 |
public void handle(HttpTestExchange t) throws IOException {
|
|
708 |
out.println("HTTP_FixedLengthHandler received request to " + t.getRequestURI());
|
|
709 |
try (InputStream is = t.getRequestBody()) {
|
|
710 |
is.readAllBytes();
|
|
711 |
}
|
|
712 |
URI requestURI = t.getRequestURI();
|
|
713 |
for (int i = 1; i<2; i++) {
|
|
714 |
String path = requestURI.getPath() + "/before/promise-" + i;
|
|
715 |
pushPromiseFor(t, requestURI, path, true);
|
|
716 |
}
|
|
717 |
byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);
|
|
718 |
t.sendResponseHeaders(200, resp.length); //fixed content length
|
|
719 |
try (OutputStream os = t.getResponseBody()) {
|
|
720 |
int bytes = resp.length/3;
|
|
721 |
for (int i = 0; i<2; i++) {
|
|
722 |
String path = requestURI.getPath() + "/after/promise-" + (i + 2);
|
|
723 |
os.write(resp, i * bytes, bytes);
|
|
724 |
os.flush();
|
|
725 |
pushPromiseFor(t, requestURI, path, true);
|
|
726 |
}
|
|
727 |
os.write(resp, 2*bytes, resp.length - 2*bytes);
|
|
728 |
}
|
|
729 |
}
|
|
730 |
|
|
731 |
}
|
|
732 |
|
|
733 |
static class HTTP_ChunkedHandler implements HttpTestHandler {
|
|
734 |
@Override
|
|
735 |
public void handle(HttpTestExchange t) throws IOException {
|
|
736 |
out.println("HTTP_ChunkedHandler received request to " + t.getRequestURI());
|
|
737 |
byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);
|
|
738 |
try (InputStream is = t.getRequestBody()) {
|
|
739 |
is.readAllBytes();
|
|
740 |
}
|
|
741 |
URI requestURI = t.getRequestURI();
|
|
742 |
for (int i = 1; i<2; i++) {
|
|
743 |
String path = requestURI.getPath() + "/before/promise-" + i;
|
|
744 |
pushPromiseFor(t, requestURI, path, false);
|
|
745 |
}
|
|
746 |
t.sendResponseHeaders(200, -1); // chunked/variable
|
|
747 |
try (OutputStream os = t.getResponseBody()) {
|
|
748 |
int bytes = resp.length/3;
|
|
749 |
for (int i = 0; i<2; i++) {
|
|
750 |
String path = requestURI.getPath() + "/after/promise-" + (i + 2);
|
|
751 |
os.write(resp, i * bytes, bytes);
|
|
752 |
os.flush();
|
|
753 |
pushPromiseFor(t, requestURI, path, false);
|
|
754 |
}
|
|
755 |
os.write(resp, 2*bytes, resp.length - 2*bytes);
|
|
756 |
}
|
|
757 |
}
|
|
758 |
}
|
|
759 |
|
|
760 |
|
|
761 |
}
|