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.common;
|
48083
|
27 |
|
|
28 |
import java.io.Closeable;
|
|
29 |
import java.lang.System.Logger.Level;
|
|
30 |
import java.nio.ByteBuffer;
|
49765
|
31 |
import java.util.ArrayList;
|
48083
|
32 |
import java.util.List;
|
|
33 |
import java.util.Objects;
|
|
34 |
import java.util.concurrent.CompletableFuture;
|
|
35 |
import java.util.concurrent.ConcurrentLinkedQueue;
|
|
36 |
import java.util.concurrent.Flow;
|
|
37 |
import java.util.concurrent.Flow.Subscriber;
|
|
38 |
import java.util.concurrent.atomic.AtomicLong;
|
|
39 |
import java.util.concurrent.atomic.AtomicReference;
|
|
40 |
|
|
41 |
/**
|
|
42 |
* A wrapper for a Flow.Subscriber. This wrapper delivers data to the wrapped
|
|
43 |
* Subscriber which is supplied to the constructor. This class takes care of
|
|
44 |
* downstream flow control automatically and upstream flow control automatically
|
|
45 |
* by default.
|
|
46 |
* <p>
|
|
47 |
* Processing is done by implementing the {@link #incoming(List, boolean)} method
|
|
48 |
* which supplies buffers from upstream. This method (or any other method)
|
|
49 |
* can then call the outgoing() method to deliver processed buffers downstream.
|
|
50 |
* <p>
|
|
51 |
* Upstream error signals are delivered downstream directly. Cancellation from
|
|
52 |
* downstream is also propagated upstream immediately.
|
|
53 |
* <p>
|
|
54 |
* Each SubscriberWrapper has a {@link java.util.concurrent.CompletableFuture}{@code <Void>}
|
|
55 |
* which propagates completion/errors from downstream to upstream. Normal completion
|
|
56 |
* can only occur after onComplete() is called, but errors can be propagated upwards
|
|
57 |
* at any time.
|
|
58 |
*/
|
|
59 |
public abstract class SubscriberWrapper
|
|
60 |
implements FlowTube.TubeSubscriber, Closeable, Flow.Processor<List<ByteBuffer>,List<ByteBuffer>>
|
|
61 |
// TODO: SSLTube Subscriber will never change? Does this really need to be a TS?
|
|
62 |
{
|
49765
|
63 |
final Logger debug =
|
|
64 |
Utils.getDebugLogger(this::dbgString, Utils.DEBUG);
|
48083
|
65 |
|
|
66 |
public enum SchedulingAction { CONTINUE, RETURN, RESCHEDULE }
|
|
67 |
|
|
68 |
volatile Flow.Subscription upstreamSubscription;
|
|
69 |
final SubscriptionBase downstreamSubscription;
|
|
70 |
volatile boolean upstreamCompleted;
|
|
71 |
volatile boolean downstreamCompleted;
|
|
72 |
volatile boolean completionAcknowledged;
|
|
73 |
private volatile Subscriber<? super List<ByteBuffer>> downstreamSubscriber;
|
|
74 |
// processed byte to send to the downstream subscriber.
|
|
75 |
private final ConcurrentLinkedQueue<List<ByteBuffer>> outputQ;
|
|
76 |
private final CompletableFuture<Void> cf;
|
|
77 |
private final SequentialScheduler pushScheduler;
|
|
78 |
private final AtomicReference<Throwable> errorRef = new AtomicReference<>();
|
|
79 |
final AtomicLong upstreamWindow = new AtomicLong(0);
|
|
80 |
|
|
81 |
/**
|
|
82 |
* Wraps the given downstream subscriber. For each call to {@link
|
|
83 |
* #onNext(List<ByteBuffer>) } the given filter function is invoked
|
|
84 |
* and the list (if not empty) returned is passed downstream.
|
|
85 |
*
|
|
86 |
* A {@code CompletableFuture} is supplied which can be used to signal an
|
|
87 |
* error from downstream and which terminates the wrapper or which signals
|
|
88 |
* completion of downstream activity which can be propagated upstream. Error
|
|
89 |
* completion can be signaled at any time, but normal completion must not be
|
|
90 |
* signaled before onComplete() is called.
|
|
91 |
*/
|
|
92 |
public SubscriberWrapper()
|
|
93 |
{
|
|
94 |
this.outputQ = new ConcurrentLinkedQueue<>();
|
49765
|
95 |
this.cf = new MinimalFuture<Void>();
|
|
96 |
cf.whenComplete((v,t) -> {
|
|
97 |
if (t != null)
|
|
98 |
errorCommon(t);
|
|
99 |
});
|
48083
|
100 |
this.pushScheduler =
|
|
101 |
SequentialScheduler.synchronizedScheduler(new DownstreamPusher());
|
|
102 |
this.downstreamSubscription = new SubscriptionBase(pushScheduler,
|
|
103 |
this::downstreamCompletion);
|
|
104 |
}
|
|
105 |
|
|
106 |
@Override
|
|
107 |
public final void subscribe(Subscriber<? super List<ByteBuffer>> downstreamSubscriber) {
|
|
108 |
Objects.requireNonNull(downstreamSubscriber);
|
|
109 |
this.downstreamSubscriber = downstreamSubscriber;
|
|
110 |
}
|
|
111 |
|
|
112 |
/**
|
|
113 |
* Wraps the given downstream wrapper in this. For each call to
|
|
114 |
* {@link #onNext(List<ByteBuffer>) } the incoming() method is called.
|
|
115 |
*
|
|
116 |
* The {@code downstreamCF} from the downstream wrapper is linked to this
|
|
117 |
* wrappers notifier.
|
|
118 |
*
|
|
119 |
* @param downstreamWrapper downstream destination
|
|
120 |
*/
|
|
121 |
public SubscriberWrapper(Subscriber<? super List<ByteBuffer>> downstreamWrapper)
|
|
122 |
{
|
|
123 |
this();
|
|
124 |
subscribe(downstreamWrapper);
|
|
125 |
}
|
|
126 |
|
|
127 |
/**
|
|
128 |
* Delivers data to be processed by this wrapper. Generated data to be sent
|
|
129 |
* downstream, must be provided to the {@link #outgoing(List, boolean)}}
|
|
130 |
* method.
|
|
131 |
*
|
|
132 |
* @param buffers a List of ByteBuffers.
|
|
133 |
* @param complete if true then no more data will be added to the list
|
|
134 |
*/
|
|
135 |
protected abstract void incoming(List<ByteBuffer> buffers, boolean complete);
|
|
136 |
|
|
137 |
/**
|
|
138 |
* This method is called to determine the window size to use at any time. The
|
|
139 |
* current window is supplied together with the current downstream queue size.
|
|
140 |
* {@code 0} should be returned if no change is
|
|
141 |
* required or a positive integer which will be added to the current window.
|
|
142 |
* The default implementation maintains a downstream queue size of no greater
|
|
143 |
* than 5. The method can be overridden if required.
|
|
144 |
*
|
|
145 |
* @param currentWindow the current upstream subscription window
|
|
146 |
* @param downstreamQsize the current number of buffers waiting to be sent
|
|
147 |
* downstream
|
|
148 |
*
|
|
149 |
* @return value to add to currentWindow
|
|
150 |
*/
|
|
151 |
protected long upstreamWindowUpdate(long currentWindow, long downstreamQsize) {
|
|
152 |
if (downstreamQsize > 5) {
|
|
153 |
return 0;
|
|
154 |
}
|
|
155 |
|
|
156 |
if (currentWindow == 0) {
|
|
157 |
return 1;
|
|
158 |
} else {
|
|
159 |
return 0;
|
|
160 |
}
|
|
161 |
}
|
|
162 |
|
|
163 |
/**
|
|
164 |
* Override this if anything needs to be done after the upstream subscriber
|
|
165 |
* has subscribed
|
|
166 |
*/
|
|
167 |
protected void onSubscribe() {
|
|
168 |
}
|
|
169 |
|
|
170 |
/**
|
|
171 |
* Override this if anything needs to be done before checking for error
|
|
172 |
* and processing the input queue.
|
|
173 |
* @return
|
|
174 |
*/
|
|
175 |
protected SchedulingAction enterScheduling() {
|
|
176 |
return SchedulingAction.CONTINUE;
|
|
177 |
}
|
|
178 |
|
|
179 |
protected boolean signalScheduling() {
|
|
180 |
if (downstreamCompleted || pushScheduler.isStopped()) {
|
|
181 |
return false;
|
|
182 |
}
|
|
183 |
pushScheduler.runOrSchedule();
|
|
184 |
return true;
|
|
185 |
}
|
|
186 |
|
|
187 |
/**
|
|
188 |
* Delivers buffers of data downstream. After incoming()
|
|
189 |
* has been called complete == true signifying completion of the upstream
|
|
190 |
* subscription, data may continue to be delivered, up to when outgoing() is
|
|
191 |
* called complete == true, after which, the downstream subscription is
|
|
192 |
* completed.
|
|
193 |
*
|
|
194 |
* It's an error to call outgoing() with complete = true if incoming() has
|
|
195 |
* not previously been called with it.
|
|
196 |
*/
|
|
197 |
public void outgoing(ByteBuffer buffer, boolean complete) {
|
|
198 |
Objects.requireNonNull(buffer);
|
|
199 |
assert !complete || !buffer.hasRemaining();
|
|
200 |
outgoing(List.of(buffer), complete);
|
|
201 |
}
|
|
202 |
|
|
203 |
/**
|
|
204 |
* Sometime it might be necessary to complete the downstream subscriber
|
|
205 |
* before the upstream completes. For instance, when an SSL server
|
|
206 |
* sends a notify_close. In that case we should let the outgoing
|
49765
|
207 |
* complete before upstream is completed.
|
48083
|
208 |
* @return true, may be overridden by subclasses.
|
|
209 |
*/
|
|
210 |
public boolean closing() {
|
|
211 |
return false;
|
|
212 |
}
|
|
213 |
|
|
214 |
public void outgoing(List<ByteBuffer> buffers, boolean complete) {
|
|
215 |
Objects.requireNonNull(buffers);
|
|
216 |
if (complete) {
|
|
217 |
assert Utils.remaining(buffers) == 0;
|
|
218 |
boolean closing = closing();
|
49765
|
219 |
if (debug.on())
|
|
220 |
debug.log("completionAcknowledged upstreamCompleted:%s,"
|
|
221 |
+ " downstreamCompleted:%s, closing:%s",
|
|
222 |
upstreamCompleted, downstreamCompleted, closing);
|
|
223 |
if (!upstreamCompleted && !closing) {
|
48083
|
224 |
throw new IllegalStateException("upstream not completed");
|
49765
|
225 |
}
|
48083
|
226 |
completionAcknowledged = true;
|
|
227 |
} else {
|
49765
|
228 |
if (debug.on())
|
|
229 |
debug.log("Adding %d to outputQ queue", Utils.remaining(buffers));
|
48083
|
230 |
outputQ.add(buffers);
|
|
231 |
}
|
49765
|
232 |
if (debug.on())
|
|
233 |
debug.log("pushScheduler" +(pushScheduler.isStopped() ? " is stopped!" : " is alive"));
|
48083
|
234 |
pushScheduler.runOrSchedule();
|
|
235 |
}
|
|
236 |
|
|
237 |
/**
|
|
238 |
* Returns a CompletableFuture which completes when this wrapper completes.
|
|
239 |
* Normal completion happens with the following steps (in order):
|
|
240 |
* 1. onComplete() is called
|
|
241 |
* 2. incoming() called with complete = true
|
|
242 |
* 3. outgoing() may continue to be called normally
|
|
243 |
* 4. outgoing called with complete = true
|
|
244 |
* 5. downstream subscriber is called onComplete()
|
|
245 |
*
|
|
246 |
* If the subscription is canceled or onComplete() is invoked the
|
|
247 |
* CompletableFuture completes exceptionally. Exceptional completion
|
|
248 |
* also occurs if downstreamCF completes exceptionally.
|
|
249 |
*/
|
|
250 |
public CompletableFuture<Void> completion() {
|
|
251 |
return cf;
|
|
252 |
}
|
|
253 |
|
|
254 |
/**
|
|
255 |
* Invoked whenever it 'may' be possible to push buffers downstream.
|
|
256 |
*/
|
|
257 |
class DownstreamPusher implements Runnable {
|
|
258 |
@Override
|
|
259 |
public void run() {
|
|
260 |
try {
|
|
261 |
run1();
|
|
262 |
} catch (Throwable t) {
|
|
263 |
errorCommon(t);
|
|
264 |
}
|
|
265 |
}
|
|
266 |
|
|
267 |
private void run1() {
|
|
268 |
if (downstreamCompleted) {
|
49765
|
269 |
if (debug.on())
|
|
270 |
debug.log("DownstreamPusher: downstream is already completed");
|
48083
|
271 |
return;
|
|
272 |
}
|
|
273 |
switch (enterScheduling()) {
|
|
274 |
case CONTINUE: break;
|
|
275 |
case RESCHEDULE: pushScheduler.runOrSchedule(); return;
|
|
276 |
case RETURN: return;
|
|
277 |
default:
|
|
278 |
errorRef.compareAndSet(null,
|
|
279 |
new InternalError("unknown scheduling command"));
|
|
280 |
break;
|
|
281 |
}
|
|
282 |
// If there was an error, send it downstream.
|
|
283 |
Throwable error = errorRef.get();
|
49765
|
284 |
if (error != null && outputQ.isEmpty()) {
|
48083
|
285 |
synchronized(this) {
|
49765
|
286 |
if (downstreamCompleted)
|
|
287 |
return;
|
48083
|
288 |
downstreamCompleted = true;
|
|
289 |
}
|
49765
|
290 |
if (debug.on())
|
|
291 |
debug.log("DownstreamPusher: forwarding error downstream: " + error);
|
48083
|
292 |
pushScheduler.stop();
|
|
293 |
outputQ.clear();
|
|
294 |
downstreamSubscriber.onError(error);
|
|
295 |
return;
|
|
296 |
}
|
|
297 |
|
|
298 |
// OK - no error, let's proceed
|
|
299 |
if (!outputQ.isEmpty()) {
|
49765
|
300 |
if (debug.on())
|
|
301 |
debug.log("DownstreamPusher: queue not empty, downstreamSubscription: %s",
|
|
302 |
downstreamSubscription);
|
48083
|
303 |
} else {
|
49765
|
304 |
if (debug.on())
|
|
305 |
debug.log("DownstreamPusher: queue empty, downstreamSubscription: %s",
|
|
306 |
downstreamSubscription);
|
48083
|
307 |
}
|
|
308 |
|
49944
|
309 |
boolean datasent = false;
|
48083
|
310 |
while (!outputQ.isEmpty() && downstreamSubscription.tryDecrement()) {
|
|
311 |
List<ByteBuffer> b = outputQ.poll();
|
49765
|
312 |
if (debug.on())
|
|
313 |
debug.log("DownstreamPusher: Pushing %d bytes downstream",
|
|
314 |
Utils.remaining(b));
|
48083
|
315 |
downstreamSubscriber.onNext(b);
|
49944
|
316 |
datasent = true;
|
48083
|
317 |
}
|
49944
|
318 |
if (datasent) upstreamWindowUpdate();
|
48083
|
319 |
checkCompletion();
|
|
320 |
}
|
|
321 |
}
|
|
322 |
|
|
323 |
void upstreamWindowUpdate() {
|
|
324 |
long downstreamQueueSize = outputQ.size();
|
49765
|
325 |
long upstreamWindowSize = upstreamWindow.get();
|
|
326 |
long n = upstreamWindowUpdate(upstreamWindowSize, downstreamQueueSize);
|
|
327 |
if (debug.on())
|
|
328 |
debug.log("upstreamWindowUpdate, "
|
|
329 |
+ "downstreamQueueSize:%d, upstreamWindow:%d",
|
|
330 |
downstreamQueueSize, upstreamWindowSize);
|
48083
|
331 |
if (n > 0)
|
|
332 |
upstreamRequest(n);
|
|
333 |
}
|
|
334 |
|
|
335 |
@Override
|
|
336 |
public void onSubscribe(Flow.Subscription subscription) {
|
|
337 |
if (upstreamSubscription != null) {
|
|
338 |
throw new IllegalStateException("Single shot publisher");
|
|
339 |
}
|
|
340 |
this.upstreamSubscription = subscription;
|
|
341 |
upstreamRequest(upstreamWindowUpdate(0, 0));
|
49765
|
342 |
if (debug.on())
|
|
343 |
debug.log("calling downstreamSubscriber::onSubscribe on %s",
|
|
344 |
downstreamSubscriber);
|
48083
|
345 |
downstreamSubscriber.onSubscribe(downstreamSubscription);
|
|
346 |
onSubscribe();
|
|
347 |
}
|
|
348 |
|
|
349 |
@Override
|
|
350 |
public void onNext(List<ByteBuffer> item) {
|
49765
|
351 |
if (debug.on()) debug.log("onNext");
|
48083
|
352 |
long prev = upstreamWindow.getAndDecrement();
|
|
353 |
if (prev <= 0)
|
|
354 |
throw new IllegalStateException("invalid onNext call");
|
|
355 |
incomingCaller(item, false);
|
|
356 |
upstreamWindowUpdate();
|
|
357 |
}
|
|
358 |
|
|
359 |
private void upstreamRequest(long n) {
|
49765
|
360 |
if (debug.on()) debug.log("requesting %d", n);
|
48083
|
361 |
upstreamWindow.getAndAdd(n);
|
|
362 |
upstreamSubscription.request(n);
|
|
363 |
}
|
|
364 |
|
|
365 |
protected void requestMore() {
|
|
366 |
if (upstreamWindow.get() == 0) {
|
|
367 |
upstreamRequest(1);
|
|
368 |
}
|
|
369 |
}
|
|
370 |
|
|
371 |
public long upstreamWindow() {
|
|
372 |
return upstreamWindow.get();
|
|
373 |
}
|
|
374 |
|
|
375 |
@Override
|
|
376 |
public void onError(Throwable throwable) {
|
49765
|
377 |
if (debug.on()) debug.log("onError: " + throwable);
|
48083
|
378 |
errorCommon(Objects.requireNonNull(throwable));
|
|
379 |
}
|
|
380 |
|
|
381 |
protected boolean errorCommon(Throwable throwable) {
|
49765
|
382 |
assert throwable != null ||
|
|
383 |
(throwable = new AssertionError("null throwable")) != null;
|
48083
|
384 |
if (errorRef.compareAndSet(null, throwable)) {
|
49765
|
385 |
if (debug.on()) debug.log("error", throwable);
|
48083
|
386 |
pushScheduler.runOrSchedule();
|
|
387 |
upstreamCompleted = true;
|
|
388 |
cf.completeExceptionally(throwable);
|
|
389 |
return true;
|
|
390 |
}
|
|
391 |
return false;
|
|
392 |
}
|
|
393 |
|
|
394 |
@Override
|
|
395 |
public void close() {
|
|
396 |
errorCommon(new RuntimeException("wrapper closed"));
|
|
397 |
}
|
|
398 |
|
49765
|
399 |
public void close(Throwable t) {
|
|
400 |
errorCommon(t);
|
|
401 |
}
|
|
402 |
|
48083
|
403 |
private void incomingCaller(List<ByteBuffer> l, boolean complete) {
|
|
404 |
try {
|
|
405 |
incoming(l, complete);
|
|
406 |
} catch(Throwable t) {
|
|
407 |
errorCommon(t);
|
|
408 |
}
|
|
409 |
}
|
|
410 |
|
|
411 |
@Override
|
|
412 |
public void onComplete() {
|
49765
|
413 |
if (debug.on()) debug.log("upstream completed: " + toString());
|
48083
|
414 |
upstreamCompleted = true;
|
|
415 |
incomingCaller(Utils.EMPTY_BB_LIST, true);
|
|
416 |
// pushScheduler will call checkCompletion()
|
|
417 |
pushScheduler.runOrSchedule();
|
|
418 |
}
|
|
419 |
|
|
420 |
/** Adds the given data to the input queue. */
|
|
421 |
public void addData(ByteBuffer l) {
|
|
422 |
if (upstreamSubscription == null) {
|
|
423 |
throw new IllegalStateException("can't add data before upstream subscriber subscribes");
|
|
424 |
}
|
|
425 |
incomingCaller(List.of(l), false);
|
|
426 |
}
|
|
427 |
|
|
428 |
void checkCompletion() {
|
|
429 |
if (downstreamCompleted || !upstreamCompleted) {
|
|
430 |
return;
|
|
431 |
}
|
|
432 |
if (!outputQ.isEmpty()) {
|
|
433 |
return;
|
|
434 |
}
|
|
435 |
if (errorRef.get() != null) {
|
|
436 |
pushScheduler.runOrSchedule();
|
|
437 |
return;
|
|
438 |
}
|
|
439 |
if (completionAcknowledged) {
|
49765
|
440 |
if (debug.on()) debug.log("calling downstreamSubscriber.onComplete()");
|
48083
|
441 |
downstreamSubscriber.onComplete();
|
|
442 |
// Fix me subscriber.onComplete.run();
|
|
443 |
downstreamCompleted = true;
|
|
444 |
cf.complete(null);
|
|
445 |
}
|
|
446 |
}
|
|
447 |
|
|
448 |
// called from the downstream Subscription.cancel()
|
|
449 |
void downstreamCompletion() {
|
|
450 |
upstreamSubscription.cancel();
|
|
451 |
cf.complete(null);
|
|
452 |
}
|
|
453 |
|
|
454 |
public void resetDownstreamDemand() {
|
|
455 |
downstreamSubscription.demand.reset();
|
|
456 |
}
|
|
457 |
|
|
458 |
@Override
|
|
459 |
public String toString() {
|
|
460 |
StringBuilder sb = new StringBuilder();
|
|
461 |
sb.append("SubscriberWrapper:")
|
|
462 |
.append(" upstreamCompleted: ").append(Boolean.toString(upstreamCompleted))
|
|
463 |
.append(" upstreamWindow: ").append(upstreamWindow.toString())
|
|
464 |
.append(" downstreamCompleted: ").append(Boolean.toString(downstreamCompleted))
|
|
465 |
.append(" completionAcknowledged: ").append(Boolean.toString(completionAcknowledged))
|
|
466 |
.append(" outputQ size: ").append(Integer.toString(outputQ.size()))
|
|
467 |
//.append(" outputQ: ").append(outputQ.toString())
|
|
468 |
.append(" cf: ").append(cf.toString())
|
|
469 |
.append(" downstreamSubscription: ").append(downstreamSubscription.toString());
|
|
470 |
|
|
471 |
return sb.toString();
|
|
472 |
}
|
|
473 |
|
|
474 |
public String dbgString() {
|
|
475 |
return "SubscriberWrapper";
|
|
476 |
}
|
|
477 |
}
|