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