001/***************************************************
002 * Licensed under MIT No Attribution (SPDX: MIT-0) *
003 ***************************************************/
004
005package org.reactivestreams.example.unicast;
006
007import org.reactivestreams.Subscriber;
008import org.reactivestreams.Subscription;
009
010import java.util.concurrent.Executor;
011import java.util.concurrent.atomic.AtomicBoolean;
012import java.util.concurrent.ConcurrentLinkedQueue;
013
014/**
015 * AsyncSubscriber is an implementation of Reactive Streams `Subscriber`,
016 * it runs asynchronously (on an Executor), requests one element
017 * at a time, and invokes a user-defined method to process each element.
018 *
019 * NOTE: The code below uses a lot of try-catches to show the reader where exceptions can be expected, and where they are forbidden.
020 */
021public abstract class AsyncSubscriber<T> implements Subscriber<T>, Runnable {
022
023  // Signal represents the asynchronous protocol between the Publisher and Subscriber
024  private static interface Signal {}
025
026  private enum OnComplete implements Signal { Instance; }
027
028  private static class OnError implements Signal {
029    public final Throwable error;
030    public OnError(final Throwable error) { this.error = error; }
031  }
032
033  private static class OnNext<T> implements Signal {
034    public final T next;
035    public OnNext(final T next) { this.next = next; }
036  }
037
038  private static class OnSubscribe implements Signal {
039    public final Subscription subscription;
040    public OnSubscribe(final Subscription subscription) { this.subscription = subscription; }
041  }
042
043  private Subscription subscription; // Obeying rule 3.1, we make this private!
044  private boolean done; // It's useful to keep track of whether this Subscriber is done or not
045  private final Executor executor; // This is the Executor we'll use to be asynchronous, obeying rule 2.2
046
047  // Only one constructor, and it's only accessible for the subclasses
048  protected AsyncSubscriber(Executor executor) {
049    if (executor == null) throw null;
050    this.executor = executor;
051  }
052
053  // Showcases a convenience method to idempotently marking the Subscriber as "done", so we don't want to process more elements
054  // herefor we also need to cancel our `Subscription`.
055  private final void done() {
056    //On this line we could add a guard against `!done`, but since rule 3.7 says that `Subscription.cancel()` is idempotent, we don't need to.
057    done = true; // If `whenNext` throws an exception, let's consider ourselves done (not accepting more elements)
058    if (subscription != null) { // If we are bailing out before we got a `Subscription` there's little need for cancelling it.
059      try {
060        subscription.cancel(); // Cancel the subscription
061      } catch(final Throwable t) {
062        //Subscription.cancel is not allowed to throw an exception, according to rule 3.15
063        (new IllegalStateException(subscription + " violated the Reactive Streams rule 3.15 by throwing an exception from cancel.", t)).printStackTrace(System.err);
064      }
065    }
066  }
067
068  // This method is invoked when the OnNext signals arrive
069  // Returns whether more elements are desired or not, and if no more elements are desired,
070  // for convenience.
071  protected abstract boolean whenNext(final T element);
072
073  // This method is invoked when the OnComplete signal arrives
074  // override this method to implement your own custom onComplete logic.
075  protected void whenComplete() { }
076
077  // This method is invoked if the OnError signal arrives
078  // override this method to implement your own custom onError logic.
079  protected void whenError(Throwable error) { }
080
081  private final void handleOnSubscribe(final Subscription s) {
082    if (s == null) {
083      // Getting a null `Subscription` here is not valid so lets just ignore it.
084    } else if (subscription != null) { // If someone has made a mistake and added this Subscriber multiple times, let's handle it gracefully
085      try {
086        s.cancel(); // Cancel the additional subscription to follow rule 2.5
087      } catch(final Throwable t) {
088        //Subscription.cancel is not allowed to throw an exception, according to rule 3.15
089        (new IllegalStateException(s + " violated the Reactive Streams rule 3.15 by throwing an exception from cancel.", t)).printStackTrace(System.err);
090      }
091    } else {
092      // We have to assign it locally before we use it, if we want to be a synchronous `Subscriber`
093      // Because according to rule 3.10, the Subscription is allowed to call `onNext` synchronously from within `request`
094      subscription = s;
095      try {
096        // If we want elements, according to rule 2.1 we need to call `request`
097        // And, according to rule 3.2 we are allowed to call this synchronously from within the `onSubscribe` method
098        s.request(1); // Our Subscriber is unbuffered and modest, it requests one element at a time
099      } catch(final Throwable t) {
100        // Subscription.request is not allowed to throw according to rule 3.16
101        (new IllegalStateException(s + " violated the Reactive Streams rule 3.16 by throwing an exception from request.", t)).printStackTrace(System.err);
102      }
103    }
104  }
105
106  private final void handleOnNext(final T element) {
107    if (!done) { // If we aren't already done
108      if(subscription == null) { // Technically this check is not needed, since we are expecting Publishers to conform to the spec
109        // Check for spec violation of 2.1 and 1.09
110        (new IllegalStateException("Someone violated the Reactive Streams rule 1.09 and 2.1 by signalling OnNext before `Subscription.request`. (no Subscription)")).printStackTrace(System.err);
111      } else {
112        try {
113          if (whenNext(element)) {
114            try {
115              subscription.request(1); // Our Subscriber is unbuffered and modest, it requests one element at a time
116            } catch(final Throwable t) {
117              // Subscription.request is not allowed to throw according to rule 3.16
118              (new IllegalStateException(subscription + " violated the Reactive Streams rule 3.16 by throwing an exception from request.", t)).printStackTrace(System.err);
119            }
120          } else {
121            done(); // This is legal according to rule 2.6
122          }
123        } catch(final Throwable t) {
124          done();
125          try {  
126            onError(t);
127          } catch(final Throwable t2) {
128            //Subscriber.onError is not allowed to throw an exception, according to rule 2.13
129            (new IllegalStateException(this + " violated the Reactive Streams rule 2.13 by throwing an exception from onError.", t2)).printStackTrace(System.err);
130          }
131        }
132      }
133    }
134  }
135
136  // Here it is important that we do not violate 2.2 and 2.3 by calling methods on the `Subscription` or `Publisher`
137  private void handleOnComplete() {
138    if (subscription == null) { // Technically this check is not needed, since we are expecting Publishers to conform to the spec
139      // Publisher is not allowed to signal onComplete before onSubscribe according to rule 1.09
140      (new IllegalStateException("Publisher violated the Reactive Streams rule 1.09 signalling onComplete prior to onSubscribe.")).printStackTrace(System.err);
141    } else {
142      done = true; // Obey rule 2.4
143      whenComplete();
144    }
145  }
146
147  // Here it is important that we do not violate 2.2 and 2.3 by calling methods on the `Subscription` or `Publisher`
148  private void handleOnError(final Throwable error) {
149    if (subscription == null) { // Technically this check is not needed, since we are expecting Publishers to conform to the spec
150      // Publisher is not allowed to signal onError before onSubscribe according to rule 1.09
151      (new IllegalStateException("Publisher violated the Reactive Streams rule 1.09 signalling onError prior to onSubscribe.")).printStackTrace(System.err);
152    } else {
153      done = true; // Obey rule 2.4
154      whenError(error);
155    }
156  }
157
158  // We implement the OnX methods on `Subscriber` to send Signals that we will process asycnhronously, but only one at a time
159
160  @Override public final void onSubscribe(final Subscription s) {
161    // As per rule 2.13, we need to throw a `java.lang.NullPointerException` if the `Subscription` is `null`
162    if (s == null) throw null;
163
164    signal(new OnSubscribe(s));
165  }
166
167  @Override public final void onNext(final T element) {
168    // As per rule 2.13, we need to throw a `java.lang.NullPointerException` if the `element` is `null`
169    if (element == null) throw null;
170
171    signal(new OnNext<T>(element));
172  }
173
174  @Override public final void onError(final Throwable t) {
175    // As per rule 2.13, we need to throw a `java.lang.NullPointerException` if the `Throwable` is `null`
176    if (t == null) throw null;
177
178    signal(new OnError(t));
179  }
180
181  @Override public final void onComplete() {
182     signal(OnComplete.Instance);
183  }
184
185  // This `ConcurrentLinkedQueue` will track signals that are sent to this `Subscriber`, like `OnComplete` and `OnNext` ,
186  // and obeying rule 2.11
187  private final ConcurrentLinkedQueue<Signal> inboundSignals = new ConcurrentLinkedQueue<Signal>();
188
189  // We are using this `AtomicBoolean` to make sure that this `Subscriber` doesn't run concurrently with itself,
190  // obeying rule 2.7 and 2.11
191  private final AtomicBoolean on = new AtomicBoolean(false);
192
193   @SuppressWarnings("unchecked")
194   @Override public final void run() {
195    if(on.get()) { // establishes a happens-before relationship with the end of the previous run
196      try {
197        final Signal s = inboundSignals.poll(); // We take a signal off the queue
198        if (!done) { // If we're done, we shouldn't process any more signals, obeying rule 2.8
199          // Below we simply unpack the `Signal`s and invoke the corresponding methods
200          if (s instanceof OnNext<?>)
201            handleOnNext(((OnNext<T>)s).next);
202          else if (s instanceof OnSubscribe)
203            handleOnSubscribe(((OnSubscribe)s).subscription);
204          else if (s instanceof OnError) // We are always able to handle OnError, obeying rule 2.10
205            handleOnError(((OnError)s).error);
206          else if (s == OnComplete.Instance) // We are always able to handle OnComplete, obeying rule 2.9
207            handleOnComplete();
208        }
209      } finally {
210        on.set(false); // establishes a happens-before relationship with the beginning of the next run
211        if(!inboundSignals.isEmpty()) // If we still have signals to process
212          tryScheduleToExecute(); // Then we try to schedule ourselves to execute again
213      }
214    }
215  }
216
217  // What `signal` does is that it sends signals to the `Subscription` asynchronously
218  private void signal(final Signal signal) {
219    if (inboundSignals.offer(signal)) // No need to null-check here as ConcurrentLinkedQueue does this for us
220      tryScheduleToExecute(); // Then we try to schedule it for execution, if it isn't already
221  }
222
223  // This method makes sure that this `Subscriber` is only executing on one Thread at a time
224  private final void tryScheduleToExecute() {
225    if(on.compareAndSet(false, true)) {
226      try {
227        executor.execute(this);
228      } catch(Throwable t) { // If we can't run on the `Executor`, we need to fail gracefully and not violate rule 2.13
229        if (!done) {
230          try {
231            done(); // First of all, this failure is not recoverable, so we need to cancel our subscription
232          } finally {
233            inboundSignals.clear(); // We're not going to need these anymore
234            // This subscription is cancelled by now, but letting the Subscriber become schedulable again means
235            // that we can drain the inboundSignals queue if anything arrives after clearing
236            on.set(false);
237          }
238        }
239      }
240    }
241  }
242}