Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableReplay.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.internal.operators.flowable;
15
16 import java.util.*;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.atomic.*;
19
20 import org.reactivestreams.*;
21
22 import io.reactivex.rxjava3.core.*;
23 import io.reactivex.rxjava3.disposables.Disposable;
24 import io.reactivex.rxjava3.exceptions.Exceptions;
25 import io.reactivex.rxjava3.flowables.ConnectableFlowable;
26 import io.reactivex.rxjava3.functions.*;
27 import io.reactivex.rxjava3.internal.fuseable.HasUpstreamPublisher;
28 import io.reactivex.rxjava3.internal.subscribers.SubscriberResourceWrapper;
29 import io.reactivex.rxjava3.internal.subscriptions.*;
30 import io.reactivex.rxjava3.internal.util.*;
31 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
32 import io.reactivex.rxjava3.schedulers.Timed;
33
34 public final class FlowableReplay<T> extends ConnectableFlowable<T> implements HasUpstreamPublisher<T> {
35 /** The source observable. */
36 final Flowable<T> source;
37 /** Holds the current subscriber that is, will be or just was subscribed to the source observable. */
38 final AtomicReference<ReplaySubscriber<T>> current;
39 /** A factory that creates the appropriate buffer for the ReplaySubscriber. */
40 final Supplier<? extends ReplayBuffer<T>> bufferFactory;
41
42 final Publisher<T> onSubscribe;
43
44 @SuppressWarnings("rawtypes")
45 static final Supplier DEFAULT_UNBOUNDED_FACTORY = new DefaultUnboundedFactory();
46
47 /**
48 * Given a connectable observable factory, it multicasts over the generated
49 * ConnectableObservable via a selector function.
50 * @param <U> the connectable observable type
51 * @param <R> the result type
52 * @param connectableFactory the factory that returns a ConnectableFlowable for each individual subscriber
53 * @param selector the function that receives a Flowable and should return another Flowable that will be subscribed to
54 * @return the new Observable instance
55 */
56 public static <U, R> Flowable<R> multicastSelector(
57 final Supplier<? extends ConnectableFlowable<U>> connectableFactory,
58 final Function<? super Flowable<U>, ? extends Publisher<R>> selector) {
59 return new MulticastFlowable<>(connectableFactory, selector);
60 }
61
62 /**
63 * Creates a replaying ConnectableObservable with an unbounded buffer.
64 * @param <T> the value type
65 * @param source the source Publisher to use
66 * @return the new ConnectableObservable instance
67 */
68 @SuppressWarnings("unchecked")
69 public static <T> ConnectableFlowable<T> createFrom(Flowable<? extends T> source) {
70 return create(source, DEFAULT_UNBOUNDED_FACTORY);
71 }
72
73 /**
74 * Creates a replaying ConnectableObservable with a size bound buffer.
75 * @param <T> the value type
76 * @param source the source Flowable to use
77 * @param bufferSize the maximum number of elements to hold
78 * @param eagerTruncate if true, the head reference is refreshed to avoid unwanted item retention
79 * @return the new ConnectableObservable instance
80 */
81 public static <T> ConnectableFlowable<T> create(Flowable<T> source,
82 final int bufferSize, boolean eagerTruncate) {
83 if (bufferSize == Integer.MAX_VALUE) {
84 return createFrom(source);
85 }
86 return create(source, new ReplayBufferSupplier<>(bufferSize, eagerTruncate));
87 }
88
89 /**
90 * Creates a replaying ConnectableObservable with a time bound buffer.
91 * @param <T> the value type
92 * @param source the source Flowable to use
93 * @param maxAge the maximum age of entries
94 * @param unit the unit of measure of the age amount
95 * @param scheduler the target scheduler providing the current time
96 * @param eagerTruncate if true, the head reference is refreshed to avoid unwanted item retention
97 * @return the new ConnectableObservable instance
98 */
99 public static <T> ConnectableFlowable<T> create(Flowable<T> source,
100 long maxAge, TimeUnit unit, Scheduler scheduler, boolean eagerTruncate) {
101 return create(source, maxAge, unit, scheduler, Integer.MAX_VALUE, eagerTruncate);
102 }
103
104 /**
105 * Creates a replaying ConnectableObservable with a size and time bound buffer.
106 * @param <T> the value type
107 * @param source the source Flowable to use
108 * @param maxAge the maximum age of entries
109 * @param unit the unit of measure of the age amount
110 * @param scheduler the target scheduler providing the current time
111 * @param bufferSize the maximum number of elements to hold
112 * @param eagerTruncate if true, the head reference is refreshed to avoid unwanted item retention
113 * @return the new ConnectableFlowable instance
114 */
115 public static <T> ConnectableFlowable<T> create(Flowable<T> source,
116 final long maxAge, final TimeUnit unit, final Scheduler scheduler, final int bufferSize, boolean eagerTruncate) {
117 return create(source, new ScheduledReplayBufferSupplier<>(bufferSize, maxAge, unit, scheduler, eagerTruncate));
118 }
119
120 /**
121 * Creates a OperatorReplay instance to replay values of the given source {@code Flowable}.
122 * @param <T> the value type
123 * @param source the source {@code Flowable} to use
124 * @param bufferFactory the factory to instantiate the appropriate buffer when the {@code Flowable} becomes active
125 * @return the {@code ConnectableFlowable} instance
126 */
127 static <T> ConnectableFlowable<T> create(Flowable<T> source,
128 final Supplier<? extends ReplayBuffer<T>> bufferFactory) {
129 // the current connection to source needs to be shared between the operator and its onSubscribe call
130 final AtomicReference<ReplaySubscriber<T>> curr = new AtomicReference<>();
131 Publisher<T> onSubscribe = new ReplayPublisher<>(curr, bufferFactory);
132 return RxJavaPlugins.onAssembly(new FlowableReplay<>(onSubscribe, source, curr, bufferFactory));
133 }
134
135 private FlowableReplay(Publisher<T> onSubscribe, Flowable<T> source,
136 final AtomicReference<ReplaySubscriber<T>> current,
137 final Supplier<? extends ReplayBuffer<T>> bufferFactory) {
138 this.onSubscribe = onSubscribe;
139 this.source = source;
140 this.current = current;
141 this.bufferFactory = bufferFactory;
142 }
143
144 @Override
145 public Publisher<T> source() {
146 return source;
147 }
148
149 @Override
150 protected void subscribeActual(Subscriber<? super T> s) {
151 onSubscribe.subscribe(s);
152 }
153
154 @Override
155 public void reset() {
156 ReplaySubscriber<T> conn = current.get();
157 if (conn != null && conn.isDisposed()) {
158 current.compareAndSet(conn, null);
159 }
160 }
161
162 @Override
163 public void connect(Consumer<? super Disposable> connection) {
164 boolean doConnect;
165 ReplaySubscriber<T> ps;
166 // we loop because concurrent connect/disconnect and termination may change the state
167 for (;;) {
168 // retrieve the current subscriber-to-source instance
169 ps = current.get();
170 // if there is none yet or the current was disposed
171 if (ps == null || ps.isDisposed()) {
172
173 ReplayBuffer<T> buf;
174
175 try {
176 buf = bufferFactory.get();
177 } catch (Throwable ex) {
178 Exceptions.throwIfFatal(ex);
179 throw ExceptionHelper.wrapOrThrow(ex);
180 }
181
182 // create a new subscriber-to-source
183 ReplaySubscriber<T> u = new ReplaySubscriber<>(buf, current);
184 // try setting it as the current subscriber-to-source
185 if (!current.compareAndSet(ps, u)) {
186 // did not work, perhaps a new subscriber arrived
187 // and created a new subscriber-to-source as well, retry
188 continue;
189 }
190 ps = u;
191 }
192 // if connect() was called concurrently, only one of them should actually
193 // connect to the source
194 doConnect = !ps.shouldConnect.get() && ps.shouldConnect.compareAndSet(false, true);
195 break; // NOPMD
196 }
197 /*
198 * Notify the callback that we have a (new) connection which it can dispose
199 * but since ps is unique to a connection, multiple calls to connect() will return the
200 * same Subscription and even if there was a connect-disconnect-connect pair, the older
201 * references won't disconnect the newer connection.
202 * Synchronous source consumers have the opportunity to disconnect via dispose on the
203 * Disposable as unsafeSubscribe may never return in its own.
204 *
205 * Note however, that asynchronously disconnecting a running source might leave
206 * child-subscribers without any terminal event; ReplaySubject does not have this
207 * issue because the cancellation was always triggered by the child-subscribers
208 * themselves.
209 */
210 try {
211 connection.accept(ps);
212 } catch (Throwable ex) {
213 Exceptions.throwIfFatal(ex);
214 if (doConnect) {
215 ps.shouldConnect.compareAndSet(true, false);
216 }
217 Exceptions.throwIfFatal(ex);
218 throw ExceptionHelper.wrapOrThrow(ex);
219 }
220 if (doConnect) {
221 source.subscribe(ps);
222 }
223 }
224
225 @SuppressWarnings("rawtypes")
226 static final class ReplaySubscriber<T>
227 extends AtomicReference<Subscription>
228 implements FlowableSubscriber<T>, Disposable {
229 private static final long serialVersionUID = 7224554242710036740L;
230 /** Holds notifications from upstream. */
231 final ReplayBuffer<T> buffer;
232 /** Indicates this Subscriber received a terminal event. */
233 boolean done;
234
235 /** Indicates an empty array of inner subscriptions. */
236 static final InnerSubscription[] EMPTY = new InnerSubscription[0];
237 /** Indicates a terminated ReplaySubscriber. */
238 static final InnerSubscription[] TERMINATED = new InnerSubscription[0];
239
240 /** Tracks the subscribed InnerSubscriptions. */
241 final AtomicReference<InnerSubscription<T>[]> subscribers;
242 /**
243 * Atomically changed from false to true by connect to make sure the
244 * connection is only performed by one thread.
245 */
246 final AtomicBoolean shouldConnect;
247
248 final AtomicInteger management;
249
250 /** Tracks the amount already requested from the upstream. */
251 long requestedFromUpstream;
252
253 /** The current connection. */
254 final AtomicReference<ReplaySubscriber<T>> current;
255
256 @SuppressWarnings("unchecked")
257 ReplaySubscriber(ReplayBuffer<T> buffer, AtomicReference<ReplaySubscriber<T>> current) {
258 this.buffer = buffer;
259 this.current = current;
260 this.management = new AtomicInteger();
261 this.subscribers = new AtomicReference<>(EMPTY);
262 this.shouldConnect = new AtomicBoolean();
263 }
264
265 @Override
266 public boolean isDisposed() {
267 return subscribers.get() == TERMINATED;
268 }
269
270 @SuppressWarnings("unchecked")
271 @Override
272 public void dispose() {
273 subscribers.set(TERMINATED);
274 current.compareAndSet(ReplaySubscriber.this, null);
275 // we don't care if it fails because it means the current has
276 // been replaced in the meantime
277 SubscriptionHelper.cancel(this);
278 }
279
280 /**
281 * Atomically try adding a new InnerSubscription to this Subscriber or return false if this
282 * Subscriber was terminated.
283 * @param producer the producer to add
284 * @return true if succeeded, false otherwise
285 */
286 @SuppressWarnings("unchecked")
287 boolean add(InnerSubscription<T> producer) {
288 // the state can change so we do a CAS loop to achieve atomicity
289 for (;;) {
290 // get the current producer array
291 InnerSubscription<T>[] c = subscribers.get();
292 // if this subscriber-to-source reached a terminal state by receiving
293 // an onError or onComplete, just refuse to add the new producer
294 if (c == TERMINATED) {
295 return false;
296 }
297 // we perform a copy-on-write logic
298 int len = c.length;
299 InnerSubscription<T>[] u = new InnerSubscription[len + 1];
300 System.arraycopy(c, 0, u, 0, len);
301 u[len] = producer;
302 // try setting the subscribers array
303 if (subscribers.compareAndSet(c, u)) {
304 return true;
305 }
306 // if failed, some other operation succeeded (another add, remove or termination)
307 // so retry
308 }
309 }
310
311 /**
312 * Atomically removes the given InnerSubscription from the subscribers array.
313 * @param p the InnerSubscription to remove
314 */
315 @SuppressWarnings("unchecked")
316 void remove(InnerSubscription<T> p) {
317 // the state can change so we do a CAS loop to achieve atomicity
318 for (;;) {
319 // let's read the current subscribers array
320 InnerSubscription<T>[] c = subscribers.get();
321 int len = c.length;
322 // if it is either empty or terminated, there is nothing to remove so we quit
323 if (len == 0) {
324 return;
325 }
326 // let's find the supplied producer in the array
327 // although this is O(n), we don't expect too many child subscribers in general
328 int j = -1;
329 for (int i = 0; i < len; i++) {
330 if (c[i].equals(p)) {
331 j = i;
332 break;
333 }
334 }
335 // we didn't find it so just quit
336 if (j < 0) {
337 return;
338 }
339 // we do copy-on-write logic here
340 InnerSubscription<T>[] u;
341 // we don't create a new empty array if producer was the single inhabitant
342 // but rather reuse an empty array
343 if (len == 1) {
344 u = EMPTY;
345 } else {
346 // otherwise, create a new array one less in size
347 u = new InnerSubscription[len - 1];
348 // copy elements being before the given producer
349 System.arraycopy(c, 0, u, 0, j);
350 // copy elements being after the given producer
351 System.arraycopy(c, j + 1, u, j, len - j - 1);
352 }
353 // try setting this new array as
354 if (subscribers.compareAndSet(c, u)) {
355 return;
356 }
357 // if we failed, it means something else happened
358 // (a concurrent add/remove or termination), we need to retry
359 }
360 }
361
362 @Override
363 public void onSubscribe(Subscription p) {
364 if (SubscriptionHelper.setOnce(this, p)) {
365 manageRequests();
366 for (InnerSubscription<T> rp : subscribers.get()) {
367 buffer.replay(rp);
368 }
369 }
370 }
371
372 @Override
373 public void onNext(T t) {
374 if (!done) {
375 buffer.next(t);
376 for (InnerSubscription<T> rp : subscribers.get()) {
377 buffer.replay(rp);
378 }
379 }
380 }
381
382 @SuppressWarnings("unchecked")
383 @Override
384 public void onError(Throwable e) {
385 // The observer front is accessed serially as required by spec so
386 // no need to CAS in the terminal value
387 if (!done) {
388 done = true;
389 buffer.error(e);
390 for (InnerSubscription<T> rp : subscribers.getAndSet(TERMINATED)) {
391 buffer.replay(rp);
392 }
393 } else {
394 RxJavaPlugins.onError(e);
395 }
396 }
397
398 @SuppressWarnings("unchecked")
399 @Override
400 public void onComplete() {
401 // The observer front is accessed serially as required by spec so
402 // no need to CAS in the terminal value
403 if (!done) {
404 done = true;
405 buffer.complete();
406 for (InnerSubscription<T> rp : subscribers.getAndSet(TERMINATED)) {
407 buffer.replay(rp);
408 }
409 }
410 }
411
412 /**
413 * Coordinates the request amounts of various child Subscribers.
414 */
415 void manageRequests() {
416 AtomicInteger m = management;
417 if (m.getAndIncrement() != 0) {
418 return;
419 }
420 int missed = 1;
421 for (;;) {
422 // if the upstream has completed, no more requesting is possible
423 if (isDisposed()) {
424 return;
425 }
426 Subscription p = get();
427
428 // only request when there is an upstream Subscription available
429 if (p != null) {
430 // how many items were requested so far
431 long alreadyRequested = requestedFromUpstream;
432 long downstreamMaxRequest = alreadyRequested;
433
434 // find out the maximum total requested of the current subscribers
435 for (InnerSubscription<T> rp : subscribers.get()) {
436 downstreamMaxRequest = Math.max(downstreamMaxRequest, rp.totalRequested.get());
437 }
438
439 // how much more to request from the upstream
440 long diff = downstreamMaxRequest - alreadyRequested;
441 if (diff != 0L) {
442 // save the new maximum requested
443 requestedFromUpstream = downstreamMaxRequest;
444 p.request(diff);
445 }
446 }
447
448 missed = m.addAndGet(-missed);
449 if (missed == 0) {
450 break;
451 }
452 }
453 }
454 }
455 /**
456 * A Subscription that manages the request and cancellation state of a
457 * child subscriber in thread-safe manner.
458 * @param <T> the value type
459 */
460 static final class InnerSubscription<T> extends AtomicLong implements Subscription, Disposable {
461
462 private static final long serialVersionUID = -4453897557930727610L;
463 /**
464 * The parent subscriber-to-source used to allow removing the child in case of
465 * child cancellation.
466 */
467 final ReplaySubscriber<T> parent;
468 /** The actual child subscriber. */
469 final Subscriber<? super T> child;
470 /**
471 * Holds an object that represents the current location in the buffer.
472 * Guarded by the emitter loop.
473 */
474 Object index;
475 /**
476 * Keeps the sum of all requested amounts.
477 */
478 final AtomicLong totalRequested;
479 /** Indicates an emission state. Guarded by this. */
480 boolean emitting;
481 /** Indicates a missed update. Guarded by this. */
482 boolean missed;
483 /**
484 * Indicates this child has been cancelled: the state is swapped in atomically and
485 * will prevent the dispatch() to emit (too many) values to a terminated child subscriber.
486 */
487 static final long CANCELLED = Long.MIN_VALUE;
488
489 InnerSubscription(ReplaySubscriber<T> parent, Subscriber<? super T> child) {
490 this.parent = parent;
491 this.child = child;
492 this.totalRequested = new AtomicLong();
493 }
494
495 @Override
496 public void request(long n) {
497 // ignore negative requests
498 if (SubscriptionHelper.validate(n)) {
499 // add to the current requested and cap it at MAX_VALUE
500 // except when there was a concurrent cancellation
501 if (BackpressureHelper.addCancel(this, n) != CANCELLED) {
502 // increment the total request counter
503 BackpressureHelper.add(totalRequested, n);
504 // if successful, notify the parent dispatcher this child can receive more
505 // elements
506 parent.manageRequests();
507 // try replaying any cached content
508 parent.buffer.replay(this);
509 }
510 }
511 }
512
513 /**
514 * Indicate that values have been emitted to this child subscriber by the dispatch() method.
515 * @param n the number of items emitted
516 * @return the updated request value (may indicate how much can be produced or a terminal state)
517 */
518 public long produced(long n) {
519 return BackpressureHelper.producedCancel(this, n);
520 }
521
522 @Override
523 public boolean isDisposed() {
524 return get() == CANCELLED;
525 }
526
527 @Override
528 public void cancel() {
529 dispose();
530 }
531
532 @Override
533 public void dispose() {
534 if (getAndSet(CANCELLED) != CANCELLED) {
535 // remove this from the parent
536 parent.remove(this);
537 // After removal, we might have unblocked the other child subscribers:
538 // let's assume this child had 0 requested before the cancellation while
539 // the others had non-zero. By removing this 'blocking' child, the others
540 // are now free to receive events
541 parent.manageRequests();
542 // make sure the last known node is not retained
543 index = null;
544 }
545 }
546 /**
547 * Convenience method to auto-cast the index object.
548 * @param <U> type to cast index object
549 * @return the current index object
550 */
551 @SuppressWarnings("unchecked")
552 <U> U index() {
553 return (U)index;
554 }
555 }
556 /**
557 * The interface for interacting with various buffering logic.
558 *
559 * @param <T> the value type
560 */
561 interface ReplayBuffer<T> {
562 /**
563 * Adds a regular value to the buffer.
564 * @param value the next value to store
565 */
566 void next(T value);
567 /**
568 * Adds a terminal exception to the buffer.
569 * @param e the Throwable instance
570 */
571 void error(Throwable e);
572 /**
573 * Adds a completion event to the buffer.
574 */
575 void complete();
576 /**
577 * Tries to replay the buffered values to the
578 * subscriber inside the output if there
579 * is new value and requests available at the
580 * same time.
581 * @param output the receiver of the events
582 */
583 void replay(InnerSubscription<T> output);
584 }
585
586 /**
587 * Holds an unbounded list of events.
588 *
589 * @param <T> the value type
590 */
591 static final class UnboundedReplayBuffer<T> extends ArrayList<Object> implements ReplayBuffer<T> {
592
593 private static final long serialVersionUID = 7063189396499112664L;
594 /** The total number of events in the buffer. */
595 volatile int size;
596
597 UnboundedReplayBuffer(int capacityHint) {
598 super(capacityHint);
599 }
600
601 @Override
602 public void next(T value) {
603 add(NotificationLite.next(value));
604 size++;
605 }
606
607 @Override
608 public void error(Throwable e) {
609 add(NotificationLite.error(e));
610 size++;
611 }
612
613 @Override
614 public void complete() {
615 add(NotificationLite.complete());
616 size++;
617 }
618
619 @Override
620 public void replay(InnerSubscription<T> output) {
621 synchronized (output) {
622 if (output.emitting) {
623 output.missed = true;
624 return;
625 }
626 output.emitting = true;
627 }
628 final Subscriber<? super T> child = output.child;
629
630 for (;;) {
631 if (output.isDisposed()) {
632 return;
633 }
634 int sourceIndex = size;
635
636 Integer destinationIndexObject = output.index();
637 int destinationIndex = destinationIndexObject != null ? destinationIndexObject : 0;
638
639 long r = output.get();
640 long r0 = r; // NOPMD
641 long e = 0L;
642
643 while (r != 0L && destinationIndex < sourceIndex) {
644 Object o = get(destinationIndex);
645 try {
646 if (NotificationLite.accept(o, child)) {
647 return;
648 }
649 } catch (Throwable err) {
650 Exceptions.throwIfFatal(err);
651 output.dispose();
652 if (!NotificationLite.isError(o) && !NotificationLite.isComplete(o)) {
653 child.onError(err);
654 } else {
655 RxJavaPlugins.onError(err);
656 }
657 return;
658 }
659 if (output.isDisposed()) {
660 return;
661 }
662 destinationIndex++;
663 r--;
664 e++;
665 }
666 if (e != 0L) {
667 output.index = destinationIndex;
668 if (r0 != Long.MAX_VALUE) {
669 output.produced(e);
670 }
671 }
672
673 synchronized (output) {
674 if (!output.missed) {
675 output.emitting = false;
676 return;
677 }
678 output.missed = false;
679 }
680 }
681 }
682 }
683
684 /**
685 * Represents a node in a bounded replay buffer's linked list.
686 */
687 static final class Node extends AtomicReference<Node> {
688
689 private static final long serialVersionUID = 245354315435971818L;
690 final Object value;
691 final long index;
692
693 Node(Object value, long index) {
694 this.value = value;
695 this.index = index;
696 }
697 }
698
699 /**
700 * Base class for bounded buffering with options to specify an
701 * enter and leave transforms and custom truncation behavior.
702 *
703 * @param <T> the value type
704 */
705 abstract static class BoundedReplayBuffer<T> extends AtomicReference<Node> implements ReplayBuffer<T> {
706
707 private static final long serialVersionUID = 2346567790059478686L;
708
709 final boolean eagerTruncate;
710
711 Node tail;
712 int size;
713
714 long index;
715
716 BoundedReplayBuffer(boolean eagerTruncate) {
717 this.eagerTruncate = eagerTruncate;
718 Node n = new Node(null, 0);
719 tail = n;
720 set(n);
721 }
722
723 /**
724 * Add a new node to the linked list.
725 * @param n the Node instance to add
726 */
727 final void addLast(Node n) {
728 tail.set(n);
729 tail = n;
730 size++;
731 }
732 /**
733 * Remove the first node from the linked list.
734 */
735 final void removeFirst() {
736 Node head = get();
737 Node next = head.get();
738 if (next == null) {
739 throw new IllegalStateException("Empty list!");
740 }
741 size--;
742 // can't just move the head because it would retain the very first value
743 // can't null out the head's value because of late replayers would see null
744 setFirst(next);
745 }
746 /* test */ final void removeSome(int n) {
747 Node head = get();
748 while (n > 0) {
749 head = head.get();
750 n--;
751 size--;
752 }
753
754 setFirst(head);
755 // correct the tail if all items have been removed
756 head = get();
757 if (head.get() == null) {
758 tail = head;
759 }
760 }
761 /**
762 * Arranges the given node is the new head from now on.
763 * @param n the Node instance to set as first
764 */
765 final void setFirst(Node n) {
766 if (eagerTruncate) {
767 Node m = new Node(null, n.index);
768 m.lazySet(n.get());
769 n = m;
770 }
771 set(n);
772 }
773
774 @Override
775 public final void next(T value) {
776 Object o = enterTransform(NotificationLite.next(value), false);
777 Node n = new Node(o, ++index);
778 addLast(n);
779 truncate();
780 }
781
782 @Override
783 public final void error(Throwable e) {
784 Object o = enterTransform(NotificationLite.error(e), true);
785 Node n = new Node(o, ++index);
786 addLast(n);
787 truncateFinal();
788 }
789
790 @Override
791 public final void complete() {
792 Object o = enterTransform(NotificationLite.complete(), true);
793 Node n = new Node(o, ++index);
794 addLast(n);
795 truncateFinal();
796 }
797
798 final void trimHead() {
799 Node head = get();
800 if (head.value != null) {
801 Node n = new Node(null, 0L);
802 n.lazySet(head.get());
803 set(n);
804 }
805 }
806
807 @Override
808 public final void replay(InnerSubscription<T> output) {
809 synchronized (output) {
810 if (output.emitting) {
811 output.missed = true;
812 return;
813 }
814 output.emitting = true;
815 }
816 for (;;) {
817 long r = output.get();
818 boolean unbounded = r == Long.MAX_VALUE; // NOPMD
819 long e = 0L;
820
821 Node node = output.index();
822 if (node == null) {
823 node = getHead();
824 output.index = node;
825
826 BackpressureHelper.add(output.totalRequested, node.index);
827 }
828
829 while (r != 0) {
830 if (output.isDisposed()) {
831 output.index = null;
832 return;
833 }
834
835 Node v = node.get();
836 if (v != null) {
837 Object o = leaveTransform(v.value);
838 try {
839 if (NotificationLite.accept(o, output.child)) {
840 output.index = null;
841 return;
842 }
843 } catch (Throwable err) {
844 Exceptions.throwIfFatal(err);
845 output.index = null;
846 output.dispose();
847 if (!NotificationLite.isError(o) && !NotificationLite.isComplete(o)) {
848 output.child.onError(err);
849 } else {
850 RxJavaPlugins.onError(err);
851 }
852 return;
853 }
854 e++;
855 r--;
856 node = v;
857 } else {
858 break;
859 }
860 }
861
862 if (r == 0 && output.isDisposed()) {
863 output.index = null;
864 return;
865 }
866
867 if (e != 0L) {
868 output.index = node;
869 if (!unbounded) {
870 output.produced(e);
871 }
872 }
873
874 synchronized (output) {
875 if (!output.missed) {
876 output.emitting = false;
877 return;
878 }
879 output.missed = false;
880 }
881 }
882
883 }
884
885 /**
886 * Override this to wrap the NotificationLite object into a
887 * container to be used later by truncate.
888 * @param value the value to transform into the internal representation
889 * @param terminal is this a terminal value?
890 * @return the transformed value
891 */
892 Object enterTransform(Object value, boolean terminal) {
893 return value;
894 }
895 /**
896 * Override this to unwrap the transformed value into a
897 * NotificationLite object.
898 * @param value the input value to transform to the external representation
899 * @return the transformed value
900 */
901 Object leaveTransform(Object value) {
902 return value;
903 }
904 /**
905 * Override this method to truncate a non-terminated buffer
906 * based on its current properties.
907 */
908 abstract void truncate();
909 /**
910 * Override this method to truncate a terminated buffer
911 * based on its properties (i.e., truncate but the very last node).
912 */
913 void truncateFinal() {
914 trimHead();
915 }
916 /* test */ final void collect(Collection<? super T> output) {
917 Node n = getHead();
918 for (;;) {
919 Node next = n.get();
920 if (next != null) {
921 Object o = next.value;
922 Object v = leaveTransform(o);
923 if (NotificationLite.isComplete(v) || NotificationLite.isError(v)) {
924 break;
925 }
926 output.add(NotificationLite.<T>getValue(v));
927 n = next;
928 } else {
929 break;
930 }
931 }
932 }
933 /* test */ boolean hasError() {
934 return tail.value != null && NotificationLite.isError(leaveTransform(tail.value));
935 }
936 /* test */ boolean hasCompleted() {
937 return tail.value != null && NotificationLite.isComplete(leaveTransform(tail.value));
938 }
939
940 Node getHead() {
941 return get();
942 }
943 }
944
945 /**
946 * A bounded replay buffer implementation with size limit only.
947 *
948 * @param <T> the value type
949 */
950 static final class SizeBoundReplayBuffer<T> extends BoundedReplayBuffer<T> {
951
952 private static final long serialVersionUID = -5898283885385201806L;
953
954 final int limit;
955 SizeBoundReplayBuffer(int limit, boolean eagerTruncate) {
956 super(eagerTruncate);
957 this.limit = limit;
958 }
959
960 @Override
961 void truncate() {
962 // overflow can be at most one element
963 if (size > limit) {
964 removeFirst();
965 }
966 }
967
968 // no need for final truncation because values are truncated one by one
969 }
970
971 /**
972 * Size and time bound replay buffer.
973 *
974 * @param <T> the buffered value type
975 */
976 static final class SizeAndTimeBoundReplayBuffer<T> extends BoundedReplayBuffer<T> {
977
978 private static final long serialVersionUID = 3457957419649567404L;
979 final Scheduler scheduler;
980 final long maxAge;
981 final TimeUnit unit;
982 final int limit;
983 SizeAndTimeBoundReplayBuffer(int limit, long maxAge, TimeUnit unit, Scheduler scheduler, boolean eagerTruncate) {
984 super(eagerTruncate);
985 this.scheduler = scheduler;
986 this.limit = limit;
987 this.maxAge = maxAge;
988 this.unit = unit;
989 }
990
991 @Override
992 Object enterTransform(Object value, boolean terminal) {
993 return new Timed<>(value, terminal ? Long.MAX_VALUE : scheduler.now(unit), unit);
994 }
995
996 @Override
997 Object leaveTransform(Object value) {
998 return ((Timed<?>)value).value();
999 }
1000
1001 @Override
1002 void truncate() {
1003 long timeLimit = scheduler.now(unit) - maxAge;
1004
1005 Node prev = get();
1006 Node next = prev.get();
1007
1008 int e = 0;
1009 for (;;) {
1010 if (size > 1) { // never truncate the very last item just added
1011 if (size > limit) {
1012 e++;
1013 size--;
1014 prev = next;
1015 next = next.get();
1016 } else {
1017 Timed<?> v = (Timed<?>)next.value;
1018 if (v.time() <= timeLimit) {
1019 e++;
1020 size--;
1021 prev = next;
1022 next = next.get();
1023 } else {
1024 break;
1025 }
1026 }
1027 } else {
1028 break;
1029 }
1030 }
1031 if (e != 0) {
1032 setFirst(prev);
1033 }
1034 }
1035
1036 @Override
1037 void truncateFinal() {
1038 long timeLimit = scheduler.now(unit) - maxAge;
1039
1040 Node prev = get();
1041 Node next = prev.get();
1042
1043 int e = 0;
1044 for (;;) {
1045 if (size > 1) {
1046 Timed<?> v = (Timed<?>)next.value;
1047 if (v.time() <= timeLimit) {
1048 e++;
1049 size--;
1050 prev = next;
1051 next = next.get();
1052 } else {
1053 break;
1054 }
1055 } else {
1056 break;
1057 }
1058 }
1059 if (e != 0) {
1060 setFirst(prev);
1061 }
1062 }
1063
1064 @Override
1065 Node getHead() {
1066 long timeLimit = scheduler.now(unit) - maxAge;
1067 Node prev = get();
1068 Node next = prev.get();
1069 for (;;) {
1070 if (next == null) {
1071 break;
1072 }
1073 Timed<?> v = (Timed<?>)next.value;
1074 if (NotificationLite.isComplete(v.value()) || NotificationLite.isError(v.value())) {
1075 break;
1076 }
1077 if (v.time() <= timeLimit) {
1078 prev = next;
1079 next = next.get();
1080 } else {
1081 break;
1082 }
1083 }
1084 return prev;
1085 }
1086 }
1087
1088 static final class MulticastFlowable<R, U> extends Flowable<R> {
1089 private final Supplier<? extends ConnectableFlowable<U>> connectableFactory;
1090 private final Function<? super Flowable<U>, ? extends Publisher<R>> selector;
1091
1092 MulticastFlowable(Supplier<? extends ConnectableFlowable<U>> connectableFactory, Function<? super Flowable<U>, ? extends Publisher<R>> selector) {
1093 this.connectableFactory = connectableFactory;
1094 this.selector = selector;
1095 }
1096
1097 @Override
1098 protected void subscribeActual(Subscriber<? super R> child) {
1099 ConnectableFlowable<U> cf;
1100 try {
1101 cf = ExceptionHelper.nullCheck(connectableFactory.get(), "The connectableFactory returned a null ConnectableFlowable.");
1102 } catch (Throwable e) {
1103 Exceptions.throwIfFatal(e);
1104 EmptySubscription.error(e, child);
1105 return;
1106 }
1107
1108 Publisher<R> observable;
1109 try {
1110 observable = ExceptionHelper.nullCheck(selector.apply(cf), "The selector returned a null Publisher.");
1111 } catch (Throwable e) {
1112 Exceptions.throwIfFatal(e);
1113 EmptySubscription.error(e, child);
1114 return;
1115 }
1116
1117 final SubscriberResourceWrapper<R> srw = new SubscriberResourceWrapper<>(child);
1118
1119 observable.subscribe(srw);
1120
1121 cf.connect(new DisposableConsumer(srw));
1122 }
1123
1124 final class DisposableConsumer implements Consumer<Disposable> {
1125 private final SubscriberResourceWrapper<R> srw;
1126
1127 DisposableConsumer(SubscriberResourceWrapper<R> srw) {
1128 this.srw = srw;
1129 }
1130
1131 @Override
1132 public void accept(Disposable r) {
1133 srw.setResource(r);
1134 }
1135 }
1136 }
1137
1138 static final class ReplayBufferSupplier<T> implements Supplier<ReplayBuffer<T>> {
1139
1140 final int bufferSize;
1141
1142 final boolean eagerTruncate;
1143
1144 ReplayBufferSupplier(int bufferSize, boolean eagerTruncate) {
1145 this.bufferSize = bufferSize;
1146 this.eagerTruncate = eagerTruncate;
1147 }
1148
1149 @Override
1150 public ReplayBuffer<T> get() {
1151 return new SizeBoundReplayBuffer<>(bufferSize, eagerTruncate);
1152 }
1153 }
1154
1155 static final class ScheduledReplayBufferSupplier<T> implements Supplier<ReplayBuffer<T>> {
1156 private final int bufferSize;
1157 private final long maxAge;
1158 private final TimeUnit unit;
1159 private final Scheduler scheduler;
1160
1161 final boolean eagerTruncate;
1162
1163 ScheduledReplayBufferSupplier(int bufferSize, long maxAge, TimeUnit unit, Scheduler scheduler, boolean eagerTruncate) {
1164 this.bufferSize = bufferSize;
1165 this.maxAge = maxAge;
1166 this.unit = unit;
1167 this.scheduler = scheduler;
1168 this.eagerTruncate = eagerTruncate;
1169 }
1170
1171 @Override
1172 public ReplayBuffer<T> get() {
1173 return new SizeAndTimeBoundReplayBuffer<>(bufferSize, maxAge, unit, scheduler, eagerTruncate);
1174 }
1175 }
1176
1177 static final class ReplayPublisher<T> implements Publisher<T> {
1178 private final AtomicReference<ReplaySubscriber<T>> curr;
1179 private final Supplier<? extends ReplayBuffer<T>> bufferFactory;
1180
1181 ReplayPublisher(AtomicReference<ReplaySubscriber<T>> curr, Supplier<? extends ReplayBuffer<T>> bufferFactory) {
1182 this.curr = curr;
1183 this.bufferFactory = bufferFactory;
1184 }
1185
1186 @Override
1187 public void subscribe(Subscriber<? super T> child) {
1188 // concurrent connection/disconnection may change the state,
1189 // we loop to be atomic while the child subscribes
1190 for (;;) {
1191 // get the current subscriber-to-source
1192 ReplaySubscriber<T> r = curr.get();
1193 // if there isn't one
1194 if (r == null) {
1195 ReplayBuffer<T> buf;
1196
1197 try {
1198 buf = bufferFactory.get();
1199 } catch (Throwable ex) {
1200 Exceptions.throwIfFatal(ex);
1201 EmptySubscription.error(ex, child);
1202 return;
1203 }
1204 // create a new subscriber to source
1205 ReplaySubscriber<T> u = new ReplaySubscriber<>(buf, curr);
1206 // let's try setting it as the current subscriber-to-source
1207 if (!curr.compareAndSet(null, u)) {
1208 // didn't work, maybe someone else did it or the current subscriber
1209 // to source has just finished
1210 continue;
1211 }
1212 // we won, let's use it going onwards
1213 r = u;
1214 }
1215
1216 // create the backpressure-managing producer for this child
1217 InnerSubscription<T> inner = new InnerSubscription<>(r, child);
1218 // the producer has been registered with the current subscriber-to-source so
1219 // at least it will receive the next terminal event
1220 // setting the producer will trigger the first request to be considered by
1221 // the subscriber-to-source.
1222 child.onSubscribe(inner);
1223 // we try to add it to the array of subscribers
1224 // if it fails, no worries because we will still have its buffer
1225 // so it is going to replay it for us
1226 r.add(inner);
1227
1228 if (inner.isDisposed()) {
1229 r.remove(inner);
1230 return;
1231 }
1232
1233 r.manageRequests();
1234
1235 // trigger the capturing of the current node and total requested
1236 r.buffer.replay(inner);
1237
1238 break; // NOPMD
1239 }
1240 }
1241 }
1242
1243 static final class DefaultUnboundedFactory implements Supplier<Object> {
1244 @Override
1245 public Object get() {
1246 return new UnboundedReplayBuffer<>(16);
1247 }
1248 }
1249 }