author | michaelm |
Wed, 04 Jul 2018 16:16:24 +0100 | |
changeset 50985 | cd41f34e548c |
parent 50681 | 4254bed3c09d |
child 52499 | 768b1c612100 |
child 56833 | be0819373531 |
permissions | -rw-r--r-- |
48083 | 1 |
/* |
49765 | 2 |
* Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. |
48083 | 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 |
||
49765 | 26 |
package jdk.internal.net.http; |
48083 | 27 |
|
28 |
import java.io.EOFException; |
|
29 |
import java.io.IOException; |
|
30 |
import java.nio.ByteBuffer; |
|
31 |
import java.util.Arrays; |
|
32 |
import java.util.HashSet; |
|
33 |
import java.util.List; |
|
34 |
import java.util.Set; |
|
35 |
import java.util.concurrent.ConcurrentLinkedDeque; |
|
36 |
import java.util.concurrent.Executor; |
|
37 |
import java.util.concurrent.Flow; |
|
38 |
import java.util.concurrent.atomic.AtomicBoolean; |
|
39 |
import java.util.concurrent.atomic.AtomicLong; |
|
40 |
import java.util.concurrent.atomic.AtomicReference; |
|
49765 | 41 |
import java.util.function.Consumer; |
42 |
import jdk.internal.net.http.common.Demand; |
|
43 |
import jdk.internal.net.http.common.FlowTube.TubeSubscriber; |
|
50681 | 44 |
import jdk.internal.net.http.common.Log; |
49765 | 45 |
import jdk.internal.net.http.common.Logger; |
50681 | 46 |
import jdk.internal.net.http.common.MinimalFuture; |
49765 | 47 |
import jdk.internal.net.http.common.SequentialScheduler; |
48 |
import jdk.internal.net.http.common.ConnectionExpiredException; |
|
49 |
import jdk.internal.net.http.common.Utils; |
|
48083 | 50 |
|
51 |
||
52 |
/** |
|
53 |
* A helper class that will queue up incoming data until the receiving |
|
54 |
* side is ready to handle it. |
|
55 |
*/ |
|
56 |
class Http1AsyncReceiver { |
|
57 |
||
49765 | 58 |
final Logger debug = Utils.getDebugLogger(this::dbgString, Utils.DEBUG); |
48083 | 59 |
|
60 |
/** |
|
61 |
* A delegate that can asynchronously receive data from an upstream flow, |
|
62 |
* parse, it, then possibly transform it and either store it (response |
|
63 |
* headers) or possibly pass it to a downstream subscriber (response body). |
|
64 |
* Usually, there will be one Http1AsyncDelegate in charge of receiving |
|
65 |
* and parsing headers, and another one in charge of receiving, parsing, |
|
66 |
* and forwarding body. Each will sequentially subscribe with the |
|
67 |
* Http1AsyncReceiver in turn. There may be additional delegates which |
|
68 |
* subscribe to the Http1AsyncReceiver, mainly for the purpose of handling |
|
69 |
* errors while the connection is busy transmitting the request body and the |
|
70 |
* Http1Exchange::readBody method hasn't been called yet, and response |
|
71 |
* delegates haven't subscribed yet. |
|
72 |
*/ |
|
73 |
static interface Http1AsyncDelegate { |
|
74 |
/** |
|
75 |
* Receives and handles a byte buffer reference. |
|
76 |
* @param ref A byte buffer reference coming from upstream. |
|
77 |
* @return false, if the byte buffer reference should be kept in the queue. |
|
78 |
* Usually, this means that either the byte buffer reference |
|
79 |
* was handled and parsing is finished, or that the receiver |
|
80 |
* didn't handle the byte reference at all. |
|
81 |
* There may or may not be any remaining data in the |
|
82 |
* byte buffer, and the byte buffer reference must not have |
|
83 |
* been cleared. |
|
84 |
* true, if the byte buffer reference was fully read and |
|
85 |
* more data can be received. |
|
86 |
*/ |
|
87 |
public boolean tryAsyncReceive(ByteBuffer ref); |
|
88 |
||
89 |
/** |
|
90 |
* Called when an exception is raised. |
|
91 |
* @param ex The raised Throwable. |
|
92 |
*/ |
|
93 |
public void onReadError(Throwable ex); |
|
94 |
||
95 |
/** |
|
96 |
* Must be called before any other method on the delegate. |
|
97 |
* The subscription can be either used directly by the delegate |
|
98 |
* to request more data (e.g. if the delegate is a header parser), |
|
99 |
* or can be forwarded to a downstream subscriber (if the delegate |
|
100 |
* is a body parser that wraps a response BodySubscriber). |
|
101 |
* In all cases, it is the responsibility of the delegate to ensure |
|
102 |
* that request(n) and demand.tryDecrement() are called appropriately. |
|
103 |
* No data will be sent to {@code tryAsyncReceive} unless |
|
104 |
* the subscription has some demand. |
|
105 |
* |
|
106 |
* @param s A subscription that allows the delegate to control the |
|
107 |
* data flow. |
|
108 |
*/ |
|
109 |
public void onSubscribe(AbstractSubscription s); |
|
110 |
||
111 |
/** |
|
112 |
* Returns the subscription that was passed to {@code onSubscribe} |
|
113 |
* @return the subscription that was passed to {@code onSubscribe}.. |
|
114 |
*/ |
|
115 |
public AbstractSubscription subscription(); |
|
116 |
||
49765 | 117 |
/** |
118 |
* Called to make sure resources are released when the |
|
119 |
* when the Http1AsyncReceiver is stopped. |
|
120 |
* @param error The Http1AsyncReceiver pending error ref, |
|
121 |
* if any. |
|
122 |
*/ |
|
123 |
public void close(Throwable error); |
|
124 |
||
48083 | 125 |
} |
126 |
||
127 |
/** |
|
128 |
* A simple subclass of AbstractSubscription that ensures the |
|
129 |
* SequentialScheduler will be run when request() is called and demand |
|
130 |
* becomes positive again. |
|
131 |
*/ |
|
132 |
private static final class Http1AsyncDelegateSubscription |
|
133 |
extends AbstractSubscription |
|
134 |
{ |
|
135 |
private final Runnable onCancel; |
|
49765 | 136 |
private final Consumer<Throwable> onError; |
48083 | 137 |
private final SequentialScheduler scheduler; |
49765 | 138 |
private volatile boolean cancelled; |
48083 | 139 |
Http1AsyncDelegateSubscription(SequentialScheduler scheduler, |
49765 | 140 |
Runnable onCancel, |
141 |
Consumer<Throwable> onError) { |
|
48083 | 142 |
this.scheduler = scheduler; |
143 |
this.onCancel = onCancel; |
|
49765 | 144 |
this.onError = onError; |
48083 | 145 |
} |
146 |
@Override |
|
147 |
public void request(long n) { |
|
49765 | 148 |
if (cancelled) return; |
149 |
try { |
|
150 |
final Demand demand = demand(); |
|
151 |
if (demand.increase(n)) { |
|
152 |
scheduler.runOrSchedule(); |
|
153 |
} |
|
154 |
} catch (IllegalArgumentException x) { |
|
155 |
cancelled = true; |
|
156 |
onError.accept(x); |
|
48083 | 157 |
} |
158 |
} |
|
159 |
@Override |
|
49765 | 160 |
public void cancel() { |
161 |
cancelled = true; |
|
162 |
onCancel.run(); |
|
163 |
} |
|
48083 | 164 |
} |
165 |
||
166 |
private final ConcurrentLinkedDeque<ByteBuffer> queue |
|
167 |
= new ConcurrentLinkedDeque<>(); |
|
168 |
private final SequentialScheduler scheduler = |
|
169 |
SequentialScheduler.synchronizedScheduler(this::flush); |
|
50681 | 170 |
final MinimalFuture<Void> whenFinished; |
48083 | 171 |
private final Executor executor; |
172 |
private final Http1TubeSubscriber subscriber = new Http1TubeSubscriber(); |
|
173 |
private final AtomicReference<Http1AsyncDelegate> pendingDelegateRef; |
|
174 |
private final AtomicLong received = new AtomicLong(); |
|
175 |
final AtomicBoolean canRequestMore = new AtomicBoolean(); |
|
176 |
||
177 |
private volatile Throwable error; |
|
178 |
private volatile Http1AsyncDelegate delegate; |
|
179 |
// This reference is only used to prevent early GC of the exchange. |
|
180 |
private volatile Http1Exchange<?> owner; |
|
181 |
// Only used for checking whether we run on the selector manager thread. |
|
182 |
private final HttpClientImpl client; |
|
183 |
private boolean retry; |
|
49765 | 184 |
private volatile boolean stopRequested; |
48083 | 185 |
|
186 |
public Http1AsyncReceiver(Executor executor, Http1Exchange<?> owner) { |
|
187 |
this.pendingDelegateRef = new AtomicReference<>(); |
|
188 |
this.executor = executor; |
|
50681 | 189 |
this.whenFinished = new MinimalFuture<>(); |
48083 | 190 |
this.owner = owner; |
191 |
this.client = owner.client; |
|
192 |
} |
|
193 |
||
194 |
// This is the main loop called by the SequentialScheduler. |
|
195 |
// It attempts to empty the queue until the scheduler is stopped, |
|
196 |
// or the delegate is unregistered, or the delegate is unable to |
|
197 |
// process the data (because it's not ready or already done), which |
|
198 |
// it signals by returning 'true'; |
|
199 |
private void flush() { |
|
200 |
ByteBuffer buf; |
|
201 |
try { |
|
202 |
assert !client.isSelectorThread() : |
|
203 |
"Http1AsyncReceiver::flush should not run in the selector: " |
|
204 |
+ Thread.currentThread().getName(); |
|
205 |
||
206 |
// First check whether we have a pending delegate that has |
|
207 |
// just subscribed, and if so, create a Subscription for it |
|
208 |
// and call onSubscribe. |
|
209 |
handlePendingDelegate(); |
|
210 |
||
211 |
// Then start emptying the queue, if possible. |
|
49765 | 212 |
while ((buf = queue.peek()) != null && !stopRequested) { |
48083 | 213 |
Http1AsyncDelegate delegate = this.delegate; |
49765 | 214 |
if (debug.on()) |
215 |
debug.log("Got %s bytes for delegate %s", |
|
216 |
buf.remaining(), delegate); |
|
48083 | 217 |
if (!hasDemand(delegate)) { |
218 |
// The scheduler will be invoked again later when the demand |
|
219 |
// becomes positive. |
|
220 |
return; |
|
221 |
} |
|
222 |
||
223 |
assert delegate != null; |
|
49765 | 224 |
if (debug.on()) |
225 |
debug.log("Forwarding %s bytes to delegate %s", |
|
226 |
buf.remaining(), delegate); |
|
48083 | 227 |
// The delegate has demand: feed it the next buffer. |
228 |
if (!delegate.tryAsyncReceive(buf)) { |
|
229 |
final long remaining = buf.remaining(); |
|
49765 | 230 |
if (debug.on()) debug.log(() -> { |
48083 | 231 |
// If the scheduler is stopped, the queue may already |
232 |
// be empty and the reference may already be released. |
|
233 |
String remstr = scheduler.isStopped() ? "" : |
|
234 |
" remaining in ref: " |
|
235 |
+ remaining; |
|
49765 | 236 |
remstr += remstr |
48083 | 237 |
+ " total remaining: " + remaining(); |
238 |
return "Delegate done: " + remaining; |
|
239 |
}); |
|
240 |
canRequestMore.set(false); |
|
241 |
// The last buffer parsed may have remaining unparsed bytes. |
|
242 |
// Don't take it out of the queue. |
|
243 |
return; // done. |
|
244 |
} |
|
245 |
||
246 |
// removed parsed buffer from queue, and continue with next |
|
247 |
// if available |
|
248 |
ByteBuffer parsed = queue.remove(); |
|
49765 | 249 |
canRequestMore.set(queue.isEmpty() && !stopRequested); |
48083 | 250 |
assert parsed == buf; |
251 |
} |
|
252 |
||
253 |
// queue is empty: let's see if we should request more |
|
254 |
checkRequestMore(); |
|
255 |
||
256 |
} catch (Throwable t) { |
|
257 |
Throwable x = error; |
|
258 |
if (x == null) error = t; // will be handled in the finally block |
|
49765 | 259 |
if (debug.on()) debug.log("Unexpected error caught in flush()", t); |
48083 | 260 |
} finally { |
261 |
// Handles any pending error. |
|
262 |
// The most recently subscribed delegate will get the error. |
|
263 |
checkForErrors(); |
|
264 |
} |
|
265 |
} |
|
266 |
||
50681 | 267 |
private String describe() { |
268 |
Http1Exchange<?> exchange = owner; |
|
269 |
if (exchange != null) { |
|
270 |
return String.valueOf(exchange.request()); |
|
271 |
} |
|
272 |
return "<uri unavailable>"; |
|
273 |
} |
|
274 |
||
48083 | 275 |
/** |
276 |
* Must be called from within the scheduler main loop. |
|
277 |
* Handles any pending errors by calling delegate.onReadError(). |
|
278 |
* If the error can be forwarded to the delegate, stops the scheduler. |
|
279 |
*/ |
|
280 |
private void checkForErrors() { |
|
281 |
// Handles any pending error. |
|
282 |
// The most recently subscribed delegate will get the error. |
|
283 |
// If the delegate is null, the error will be handled by the next |
|
284 |
// delegate that subscribes. |
|
285 |
// If the queue is not empty, wait until it it is empty before |
|
286 |
// handling the error. |
|
287 |
Http1AsyncDelegate delegate = pendingDelegateRef.get(); |
|
288 |
if (delegate == null) delegate = this.delegate; |
|
289 |
Throwable x = error; |
|
49765 | 290 |
if (delegate != null && x != null && (stopRequested || queue.isEmpty())) { |
48083 | 291 |
// forward error only after emptying the queue. |
292 |
final Object captured = delegate; |
|
49765 | 293 |
if (debug.on()) |
294 |
debug.log(() -> "flushing " + x + "\n\t delegate: " + captured |
|
295 |
+ "\t\t queue.isEmpty: " + queue.isEmpty()); |
|
48083 | 296 |
scheduler.stop(); |
297 |
delegate.onReadError(x); |
|
50681 | 298 |
whenFinished.completeExceptionally(x); |
299 |
if (Log.channel()) { |
|
300 |
Log.logChannel("HTTP/1 read subscriber stopped for: {0}", describe()); |
|
301 |
} |
|
49765 | 302 |
if (stopRequested) { |
303 |
// This is the special case where the subscriber |
|
304 |
// has requested an illegal number of items. |
|
305 |
// In this case, the error doesn't come from |
|
306 |
// upstream, but from downstream, and we need to |
|
307 |
// close the upstream connection. |
|
308 |
Http1Exchange<?> exchg = owner; |
|
309 |
stop(); |
|
310 |
if (exchg != null) exchg.connection().close(); |
|
311 |
} |
|
48083 | 312 |
} |
313 |
} |
|
314 |
||
315 |
/** |
|
316 |
* Must be called from within the scheduler main loop. |
|
317 |
* Figure out whether more data should be requested from the |
|
318 |
* Http1TubeSubscriber. |
|
319 |
*/ |
|
320 |
private void checkRequestMore() { |
|
321 |
Http1AsyncDelegate delegate = this.delegate; |
|
322 |
boolean more = this.canRequestMore.get(); |
|
323 |
boolean hasDemand = hasDemand(delegate); |
|
49765 | 324 |
if (debug.on()) |
325 |
debug.log("checkRequestMore: " + "canRequestMore=" + more |
|
326 |
+ ", hasDemand=" + hasDemand |
|
327 |
+ (delegate == null ? ", delegate=null" : "")); |
|
48083 | 328 |
if (hasDemand) { |
329 |
subscriber.requestMore(); |
|
330 |
} |
|
331 |
} |
|
332 |
||
333 |
/** |
|
334 |
* Must be called from within the scheduler main loop. |
|
335 |
* Return true if the delegate is not null and has some demand. |
|
336 |
* @param delegate The Http1AsyncDelegate delegate |
|
337 |
* @return true if the delegate is not null and has some demand |
|
338 |
*/ |
|
339 |
private boolean hasDemand(Http1AsyncDelegate delegate) { |
|
340 |
if (delegate == null) return false; |
|
341 |
AbstractSubscription subscription = delegate.subscription(); |
|
342 |
long demand = subscription.demand().get(); |
|
49765 | 343 |
if (debug.on()) |
344 |
debug.log("downstream subscription demand is %s", demand); |
|
48083 | 345 |
return demand > 0; |
346 |
} |
|
347 |
||
348 |
/** |
|
349 |
* Must be called from within the scheduler main loop. |
|
350 |
* Handles pending delegate subscription. |
|
351 |
* Return true if there was some pending delegate subscription and a new |
|
352 |
* delegate was subscribed, false otherwise. |
|
353 |
* |
|
354 |
* @return true if there was some pending delegate subscription and a new |
|
355 |
* delegate was subscribed, false otherwise. |
|
356 |
*/ |
|
357 |
private boolean handlePendingDelegate() { |
|
358 |
Http1AsyncDelegate pending = pendingDelegateRef.get(); |
|
359 |
if (pending != null && pendingDelegateRef.compareAndSet(pending, null)) { |
|
360 |
Http1AsyncDelegate delegate = this.delegate; |
|
361 |
if (delegate != null) unsubscribe(delegate); |
|
49765 | 362 |
Consumer<Throwable> onSubscriptionError = (x) -> { |
363 |
setRetryOnError(false); |
|
364 |
stopRequested = true; |
|
365 |
onReadError(x); |
|
366 |
}; |
|
48083 | 367 |
Runnable cancel = () -> { |
49765 | 368 |
if (debug.on()) |
369 |
debug.log("Downstream subscription cancelled by %s", pending); |
|
48083 | 370 |
// The connection should be closed, as some data may |
371 |
// be left over in the stream. |
|
372 |
try { |
|
373 |
setRetryOnError(false); |
|
49944 | 374 |
pending.close(null); |
48083 | 375 |
onReadError(new IOException("subscription cancelled")); |
376 |
unsubscribe(pending); |
|
377 |
} finally { |
|
378 |
Http1Exchange<?> exchg = owner; |
|
379 |
stop(); |
|
380 |
if (exchg != null) exchg.connection().close(); |
|
381 |
} |
|
382 |
}; |
|
383 |
// The subscription created by a delegate is only loosely |
|
384 |
// coupled with the upstream subscription. This is partly because |
|
385 |
// the header/body parser work with a flow of ByteBuffer, whereas |
|
386 |
// we have a flow List<ByteBuffer> upstream. |
|
387 |
Http1AsyncDelegateSubscription subscription = |
|
49765 | 388 |
new Http1AsyncDelegateSubscription(scheduler, cancel, onSubscriptionError); |
50985
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
389 |
try { |
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
390 |
pending.onSubscribe(subscription); |
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
391 |
} finally { |
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
392 |
this.delegate = delegate = pending; |
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
393 |
} |
48083 | 394 |
final Object captured = delegate; |
49765 | 395 |
if (debug.on()) |
396 |
debug.log("delegate is now " + captured |
|
397 |
+ ", demand=" + subscription.demand().get() |
|
398 |
+ ", canRequestMore=" + canRequestMore.get() |
|
399 |
+ ", queue.isEmpty=" + queue.isEmpty()); |
|
48083 | 400 |
return true; |
401 |
} |
|
402 |
return false; |
|
403 |
} |
|
404 |
||
405 |
synchronized void setRetryOnError(boolean retry) { |
|
406 |
this.retry = retry; |
|
407 |
} |
|
408 |
||
409 |
void clear() { |
|
49765 | 410 |
if (debug.on()) debug.log("cleared"); |
48083 | 411 |
this.pendingDelegateRef.set(null); |
412 |
this.delegate = null; |
|
413 |
this.owner = null; |
|
414 |
} |
|
415 |
||
416 |
void subscribe(Http1AsyncDelegate delegate) { |
|
417 |
synchronized(this) { |
|
418 |
pendingDelegateRef.set(delegate); |
|
419 |
} |
|
420 |
if (queue.isEmpty()) { |
|
421 |
canRequestMore.set(true); |
|
422 |
} |
|
49765 | 423 |
if (debug.on()) |
424 |
debug.log("Subscribed pending " + delegate + " queue.isEmpty: " |
|
425 |
+ queue.isEmpty()); |
|
48083 | 426 |
// Everything may have been received already. Make sure |
427 |
// we parse it. |
|
428 |
if (client.isSelectorThread()) { |
|
49765 | 429 |
scheduler.runOrSchedule(executor); |
48083 | 430 |
} else { |
431 |
scheduler.runOrSchedule(); |
|
432 |
} |
|
433 |
} |
|
434 |
||
435 |
// Used for debugging only! |
|
436 |
long remaining() { |
|
437 |
return Utils.remaining(queue.toArray(Utils.EMPTY_BB_ARRAY)); |
|
438 |
} |
|
439 |
||
440 |
void unsubscribe(Http1AsyncDelegate delegate) { |
|
441 |
synchronized(this) { |
|
442 |
if (this.delegate == delegate) { |
|
49765 | 443 |
if (debug.on()) debug.log("Unsubscribed %s", delegate); |
48083 | 444 |
this.delegate = null; |
445 |
} |
|
446 |
} |
|
447 |
} |
|
448 |
||
449 |
// Callback: Consumer of ByteBuffer |
|
450 |
private void asyncReceive(ByteBuffer buf) { |
|
49765 | 451 |
if (debug.on()) |
452 |
debug.log("Putting %s bytes into the queue", buf.remaining()); |
|
48083 | 453 |
received.addAndGet(buf.remaining()); |
454 |
queue.offer(buf); |
|
455 |
||
456 |
// This callback is called from within the selector thread. |
|
457 |
// Use an executor here to avoid doing the heavy lifting in the |
|
458 |
// selector. |
|
49765 | 459 |
scheduler.runOrSchedule(executor); |
48083 | 460 |
} |
461 |
||
462 |
// Callback: Consumer of Throwable |
|
463 |
void onReadError(Throwable ex) { |
|
464 |
Http1AsyncDelegate delegate; |
|
465 |
Throwable recorded; |
|
49765 | 466 |
if (debug.on()) debug.log("onError: %s", (Object) ex); |
48083 | 467 |
synchronized (this) { |
468 |
delegate = this.delegate; |
|
469 |
recorded = error; |
|
470 |
if (recorded == null) { |
|
471 |
// retry is set to true by HttpExchange when the connection is |
|
472 |
// already connected, which means it's been retrieved from |
|
473 |
// the pool. |
|
474 |
if (retry && (ex instanceof IOException)) { |
|
475 |
// could be either EOFException, or |
|
476 |
// IOException("connection reset by peer), or |
|
477 |
// SSLHandshakeException resulting from the server having |
|
478 |
// closed the SSL session. |
|
479 |
if (received.get() == 0) { |
|
480 |
// If we receive such an exception before having |
|
481 |
// received any byte, then in this case, we will |
|
482 |
// throw ConnectionExpiredException |
|
483 |
// to try & force a retry of the request. |
|
484 |
retry = false; |
|
50681 | 485 |
ex = new ConnectionExpiredException(ex); |
48083 | 486 |
} |
487 |
} |
|
488 |
error = ex; |
|
489 |
} |
|
50681 | 490 |
} |
50985
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
491 |
|
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
492 |
final Throwable t = (recorded == null ? ex : recorded); |
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
493 |
if (debug.on()) |
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
494 |
debug.log("recorded " + t + "\n\t delegate: " + delegate |
cd41f34e548c
8206001: Enable TLS1.3 by default in Http Client
michaelm
parents:
50681
diff
changeset
|
495 |
+ "\t\t queue.isEmpty: " + queue.isEmpty(), ex); |
50681 | 496 |
if (Log.errors()) { |
497 |
Log.logError("HTTP/1 read subscriber recorded error: {0} - {1}", describe(), t); |
|
48083 | 498 |
} |
49765 | 499 |
if (queue.isEmpty() || pendingDelegateRef.get() != null || stopRequested) { |
48083 | 500 |
// This callback is called from within the selector thread. |
501 |
// Use an executor here to avoid doing the heavy lifting in the |
|
502 |
// selector. |
|
50681 | 503 |
if (Log.errors()) { |
504 |
Log.logError("HTTP/1 propagating recorded error: {0} - {1}", describe(), t); |
|
505 |
} |
|
49765 | 506 |
scheduler.runOrSchedule(executor); |
48083 | 507 |
} |
508 |
} |
|
509 |
||
510 |
void stop() { |
|
49765 | 511 |
if (debug.on()) debug.log("stopping"); |
50681 | 512 |
if (Log.channel() && !scheduler.isStopped()) { |
513 |
Log.logChannel("HTTP/1 read subscriber stopped for {0}", describe()); |
|
514 |
} |
|
48083 | 515 |
scheduler.stop(); |
49765 | 516 |
// make sure ref count is handled properly by |
517 |
// closing the delegate. |
|
518 |
Http1AsyncDelegate previous = delegate; |
|
519 |
if (previous != null) previous.close(error); |
|
48083 | 520 |
delegate = null; |
521 |
owner = null; |
|
50681 | 522 |
whenFinished.complete(null); |
48083 | 523 |
} |
524 |
||
525 |
/** |
|
526 |
* Returns the TubeSubscriber for reading from the connection flow. |
|
527 |
* @return the TubeSubscriber for reading from the connection flow. |
|
528 |
*/ |
|
529 |
TubeSubscriber subscriber() { |
|
530 |
return subscriber; |
|
531 |
} |
|
532 |
||
533 |
/** |
|
534 |
* A simple tube subscriber for reading from the connection flow. |
|
535 |
*/ |
|
536 |
final class Http1TubeSubscriber implements TubeSubscriber { |
|
537 |
volatile Flow.Subscription subscription; |
|
538 |
volatile boolean completed; |
|
539 |
volatile boolean dropped; |
|
540 |
||
541 |
public void onSubscribe(Flow.Subscription subscription) { |
|
542 |
// supports being called multiple time. |
|
543 |
// doesn't cancel the previous subscription, since that is |
|
544 |
// most probably the same as the new subscription. |
|
50681 | 545 |
if (debug.on()) debug.log("Received onSubscribed from upstream"); |
546 |
if (Log.channel()) { |
|
547 |
Log.logChannel("HTTP/1 read subscriber got subscription from {0}", describe()); |
|
548 |
} |
|
48083 | 549 |
assert this.subscription == null || dropped == false; |
550 |
this.subscription = subscription; |
|
551 |
dropped = false; |
|
552 |
canRequestMore.set(true); |
|
553 |
if (delegate != null) { |
|
49765 | 554 |
scheduler.runOrSchedule(executor); |
50681 | 555 |
} else { |
556 |
if (debug.on()) debug.log("onSubscribe: read delegate not present yet"); |
|
48083 | 557 |
} |
558 |
} |
|
559 |
||
560 |
void requestMore() { |
|
561 |
Flow.Subscription s = subscription; |
|
562 |
if (s == null) return; |
|
563 |
if (canRequestMore.compareAndSet(true, false)) { |
|
564 |
if (!completed && !dropped) { |
|
49765 | 565 |
if (debug.on()) |
566 |
debug.log("Http1TubeSubscriber: requesting one more from upstream"); |
|
48083 | 567 |
s.request(1); |
568 |
return; |
|
569 |
} |
|
570 |
} |
|
49765 | 571 |
if (debug.on()) |
572 |
debug.log("Http1TubeSubscriber: no need to request more"); |
|
48083 | 573 |
} |
574 |
||
575 |
@Override |
|
576 |
public void onNext(List<ByteBuffer> item) { |
|
577 |
canRequestMore.set(item.isEmpty()); |
|
578 |
for (ByteBuffer buffer : item) { |
|
579 |
asyncReceive(buffer); |
|
580 |
} |
|
581 |
} |
|
582 |
||
583 |
@Override |
|
584 |
public void onError(Throwable throwable) { |
|
585 |
onReadError(throwable); |
|
586 |
completed = true; |
|
587 |
} |
|
588 |
||
589 |
@Override |
|
590 |
public void onComplete() { |
|
591 |
onReadError(new EOFException("EOF reached while reading")); |
|
592 |
completed = true; |
|
593 |
} |
|
594 |
||
595 |
public void dropSubscription() { |
|
49765 | 596 |
if (debug.on()) debug.log("Http1TubeSubscriber: dropSubscription"); |
48083 | 597 |
// we could probably set subscription to null here... |
598 |
// then we might not need the 'dropped' boolean? |
|
599 |
dropped = true; |
|
600 |
} |
|
601 |
||
602 |
} |
|
603 |
||
604 |
// Drains the content of the queue into a single ByteBuffer. |
|
605 |
// The scheduler must be permanently stopped before calling drain(). |
|
606 |
ByteBuffer drain(ByteBuffer initial) { |
|
607 |
// Revisit: need to clean that up. |
|
608 |
// |
|
609 |
ByteBuffer b = initial = (initial == null ? Utils.EMPTY_BYTEBUFFER : initial); |
|
610 |
assert scheduler.isStopped(); |
|
611 |
||
612 |
if (queue.isEmpty()) return b; |
|
613 |
||
614 |
// sanity check: we shouldn't have queued the same |
|
615 |
// buffer twice. |
|
616 |
ByteBuffer[] qbb = queue.toArray(new ByteBuffer[queue.size()]); |
|
49765 | 617 |
|
618 |
// the assertion looks suspicious, more investigation needed |
|
619 |
// |
|
620 |
// assert java.util.stream.Stream.of(qbb) |
|
621 |
// .collect(Collectors.toSet()) |
|
622 |
// .size() == qbb.length : debugQBB(qbb); |
|
48083 | 623 |
|
624 |
// compute the number of bytes in the queue, the number of bytes |
|
625 |
// in the initial buffer |
|
626 |
// TODO: will need revisiting - as it is not guaranteed that all |
|
627 |
// data will fit in single BB! |
|
628 |
int size = Utils.remaining(qbb, Integer.MAX_VALUE); |
|
629 |
int remaining = b.remaining(); |
|
630 |
int free = b.capacity() - b.position() - remaining; |
|
49765 | 631 |
if (debug.on()) |
632 |
debug.log("Flushing %s bytes from queue into initial buffer " |
|
633 |
+ "(remaining=%s, free=%s)", size, remaining, free); |
|
48083 | 634 |
|
635 |
// check whether the initial buffer has enough space |
|
636 |
if (size > free) { |
|
49765 | 637 |
if (debug.on()) |
638 |
debug.log("Allocating new buffer for initial: %s", (size + remaining)); |
|
48083 | 639 |
// allocates a new buffer and copy initial to it |
640 |
b = ByteBuffer.allocate(size + remaining); |
|
641 |
Utils.copy(initial, b); |
|
642 |
assert b.position() == remaining; |
|
643 |
b.flip(); |
|
644 |
assert b.position() == 0; |
|
645 |
assert b.limit() == remaining; |
|
646 |
assert b.remaining() == remaining; |
|
647 |
} |
|
648 |
||
649 |
// store position and limit |
|
650 |
int pos = b.position(); |
|
651 |
int limit = b.limit(); |
|
652 |
assert limit - pos == remaining; |
|
653 |
assert b.capacity() >= remaining + size |
|
654 |
: "capacity: " + b.capacity() |
|
655 |
+ ", remaining: " + b.remaining() |
|
656 |
+ ", size: " + size; |
|
657 |
||
658 |
// prepare to copy the content of the queue |
|
659 |
b.position(limit); |
|
660 |
b.limit(pos + remaining + size); |
|
661 |
assert b.remaining() >= size : |
|
662 |
"remaining: " + b.remaining() + ", size: " + size; |
|
663 |
||
664 |
// copy the content of the queue |
|
665 |
int count = 0; |
|
666 |
for (int i=0; i<qbb.length; i++) { |
|
667 |
ByteBuffer b2 = qbb[i]; |
|
668 |
int r = b2.remaining(); |
|
669 |
assert b.remaining() >= r : "need at least " + r + " only " |
|
670 |
+ b.remaining() + " available"; |
|
671 |
int copied = Utils.copy(b2, b); |
|
672 |
assert copied == r : "copied="+copied+" available="+r; |
|
673 |
assert b2.remaining() == 0; |
|
674 |
count += copied; |
|
675 |
} |
|
676 |
assert count == size; |
|
677 |
assert b.position() == pos + remaining + size : |
|
678 |
"b.position="+b.position()+" != "+pos+"+"+remaining+"+"+size; |
|
679 |
||
680 |
// reset limit and position |
|
681 |
b.limit(limit+size); |
|
682 |
b.position(pos); |
|
683 |
||
684 |
// we can clear the refs |
|
685 |
queue.clear(); |
|
686 |
final ByteBuffer bb = b; |
|
49765 | 687 |
if (debug.on()) |
688 |
debug.log("Initial buffer now has " + bb.remaining() |
|
689 |
+ " pos=" + bb.position() + " limit=" + bb.limit()); |
|
48083 | 690 |
|
691 |
return b; |
|
692 |
} |
|
693 |
||
694 |
private String debugQBB(ByteBuffer[] qbb) { |
|
695 |
StringBuilder msg = new StringBuilder(); |
|
696 |
List<ByteBuffer> lbb = Arrays.asList(qbb); |
|
697 |
Set<ByteBuffer> sbb = new HashSet<>(Arrays.asList(qbb)); |
|
698 |
||
699 |
int uniquebb = sbb.size(); |
|
700 |
msg.append("qbb: ").append(lbb.size()) |
|
701 |
.append(" (unique: ").append(uniquebb).append("), ") |
|
702 |
.append("duplicates: "); |
|
703 |
String sep = ""; |
|
704 |
for (ByteBuffer b : lbb) { |
|
705 |
if (!sbb.remove(b)) { |
|
706 |
msg.append(sep) |
|
707 |
.append(String.valueOf(b)) |
|
708 |
.append("[remaining=") |
|
709 |
.append(b.remaining()) |
|
710 |
.append(", position=") |
|
711 |
.append(b.position()) |
|
712 |
.append(", capacity=") |
|
713 |
.append(b.capacity()) |
|
714 |
.append("]"); |
|
715 |
sep = ", "; |
|
716 |
} |
|
717 |
} |
|
718 |
return msg.toString(); |
|
719 |
} |
|
720 |
||
721 |
volatile String dbgTag; |
|
722 |
String dbgString() { |
|
723 |
String tag = dbgTag; |
|
724 |
if (tag == null) { |
|
725 |
String flowTag = null; |
|
726 |
Http1Exchange<?> exchg = owner; |
|
727 |
Object flow = (exchg != null) |
|
728 |
? exchg.connection().getConnectionFlow() |
|
729 |
: null; |
|
730 |
flowTag = tag = flow == null ? null: (String.valueOf(flow)); |
|
731 |
if (flowTag != null) { |
|
49765 | 732 |
dbgTag = tag = "Http1AsyncReceiver("+ flowTag + ")"; |
48083 | 733 |
} else { |
49765 | 734 |
tag = "Http1AsyncReceiver(?)"; |
48083 | 735 |
} |
736 |
} |
|
737 |
return tag; |
|
738 |
} |
|
739 |
} |