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);
|
48083
|
389 |
pending.onSubscribe(subscription);
|
|
390 |
this.delegate = delegate = pending;
|
|
391 |
final Object captured = delegate;
|
49765
|
392 |
if (debug.on())
|
|
393 |
debug.log("delegate is now " + captured
|
|
394 |
+ ", demand=" + subscription.demand().get()
|
|
395 |
+ ", canRequestMore=" + canRequestMore.get()
|
|
396 |
+ ", queue.isEmpty=" + queue.isEmpty());
|
48083
|
397 |
return true;
|
|
398 |
}
|
|
399 |
return false;
|
|
400 |
}
|
|
401 |
|
|
402 |
synchronized void setRetryOnError(boolean retry) {
|
|
403 |
this.retry = retry;
|
|
404 |
}
|
|
405 |
|
|
406 |
void clear() {
|
49765
|
407 |
if (debug.on()) debug.log("cleared");
|
48083
|
408 |
this.pendingDelegateRef.set(null);
|
|
409 |
this.delegate = null;
|
|
410 |
this.owner = null;
|
|
411 |
}
|
|
412 |
|
|
413 |
void subscribe(Http1AsyncDelegate delegate) {
|
|
414 |
synchronized(this) {
|
|
415 |
pendingDelegateRef.set(delegate);
|
|
416 |
}
|
|
417 |
if (queue.isEmpty()) {
|
|
418 |
canRequestMore.set(true);
|
|
419 |
}
|
49765
|
420 |
if (debug.on())
|
|
421 |
debug.log("Subscribed pending " + delegate + " queue.isEmpty: "
|
|
422 |
+ queue.isEmpty());
|
48083
|
423 |
// Everything may have been received already. Make sure
|
|
424 |
// we parse it.
|
|
425 |
if (client.isSelectorThread()) {
|
49765
|
426 |
scheduler.runOrSchedule(executor);
|
48083
|
427 |
} else {
|
|
428 |
scheduler.runOrSchedule();
|
|
429 |
}
|
|
430 |
}
|
|
431 |
|
|
432 |
// Used for debugging only!
|
|
433 |
long remaining() {
|
|
434 |
return Utils.remaining(queue.toArray(Utils.EMPTY_BB_ARRAY));
|
|
435 |
}
|
|
436 |
|
|
437 |
void unsubscribe(Http1AsyncDelegate delegate) {
|
|
438 |
synchronized(this) {
|
|
439 |
if (this.delegate == delegate) {
|
49765
|
440 |
if (debug.on()) debug.log("Unsubscribed %s", delegate);
|
48083
|
441 |
this.delegate = null;
|
|
442 |
}
|
|
443 |
}
|
|
444 |
}
|
|
445 |
|
|
446 |
// Callback: Consumer of ByteBuffer
|
|
447 |
private void asyncReceive(ByteBuffer buf) {
|
49765
|
448 |
if (debug.on())
|
|
449 |
debug.log("Putting %s bytes into the queue", buf.remaining());
|
48083
|
450 |
received.addAndGet(buf.remaining());
|
|
451 |
queue.offer(buf);
|
|
452 |
|
|
453 |
// This callback is called from within the selector thread.
|
|
454 |
// Use an executor here to avoid doing the heavy lifting in the
|
|
455 |
// selector.
|
49765
|
456 |
scheduler.runOrSchedule(executor);
|
48083
|
457 |
}
|
|
458 |
|
|
459 |
// Callback: Consumer of Throwable
|
|
460 |
void onReadError(Throwable ex) {
|
|
461 |
Http1AsyncDelegate delegate;
|
|
462 |
Throwable recorded;
|
49765
|
463 |
if (debug.on()) debug.log("onError: %s", (Object) ex);
|
48083
|
464 |
synchronized (this) {
|
|
465 |
delegate = this.delegate;
|
|
466 |
recorded = error;
|
|
467 |
if (recorded == null) {
|
|
468 |
// retry is set to true by HttpExchange when the connection is
|
|
469 |
// already connected, which means it's been retrieved from
|
|
470 |
// the pool.
|
|
471 |
if (retry && (ex instanceof IOException)) {
|
|
472 |
// could be either EOFException, or
|
|
473 |
// IOException("connection reset by peer), or
|
|
474 |
// SSLHandshakeException resulting from the server having
|
|
475 |
// closed the SSL session.
|
|
476 |
if (received.get() == 0) {
|
|
477 |
// If we receive such an exception before having
|
|
478 |
// received any byte, then in this case, we will
|
|
479 |
// throw ConnectionExpiredException
|
|
480 |
// to try & force a retry of the request.
|
|
481 |
retry = false;
|
50681
|
482 |
ex = new ConnectionExpiredException(ex);
|
48083
|
483 |
}
|
|
484 |
}
|
|
485 |
error = ex;
|
|
486 |
}
|
50681
|
487 |
}
|
48083
|
488 |
final Throwable t = (recorded == null ? ex : recorded);
|
49765
|
489 |
if (debug.on())
|
|
490 |
debug.log("recorded " + t + "\n\t delegate: " + delegate
|
|
491 |
+ "\t\t queue.isEmpty: " + queue.isEmpty(), ex);
|
50681
|
492 |
if (Log.errors()) {
|
|
493 |
Log.logError("HTTP/1 read subscriber recorded error: {0} - {1}", describe(), t);
|
48083
|
494 |
}
|
49765
|
495 |
if (queue.isEmpty() || pendingDelegateRef.get() != null || stopRequested) {
|
48083
|
496 |
// This callback is called from within the selector thread.
|
|
497 |
// Use an executor here to avoid doing the heavy lifting in the
|
|
498 |
// selector.
|
50681
|
499 |
if (Log.errors()) {
|
|
500 |
Log.logError("HTTP/1 propagating recorded error: {0} - {1}", describe(), t);
|
|
501 |
}
|
49765
|
502 |
scheduler.runOrSchedule(executor);
|
48083
|
503 |
}
|
|
504 |
}
|
|
505 |
|
|
506 |
void stop() {
|
49765
|
507 |
if (debug.on()) debug.log("stopping");
|
50681
|
508 |
if (Log.channel() && !scheduler.isStopped()) {
|
|
509 |
Log.logChannel("HTTP/1 read subscriber stopped for {0}", describe());
|
|
510 |
}
|
48083
|
511 |
scheduler.stop();
|
49765
|
512 |
// make sure ref count is handled properly by
|
|
513 |
// closing the delegate.
|
|
514 |
Http1AsyncDelegate previous = delegate;
|
|
515 |
if (previous != null) previous.close(error);
|
48083
|
516 |
delegate = null;
|
|
517 |
owner = null;
|
50681
|
518 |
whenFinished.complete(null);
|
48083
|
519 |
}
|
|
520 |
|
|
521 |
/**
|
|
522 |
* Returns the TubeSubscriber for reading from the connection flow.
|
|
523 |
* @return the TubeSubscriber for reading from the connection flow.
|
|
524 |
*/
|
|
525 |
TubeSubscriber subscriber() {
|
|
526 |
return subscriber;
|
|
527 |
}
|
|
528 |
|
|
529 |
/**
|
|
530 |
* A simple tube subscriber for reading from the connection flow.
|
|
531 |
*/
|
|
532 |
final class Http1TubeSubscriber implements TubeSubscriber {
|
|
533 |
volatile Flow.Subscription subscription;
|
|
534 |
volatile boolean completed;
|
|
535 |
volatile boolean dropped;
|
|
536 |
|
|
537 |
public void onSubscribe(Flow.Subscription subscription) {
|
|
538 |
// supports being called multiple time.
|
|
539 |
// doesn't cancel the previous subscription, since that is
|
|
540 |
// most probably the same as the new subscription.
|
50681
|
541 |
if (debug.on()) debug.log("Received onSubscribed from upstream");
|
|
542 |
if (Log.channel()) {
|
|
543 |
Log.logChannel("HTTP/1 read subscriber got subscription from {0}", describe());
|
|
544 |
}
|
48083
|
545 |
assert this.subscription == null || dropped == false;
|
|
546 |
this.subscription = subscription;
|
|
547 |
dropped = false;
|
|
548 |
canRequestMore.set(true);
|
|
549 |
if (delegate != null) {
|
49765
|
550 |
scheduler.runOrSchedule(executor);
|
50681
|
551 |
} else {
|
|
552 |
if (debug.on()) debug.log("onSubscribe: read delegate not present yet");
|
48083
|
553 |
}
|
|
554 |
}
|
|
555 |
|
|
556 |
void requestMore() {
|
|
557 |
Flow.Subscription s = subscription;
|
|
558 |
if (s == null) return;
|
|
559 |
if (canRequestMore.compareAndSet(true, false)) {
|
|
560 |
if (!completed && !dropped) {
|
49765
|
561 |
if (debug.on())
|
|
562 |
debug.log("Http1TubeSubscriber: requesting one more from upstream");
|
48083
|
563 |
s.request(1);
|
|
564 |
return;
|
|
565 |
}
|
|
566 |
}
|
49765
|
567 |
if (debug.on())
|
|
568 |
debug.log("Http1TubeSubscriber: no need to request more");
|
48083
|
569 |
}
|
|
570 |
|
|
571 |
@Override
|
|
572 |
public void onNext(List<ByteBuffer> item) {
|
|
573 |
canRequestMore.set(item.isEmpty());
|
|
574 |
for (ByteBuffer buffer : item) {
|
|
575 |
asyncReceive(buffer);
|
|
576 |
}
|
|
577 |
}
|
|
578 |
|
|
579 |
@Override
|
|
580 |
public void onError(Throwable throwable) {
|
|
581 |
onReadError(throwable);
|
|
582 |
completed = true;
|
|
583 |
}
|
|
584 |
|
|
585 |
@Override
|
|
586 |
public void onComplete() {
|
|
587 |
onReadError(new EOFException("EOF reached while reading"));
|
|
588 |
completed = true;
|
|
589 |
}
|
|
590 |
|
|
591 |
public void dropSubscription() {
|
49765
|
592 |
if (debug.on()) debug.log("Http1TubeSubscriber: dropSubscription");
|
48083
|
593 |
// we could probably set subscription to null here...
|
|
594 |
// then we might not need the 'dropped' boolean?
|
|
595 |
dropped = true;
|
|
596 |
}
|
|
597 |
|
|
598 |
}
|
|
599 |
|
|
600 |
// Drains the content of the queue into a single ByteBuffer.
|
|
601 |
// The scheduler must be permanently stopped before calling drain().
|
|
602 |
ByteBuffer drain(ByteBuffer initial) {
|
|
603 |
// Revisit: need to clean that up.
|
|
604 |
//
|
|
605 |
ByteBuffer b = initial = (initial == null ? Utils.EMPTY_BYTEBUFFER : initial);
|
|
606 |
assert scheduler.isStopped();
|
|
607 |
|
|
608 |
if (queue.isEmpty()) return b;
|
|
609 |
|
|
610 |
// sanity check: we shouldn't have queued the same
|
|
611 |
// buffer twice.
|
|
612 |
ByteBuffer[] qbb = queue.toArray(new ByteBuffer[queue.size()]);
|
49765
|
613 |
|
|
614 |
// the assertion looks suspicious, more investigation needed
|
|
615 |
//
|
|
616 |
// assert java.util.stream.Stream.of(qbb)
|
|
617 |
// .collect(Collectors.toSet())
|
|
618 |
// .size() == qbb.length : debugQBB(qbb);
|
48083
|
619 |
|
|
620 |
// compute the number of bytes in the queue, the number of bytes
|
|
621 |
// in the initial buffer
|
|
622 |
// TODO: will need revisiting - as it is not guaranteed that all
|
|
623 |
// data will fit in single BB!
|
|
624 |
int size = Utils.remaining(qbb, Integer.MAX_VALUE);
|
|
625 |
int remaining = b.remaining();
|
|
626 |
int free = b.capacity() - b.position() - remaining;
|
49765
|
627 |
if (debug.on())
|
|
628 |
debug.log("Flushing %s bytes from queue into initial buffer "
|
|
629 |
+ "(remaining=%s, free=%s)", size, remaining, free);
|
48083
|
630 |
|
|
631 |
// check whether the initial buffer has enough space
|
|
632 |
if (size > free) {
|
49765
|
633 |
if (debug.on())
|
|
634 |
debug.log("Allocating new buffer for initial: %s", (size + remaining));
|
48083
|
635 |
// allocates a new buffer and copy initial to it
|
|
636 |
b = ByteBuffer.allocate(size + remaining);
|
|
637 |
Utils.copy(initial, b);
|
|
638 |
assert b.position() == remaining;
|
|
639 |
b.flip();
|
|
640 |
assert b.position() == 0;
|
|
641 |
assert b.limit() == remaining;
|
|
642 |
assert b.remaining() == remaining;
|
|
643 |
}
|
|
644 |
|
|
645 |
// store position and limit
|
|
646 |
int pos = b.position();
|
|
647 |
int limit = b.limit();
|
|
648 |
assert limit - pos == remaining;
|
|
649 |
assert b.capacity() >= remaining + size
|
|
650 |
: "capacity: " + b.capacity()
|
|
651 |
+ ", remaining: " + b.remaining()
|
|
652 |
+ ", size: " + size;
|
|
653 |
|
|
654 |
// prepare to copy the content of the queue
|
|
655 |
b.position(limit);
|
|
656 |
b.limit(pos + remaining + size);
|
|
657 |
assert b.remaining() >= size :
|
|
658 |
"remaining: " + b.remaining() + ", size: " + size;
|
|
659 |
|
|
660 |
// copy the content of the queue
|
|
661 |
int count = 0;
|
|
662 |
for (int i=0; i<qbb.length; i++) {
|
|
663 |
ByteBuffer b2 = qbb[i];
|
|
664 |
int r = b2.remaining();
|
|
665 |
assert b.remaining() >= r : "need at least " + r + " only "
|
|
666 |
+ b.remaining() + " available";
|
|
667 |
int copied = Utils.copy(b2, b);
|
|
668 |
assert copied == r : "copied="+copied+" available="+r;
|
|
669 |
assert b2.remaining() == 0;
|
|
670 |
count += copied;
|
|
671 |
}
|
|
672 |
assert count == size;
|
|
673 |
assert b.position() == pos + remaining + size :
|
|
674 |
"b.position="+b.position()+" != "+pos+"+"+remaining+"+"+size;
|
|
675 |
|
|
676 |
// reset limit and position
|
|
677 |
b.limit(limit+size);
|
|
678 |
b.position(pos);
|
|
679 |
|
|
680 |
// we can clear the refs
|
|
681 |
queue.clear();
|
|
682 |
final ByteBuffer bb = b;
|
49765
|
683 |
if (debug.on())
|
|
684 |
debug.log("Initial buffer now has " + bb.remaining()
|
|
685 |
+ " pos=" + bb.position() + " limit=" + bb.limit());
|
48083
|
686 |
|
|
687 |
return b;
|
|
688 |
}
|
|
689 |
|
|
690 |
private String debugQBB(ByteBuffer[] qbb) {
|
|
691 |
StringBuilder msg = new StringBuilder();
|
|
692 |
List<ByteBuffer> lbb = Arrays.asList(qbb);
|
|
693 |
Set<ByteBuffer> sbb = new HashSet<>(Arrays.asList(qbb));
|
|
694 |
|
|
695 |
int uniquebb = sbb.size();
|
|
696 |
msg.append("qbb: ").append(lbb.size())
|
|
697 |
.append(" (unique: ").append(uniquebb).append("), ")
|
|
698 |
.append("duplicates: ");
|
|
699 |
String sep = "";
|
|
700 |
for (ByteBuffer b : lbb) {
|
|
701 |
if (!sbb.remove(b)) {
|
|
702 |
msg.append(sep)
|
|
703 |
.append(String.valueOf(b))
|
|
704 |
.append("[remaining=")
|
|
705 |
.append(b.remaining())
|
|
706 |
.append(", position=")
|
|
707 |
.append(b.position())
|
|
708 |
.append(", capacity=")
|
|
709 |
.append(b.capacity())
|
|
710 |
.append("]");
|
|
711 |
sep = ", ";
|
|
712 |
}
|
|
713 |
}
|
|
714 |
return msg.toString();
|
|
715 |
}
|
|
716 |
|
|
717 |
volatile String dbgTag;
|
|
718 |
String dbgString() {
|
|
719 |
String tag = dbgTag;
|
|
720 |
if (tag == null) {
|
|
721 |
String flowTag = null;
|
|
722 |
Http1Exchange<?> exchg = owner;
|
|
723 |
Object flow = (exchg != null)
|
|
724 |
? exchg.connection().getConnectionFlow()
|
|
725 |
: null;
|
|
726 |
flowTag = tag = flow == null ? null: (String.valueOf(flow));
|
|
727 |
if (flowTag != null) {
|
49765
|
728 |
dbgTag = tag = "Http1AsyncReceiver("+ flowTag + ")";
|
48083
|
729 |
} else {
|
49765
|
730 |
tag = "Http1AsyncReceiver(?)";
|
48083
|
731 |
}
|
|
732 |
}
|
|
733 |
return tag;
|
|
734 |
}
|
|
735 |
}
|