author | chegar |
Wed, 07 Feb 2018 14:17:24 +0000 | |
branch | http-client-branch |
changeset 56089 | 42208b2f224e |
parent 55973 | 4d9b002587db |
child 56167 | 96fa4f49a9ff |
permissions | -rw-r--r-- |
48083 | 1 |
/* |
2 |
* Copyright (c) 2017, 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 |
import java.nio.ByteBuffer; |
|
25 |
import java.util.List; |
|
26 |
import java.util.Random; |
|
27 |
import java.util.concurrent.CompletableFuture; |
|
28 |
import java.util.concurrent.CompletionStage; |
|
29 |
import java.util.concurrent.Executor; |
|
30 |
import java.util.concurrent.ExecutorService; |
|
31 |
import java.util.concurrent.Executors; |
|
32 |
import java.util.concurrent.Flow; |
|
33 |
import java.util.concurrent.Flow.Subscription; |
|
34 |
import java.util.concurrent.SubmissionPublisher; |
|
35 |
import java.util.function.BiConsumer; |
|
56089
42208b2f224e
http-client-branch: move to standard package and module name
chegar
parents:
55973
diff
changeset
|
36 |
import java.net.http.HttpResponse.BodyHandler; |
42208b2f224e
http-client-branch: move to standard package and module name
chegar
parents:
55973
diff
changeset
|
37 |
import java.net.http.HttpResponse.BodySubscriber; |
48083 | 38 |
import jdk.test.lib.RandomFactory; |
39 |
import org.testng.annotations.DataProvider; |
|
40 |
import org.testng.annotations.Test; |
|
41 |
import static java.lang.Long.MAX_VALUE; |
|
42 |
import static java.lang.Long.min; |
|
43 |
import static java.lang.System.out; |
|
44 |
import static java.util.concurrent.CompletableFuture.delayedExecutor; |
|
45 |
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
|
46 |
import static org.testng.Assert.*; |
|
47 |
||
48 |
/* |
|
49 |
* @test |
|
50 |
* @bug 8184285 |
|
51 |
* @summary Direct test for HttpResponse.BodySubscriber.buffering() API |
|
52 |
* @key randomness |
|
53 |
* @library /test/lib |
|
54 |
* @build jdk.test.lib.RandomFactory |
|
55 |
* @run testng/othervm -Djdk.internal.httpclient.debug=true BufferingSubscriberTest |
|
56 |
*/ |
|
57 |
||
58 |
public class BufferingSubscriberTest { |
|
59 |
||
60 |
// If we compute that a test will take less that 10s |
|
61 |
// we judge it acceptable |
|
62 |
static final long LOWER_THRESHOLD = 10_000; // 10 sec. |
|
63 |
// If we compute that a test will take more than 20 sec |
|
64 |
// we judge it problematic: we will try to adjust the |
|
65 |
// buffer sizes, and if we can't we will print a warning |
|
66 |
static final long UPPER_THRESHOLD = 20_000; // 20 sec. |
|
67 |
||
68 |
static final Random random = RandomFactory.getRandom(); |
|
69 |
static final long start = System.nanoTime(); |
|
70 |
static final String START = "start"; |
|
71 |
static final String END = "end "; |
|
72 |
static long elapsed() { return (System.nanoTime() - start)/1000_000;} |
|
73 |
static void printStamp(String what, String fmt, Object... args) { |
|
74 |
long elapsed = elapsed(); |
|
75 |
long sec = elapsed/1000; |
|
76 |
long ms = elapsed % 1000; |
|
77 |
String time = sec > 0 ? sec + "sec " : ""; |
|
78 |
time = time + ms + "ms"; |
|
79 |
out.println(what + "\t ["+time+"]\t "+ String.format(fmt,args)); |
|
80 |
} |
|
81 |
@DataProvider(name = "negatives") |
|
82 |
public Object[][] negatives() { |
|
83 |
return new Object[][] { { 0 }, { -1 }, { -1000 } }; |
|
84 |
} |
|
85 |
||
86 |
@Test(dataProvider = "negatives", expectedExceptions = IllegalArgumentException.class) |
|
87 |
public void subscriberThrowsIAE(int bufferSize) { |
|
88 |
printStamp(START, "subscriberThrowsIAE(%d)", bufferSize); |
|
89 |
try { |
|
90 |
BodySubscriber<?> bp = BodySubscriber.asByteArray(); |
|
91 |
BodySubscriber.buffering(bp, bufferSize); |
|
92 |
} finally { |
|
93 |
printStamp(END, "subscriberThrowsIAE(%d)", bufferSize); |
|
94 |
} |
|
95 |
} |
|
96 |
||
97 |
@Test(dataProvider = "negatives", expectedExceptions = IllegalArgumentException.class) |
|
98 |
public void handlerThrowsIAE(int bufferSize) { |
|
99 |
printStamp(START, "handlerThrowsIAE(%d)", bufferSize); |
|
100 |
try { |
|
101 |
BodyHandler<?> bp = BodyHandler.asByteArray(); |
|
102 |
BodyHandler.buffering(bp, bufferSize); |
|
103 |
} finally { |
|
104 |
printStamp(END, "handlerThrowsIAE(%d)", bufferSize); |
|
105 |
} |
|
106 |
} |
|
107 |
||
108 |
// --- |
|
109 |
||
110 |
@DataProvider(name = "config") |
|
111 |
public Object[][] config() { |
|
112 |
return new Object[][] { |
|
113 |
// iterations delayMillis numBuffers bufferSize maxBufferSize minBufferSize |
|
114 |
{ 1, 0, 1, 1, 2, 1 }, |
|
115 |
{ 1, 5, 1, 100, 2, 1 }, |
|
116 |
{ 1, 0, 1, 10, 1000, 1 }, |
|
117 |
{ 1, 10, 1, 10, 1000, 1 }, |
|
118 |
{ 1, 0, 1, 1000, 1000, 10 }, |
|
119 |
{ 1, 0, 10, 1000, 1000, 50 }, |
|
120 |
{ 1, 0, 1000, 10 , 1000, 50 }, |
|
121 |
{ 1, 100, 1, 1000 * 4, 1000, 50 }, |
|
122 |
{ 100, 0, 1000, 1, 2, 1 }, |
|
123 |
{ 3, 0, 4, 5006, 1000, 50 }, |
|
124 |
{ 20, 0, 100, 4888, 1000, 100 }, |
|
125 |
{ 16, 10, 1000, 50 , 1000, 100 }, |
|
126 |
{ 16, 10, 1000, 50 , 657, 657 }, |
|
127 |
}; |
|
128 |
} |
|
129 |
||
130 |
@Test(dataProvider = "config") |
|
131 |
public void test(int iterations, |
|
132 |
int delayMillis, |
|
133 |
int numBuffers, |
|
134 |
int bufferSize, |
|
135 |
int maxBufferSize, |
|
136 |
int minbufferSize) { |
|
137 |
for (long perRequestAmount : new long[] { 1L, MAX_VALUE }) |
|
138 |
test(iterations, |
|
139 |
delayMillis, |
|
140 |
numBuffers, |
|
141 |
bufferSize, |
|
142 |
maxBufferSize, |
|
143 |
minbufferSize, |
|
144 |
perRequestAmount); |
|
145 |
} |
|
146 |
||
147 |
volatile boolean onNextThrew; |
|
148 |
||
149 |
BiConsumer<Flow.Subscriber<?>, ? super Throwable> onNextThrowHandler = |
|
150 |
(sub, ex) -> { |
|
151 |
onNextThrew = true; |
|
152 |
System.out.println("onNext threw " + ex); |
|
153 |
ex.printStackTrace(); |
|
154 |
}; |
|
155 |
||
156 |
public void test(int iterations, |
|
157 |
int delayMillis, |
|
158 |
int numBuffers, |
|
159 |
int bufferSize, |
|
160 |
int maxBufferSize, |
|
161 |
int minBufferSize, |
|
162 |
long requestAmount) { |
|
163 |
ExecutorService executor = Executors.newFixedThreadPool(1); |
|
164 |
try { |
|
165 |
out.printf("Iterations %d\n", iterations); |
|
166 |
for (int i=0; i<iterations; i++ ) { |
|
167 |
printStamp(START, "Iteration %d", i); |
|
168 |
try { |
|
169 |
SubmissionPublisher<List<ByteBuffer>> publisher = |
|
170 |
new SubmissionPublisher<>(executor, |
|
171 |
1, // lock-step with the publisher, for now |
|
172 |
onNextThrowHandler); |
|
173 |
CompletableFuture<?> cf = sink(publisher, |
|
174 |
delayMillis, |
|
175 |
numBuffers * bufferSize, |
|
176 |
requestAmount, |
|
177 |
maxBufferSize, |
|
178 |
minBufferSize); |
|
179 |
source(publisher, numBuffers, bufferSize); |
|
180 |
publisher.close(); |
|
181 |
cf.join(); |
|
182 |
} finally { |
|
183 |
printStamp(END, "Iteration %d\n", i); |
|
184 |
} |
|
185 |
} |
|
186 |
||
187 |
assertFalse(onNextThrew, "Unexpected onNextThrew, check output"); |
|
188 |
||
189 |
out.println("OK"); |
|
190 |
} finally { |
|
191 |
executor.shutdown(); |
|
192 |
} |
|
193 |
} |
|
194 |
||
195 |
static long accumulatedDataSize(List<ByteBuffer> bufs) { |
|
196 |
return bufs.stream().mapToLong(ByteBuffer::remaining).sum(); |
|
197 |
} |
|
198 |
||
199 |
/** Returns a new BB with its contents set to monotonically increasing |
|
200 |
* values, staring at the given start index and wrapping every 100. */ |
|
201 |
static ByteBuffer allocateBuffer(int size, int startIdx) { |
|
202 |
ByteBuffer b = ByteBuffer.allocate(size); |
|
203 |
for (int i=0; i<size; i++) |
|
204 |
b.put((byte)((startIdx + i) % 100)); |
|
205 |
b.position(0); |
|
206 |
return b; |
|
207 |
} |
|
208 |
||
209 |
static class TestSubscriber implements BodySubscriber<Integer> { |
|
210 |
final int delayMillis; |
|
211 |
final int bufferSize; |
|
212 |
final int expectedTotalSize; |
|
213 |
final long requestAmount; |
|
214 |
final CompletableFuture<Integer> completion; |
|
215 |
final Executor delayedExecutor; |
|
216 |
volatile Flow.Subscription subscription; |
|
217 |
||
218 |
TestSubscriber(int bufferSize, |
|
219 |
int delayMillis, |
|
220 |
int expectedTotalSize, |
|
221 |
long requestAmount) { |
|
222 |
this.bufferSize = bufferSize; |
|
223 |
this.completion = new CompletableFuture<>(); |
|
224 |
this.delayMillis = delayMillis; |
|
225 |
this.delayedExecutor = delayedExecutor(delayMillis, MILLISECONDS); |
|
226 |
this.expectedTotalSize = expectedTotalSize; |
|
227 |
this.requestAmount = requestAmount; |
|
228 |
} |
|
229 |
||
230 |
/** |
|
231 |
* Example of a factory method which would decorate a buffering |
|
232 |
* subscriber to create a new subscriber dependent on buffering capability. |
|
233 |
* <p> |
|
234 |
* The integer type parameter simulates the body just by counting the |
|
235 |
* number of bytes in the body. |
|
236 |
*/ |
|
237 |
static BodySubscriber<Integer> createSubscriber(int bufferSize, |
|
238 |
int delay, |
|
239 |
int expectedTotalSize, |
|
240 |
long requestAmount) { |
|
241 |
TestSubscriber s = new TestSubscriber(bufferSize, |
|
242 |
delay, |
|
243 |
expectedTotalSize, |
|
244 |
requestAmount); |
|
245 |
return BodySubscriber.buffering(s, bufferSize); |
|
246 |
} |
|
247 |
||
248 |
private void requestMore() { |
|
249 |
subscription.request(requestAmount); |
|
250 |
} |
|
251 |
||
252 |
@Override |
|
253 |
public void onSubscribe(Subscription subscription) { |
|
254 |
assertNull(this.subscription); |
|
255 |
this.subscription = subscription; |
|
256 |
if (delayMillis > 0) |
|
257 |
delayedExecutor.execute(this::requestMore); |
|
258 |
else |
|
259 |
requestMore(); |
|
260 |
} |
|
261 |
||
262 |
volatile int wrongSizes; |
|
263 |
volatile int totalBytesReceived; |
|
264 |
volatile int onNextInvocations; |
|
265 |
volatile long lastSeenSize = -1; |
|
266 |
volatile boolean noMoreOnNext; // false |
|
267 |
volatile int index; // 0 |
|
268 |
volatile long count; |
|
269 |
||
270 |
@Override |
|
271 |
public void onNext(List<ByteBuffer> items) { |
|
272 |
try { |
|
273 |
long sz = accumulatedDataSize(items); |
|
274 |
boolean printStamp = delayMillis > 0 |
|
275 |
&& requestAmount < Long.MAX_VALUE |
|
276 |
&& count % 20 == 0; |
|
277 |
if (printStamp) { |
|
278 |
printStamp("stamp", "count=%d sz=%d accumulated=%d", |
|
279 |
count, sz, (totalBytesReceived + sz)); |
|
280 |
} |
|
281 |
count++; |
|
282 |
onNextInvocations++; |
|
283 |
assertNotEquals(sz, 0L, "Unexpected empty buffers"); |
|
284 |
items.stream().forEach(b -> assertEquals(b.position(), 0)); |
|
285 |
assertFalse(noMoreOnNext); |
|
286 |
||
287 |
if (sz != bufferSize) { |
|
288 |
String msg = sz + ", should be less than bufferSize, " + bufferSize; |
|
289 |
assertTrue(sz < bufferSize, msg); |
|
290 |
assertTrue(lastSeenSize == -1 || lastSeenSize == bufferSize); |
|
291 |
noMoreOnNext = true; |
|
292 |
wrongSizes++; |
|
293 |
printStamp("onNext", |
|
294 |
"Possibly received last buffer: sz=%d, accumulated=%d, total=%d", |
|
295 |
sz, totalBytesReceived, totalBytesReceived + sz); |
|
296 |
} else { |
|
297 |
assertEquals(sz, bufferSize, "Expected to receive exactly bufferSize"); |
|
298 |
} |
|
299 |
lastSeenSize = sz; |
|
300 |
||
301 |
// Ensure expected contents |
|
302 |
for (ByteBuffer b : items) { |
|
303 |
while (b.hasRemaining()) { |
|
304 |
assertEquals(b.get(), (byte) (index % 100)); |
|
305 |
index++; |
|
306 |
} |
|
307 |
} |
|
308 |
||
309 |
totalBytesReceived += sz; |
|
310 |
assertEquals(totalBytesReceived, index); |
|
311 |
if (delayMillis > 0 && ((expectedTotalSize - totalBytesReceived) > bufferSize)) |
|
312 |
delayedExecutor.execute(this::requestMore); |
|
313 |
else |
|
314 |
requestMore(); |
|
315 |
} catch (Throwable t) { |
|
316 |
completion.completeExceptionally(t); |
|
317 |
} |
|
318 |
} |
|
319 |
||
320 |
@Override |
|
321 |
public void onError(Throwable throwable) { |
|
322 |
completion.completeExceptionally(throwable); |
|
323 |
} |
|
324 |
||
325 |
@Override |
|
326 |
public void onComplete() { |
|
327 |
if (wrongSizes > 1) { // allow just the final item to be smaller |
|
328 |
String msg = "Wrong sizes. Expected no more than 1. [" + this + "]"; |
|
329 |
completion.completeExceptionally(new Throwable(msg)); |
|
330 |
} |
|
331 |
if (totalBytesReceived != expectedTotalSize) { |
|
332 |
String msg = "Wrong number of bytes. [" + this + "]"; |
|
333 |
completion.completeExceptionally(new Throwable(msg)); |
|
334 |
} else { |
|
335 |
completion.complete(totalBytesReceived); |
|
336 |
} |
|
337 |
} |
|
338 |
||
339 |
@Override |
|
340 |
public CompletionStage<Integer> getBody() { |
|
341 |
return completion; |
|
342 |
} |
|
343 |
||
344 |
@Override |
|
345 |
public String toString() { |
|
346 |
StringBuilder sb = new StringBuilder(); |
|
347 |
sb.append(super.toString()); |
|
348 |
sb.append(", bufferSize=").append(bufferSize); |
|
349 |
sb.append(", onNextInvocations=").append(onNextInvocations); |
|
350 |
sb.append(", totalBytesReceived=").append(totalBytesReceived); |
|
351 |
sb.append(", expectedTotalSize=").append(expectedTotalSize); |
|
352 |
sb.append(", requestAmount=").append(requestAmount); |
|
353 |
sb.append(", lastSeenSize=").append(lastSeenSize); |
|
354 |
sb.append(", wrongSizes=").append(wrongSizes); |
|
355 |
sb.append(", index=").append(index); |
|
356 |
return sb.toString(); |
|
357 |
} |
|
358 |
} |
|
359 |
||
360 |
/** |
|
361 |
* Publishes data, through the given publisher, using the main thread. |
|
362 |
* |
|
363 |
* Note: The executor supplied when creating the SubmissionPublisher provides |
|
364 |
* the threads for executing the Subscribers. |
|
365 |
* |
|
366 |
* @param publisher the publisher |
|
367 |
* @param numBuffers the number of buffers to send ( before splitting in two ) |
|
368 |
* @param bufferSize the total size of the data to send ( before splitting in two ) |
|
369 |
*/ |
|
370 |
static void source(SubmissionPublisher<List<ByteBuffer>> publisher, |
|
371 |
int numBuffers, |
|
372 |
int bufferSize) { |
|
373 |
printStamp("source","Publishing %d buffers of size %d each", numBuffers, bufferSize); |
|
374 |
int index = 0; |
|
375 |
for (int i=0; i<numBuffers; i++) { |
|
376 |
int chunkSize = random.nextInt(bufferSize); |
|
377 |
ByteBuffer buf1 = allocateBuffer(chunkSize, index); |
|
378 |
index += chunkSize; |
|
379 |
ByteBuffer buf2 = allocateBuffer(bufferSize - chunkSize, index); |
|
380 |
index += bufferSize - chunkSize; |
|
381 |
publisher.submit(List.of(buf1, buf2)); |
|
382 |
} |
|
383 |
printStamp("source", "complete"); |
|
384 |
} |
|
385 |
||
386 |
/** |
|
387 |
* Creates and subscribes Subscribers that receive data from the given |
|
388 |
* publisher. |
|
389 |
* |
|
390 |
* @param publisher the publisher |
|
391 |
* @param delayMillis time, in milliseconds, to delay the Subscription |
|
392 |
* requesting more bytes ( for simulating slow consumption ) |
|
393 |
* @param expectedTotalSize the total number of bytes expected to be received |
|
394 |
* by the subscribers |
|
395 |
* @return a CompletableFuture which completes when the subscription is complete |
|
396 |
*/ |
|
397 |
static CompletableFuture<?> sink(SubmissionPublisher<List<ByteBuffer>> publisher, |
|
398 |
int delayMillis, |
|
399 |
int expectedTotalSize, |
|
400 |
long requestAmount, |
|
401 |
int maxBufferSize, |
|
402 |
int minBufferSize) { |
|
403 |
int bufferSize = chooseBufferSize(maxBufferSize, |
|
404 |
minBufferSize, |
|
405 |
delayMillis, |
|
406 |
expectedTotalSize, |
|
407 |
requestAmount); |
|
408 |
assert bufferSize > 0; |
|
409 |
assert bufferSize >= minBufferSize; |
|
410 |
assert bufferSize <= maxBufferSize; |
|
411 |
BodySubscriber<Integer> sub = TestSubscriber.createSubscriber(bufferSize, |
|
412 |
delayMillis, |
|
413 |
expectedTotalSize, |
|
414 |
requestAmount); |
|
415 |
publisher.subscribe(sub); |
|
416 |
printStamp("sink","Subscriber reads data with buffer size: %d", bufferSize); |
|
417 |
out.printf("Subscription delay is %d msec\n", delayMillis); |
|
418 |
long delay = (((long)delayMillis * expectedTotalSize) / bufferSize) / requestAmount; |
|
419 |
out.printf("Minimum total delay is %d sec %d ms\n", delay / 1000, delay % 1000); |
|
420 |
out.printf("Request amount is %d items\n", requestAmount); |
|
421 |
return sub.getBody().toCompletableFuture(); |
|
422 |
} |
|
423 |
||
424 |
static int chooseBufferSize(int maxBufferSize, |
|
425 |
int minBufferSize, |
|
426 |
int delaysMillis, |
|
427 |
int expectedTotalSize, |
|
428 |
long requestAmount) { |
|
429 |
assert minBufferSize > 0 && maxBufferSize > 0 && requestAmount > 0; |
|
430 |
int bufferSize = maxBufferSize == minBufferSize ? maxBufferSize : |
|
431 |
(random.nextInt(maxBufferSize - minBufferSize) |
|
432 |
+ minBufferSize); |
|
433 |
if (requestAmount == Long.MAX_VALUE) return bufferSize; |
|
434 |
long minDelay = (((long)delaysMillis * expectedTotalSize) / maxBufferSize) |
|
435 |
/ requestAmount; |
|
436 |
long maxDelay = (((long)delaysMillis * expectedTotalSize) / minBufferSize) |
|
437 |
/ requestAmount; |
|
438 |
// if the maximum delay is < 10s just take a random number between min and max. |
|
439 |
if (maxDelay <= LOWER_THRESHOLD) { |
|
440 |
return bufferSize; |
|
441 |
} |
|
442 |
// if minimum delay is greater than 20s then print a warning and use max buffer. |
|
443 |
if (minDelay >= UPPER_THRESHOLD) { |
|
444 |
System.out.println("Warning: minimum delay is " |
|
445 |
+ minDelay/1000 + "sec " + minDelay%1000 + "ms"); |
|
446 |
System.err.println("Warning: minimum delay is " |
|
447 |
+ minDelay/1000 + "sec " + minDelay%1000 + "ms"); |
|
448 |
return maxBufferSize; |
|
449 |
} |
|
450 |
// maxDelay could be anything, but minDelay is below the UPPER_THRESHOLD |
|
451 |
// try to pick up a buffer size that keeps the delay below the |
|
452 |
// UPPER_THRESHOLD |
|
453 |
while (minBufferSize < maxBufferSize) { |
|
454 |
bufferSize = random.nextInt(maxBufferSize - minBufferSize) |
|
455 |
+ minBufferSize; |
|
456 |
long delay = (((long)delaysMillis * expectedTotalSize) / bufferSize) |
|
457 |
/ requestAmount; |
|
458 |
if (delay < UPPER_THRESHOLD) return bufferSize; |
|
459 |
minBufferSize++; |
|
460 |
} |
|
461 |
return minBufferSize; |
|
462 |
} |
|
463 |
||
464 |
// --- |
|
465 |
||
466 |
/* Main entry point for standalone testing of the main functional test. */ |
|
467 |
public static void main(String... args) { |
|
468 |
BufferingSubscriberTest t = new BufferingSubscriberTest(); |
|
469 |
for (Object[] objs : t.config()) |
|
470 |
t.test((int)objs[0], (int)objs[1], (int)objs[2], (int)objs[3], (int)objs[4], (int)objs[5]); |
|
471 |
} |
|
472 |
} |