All Downloads are FREE. Search and download functionalities are using the official Maven repository.

reactor.core.publisher.FluxBufferBoundary Maven / Gradle / Ivy

/*
 * Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package reactor.core.publisher;

import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.Supplier;

import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Exceptions;
import reactor.util.annotation.Nullable;
import reactor.util.context.Context;

/**
 * Buffers elements into custom collections where the buffer boundary is signalled
 * by another publisher.
 *
 * @param  the source value type
 * @param  the element type of the boundary publisher (irrelevant)
 * @param  the output collection type
 *
 * @see Reactive-Streams-Commons
 */
final class FluxBufferBoundary>
		extends FluxOperator {

	final Publisher other;

	final Supplier bufferSupplier;

	FluxBufferBoundary(Flux source,
			Publisher other,
			Supplier bufferSupplier) {
		super(source);
		this.other = Objects.requireNonNull(other, "other");
		this.bufferSupplier = Objects.requireNonNull(bufferSupplier, "bufferSupplier");
	}

	@Override
	public int getPrefetch() {
		return Integer.MAX_VALUE;
	}

	@Override
	public void subscribe(CoreSubscriber actual) {
		C buffer;

		try {
			buffer = Objects.requireNonNull(bufferSupplier.get(),
					"The bufferSupplier returned a null buffer");
		}
		catch (Throwable e) {
			Operators.error(actual, Operators.onOperatorError(e, actual.currentContext()));
			return;
		}

		BufferBoundaryMain parent =
				new BufferBoundaryMain<>(
						source instanceof FluxInterval ?
								actual : Operators.serialize(actual),
						buffer, bufferSupplier);

		actual.onSubscribe(parent);

		other.subscribe(parent.other);

		source.subscribe(parent);
	}

	static final class BufferBoundaryMain>
			implements InnerOperator {

		final Supplier           bufferSupplier;
		final CoreSubscriber actual;

		final BufferBoundaryOther other;

		C buffer;

		volatile Subscription s;

		@SuppressWarnings("rawtypes")
		static final AtomicReferenceFieldUpdater S =
				AtomicReferenceFieldUpdater.newUpdater(BufferBoundaryMain.class,
						Subscription.class,
						"s");

		volatile long requested;
		@SuppressWarnings("rawtypes")
		static final AtomicLongFieldUpdater REQUESTED =
				AtomicLongFieldUpdater.newUpdater(BufferBoundaryMain.class, "requested");

		BufferBoundaryMain(CoreSubscriber actual,
				C buffer,
				Supplier bufferSupplier) {
			this.actual = actual;
			this.buffer = buffer;
			this.bufferSupplier = bufferSupplier;
			this.other = new BufferBoundaryOther<>(this);
		}

		@Override
		public CoreSubscriber actual() {
			return actual;
		}

		@Override
		@Nullable
		public Object scanUnsafe(Attr key) {
			if (key == Attr.PARENT) return s;
			if (key == Attr.CANCELLED) return s == Operators.cancelledSubscription();
			if (key == Attr.CAPACITY) {
				C buffer = this.buffer;
				return buffer != null ? buffer.size() : 0;
			}
			if (key == Attr.PREFETCH) return Integer.MAX_VALUE;
			if (key == Attr.REQUESTED_FROM_DOWNSTREAM) return requested;

			return InnerOperator.super.scanUnsafe(key);
		}

		@Override
		public void request(long n) {
			if (Operators.validate(n)) {
				Operators.addCap(REQUESTED, this, n);
			}
		}

		@Override
		public void cancel() {
			Operators.terminate(S, this);
			other.cancel();
		}

		@Override
		public void onSubscribe(Subscription s) {
			if (Operators.setOnce(S, this, s)) {
				s.request(Long.MAX_VALUE);
			}
		}

		@Override
		public void onNext(T t) {
			synchronized (this) {
				C b = buffer;
				if (b != null) {
					b.add(t);
					return;
				}
			}

			Operators.onNextDropped(t, actual.currentContext());
		}

		@Override
		public void onError(Throwable t) {
			if(Operators.setTerminated(S, this)) {
				synchronized (this) {
					buffer = null;
				}

				other.cancel();
				actual.onError(t);
				return;
			}
			Operators.onErrorDropped(t, actual.currentContext());
		}

		@Override
		public void onComplete() {
			if(Operators.setTerminated(S, this)) {
				C b;
				synchronized (this) {
					b = buffer;
					buffer = null;
				}

				other.cancel();
				if (!b.isEmpty()) {
					if (emit(b)) {
						actual.onComplete();
					}
				}
				else {
					actual.onComplete();
				}
			}
		}
		void otherComplete() {
			Subscription s = S.getAndSet(this, Operators.cancelledSubscription());
			if(s != Operators.cancelledSubscription()) {
				C b;
				synchronized (this) {
					b = buffer;
					buffer = null;
				}

				if(s != null){
					s.cancel();
				}

				if (b != null && !b.isEmpty()) {
					if (emit(b)) {
						actual.onComplete();
					}
				}
				else {
					actual.onComplete();
				}
			}
		}

		void otherError(Throwable t){
			Subscription s = S.getAndSet(this, Operators.cancelledSubscription());
			if(s != Operators.cancelledSubscription()) {
				synchronized (this) {
					buffer = null;
				}

				if(s != null){
					s.cancel();
				}

				actual.onError(t);
				return;
			}
			Operators.onErrorDropped(t, actual.currentContext());
		}

		void otherNext() {
			C c;

			try {
				c = Objects.requireNonNull(bufferSupplier.get(),
						"The bufferSupplier returned a null buffer");
			}
			catch (Throwable e) {
				otherError(Operators.onOperatorError(other, e, actual.currentContext()));
				return;
			}

			C b;
			synchronized (this) {
				b = buffer;
				buffer = c;
			}

			if (b == null || b.isEmpty()) {
				return;
			}

			emit(b);
		}

		boolean emit(C b) {
			long r = requested;
			if (r != 0L) {
				actual.onNext(b);
				if (r != Long.MAX_VALUE) {
					REQUESTED.decrementAndGet(this);
				}
				return true;
			}
			else {
				actual.onError(Operators.onOperatorError(this, Exceptions
						.failWithOverflow(), b, actual.currentContext()));

				return false;
			}
		}
	}

	static final class BufferBoundaryOther extends Operators.DeferredSubscription
			implements InnerConsumer {

		final BufferBoundaryMain main;

		BufferBoundaryOther(BufferBoundaryMain main) {
			this.main = main;
		}

		@Override
		public void onSubscribe(Subscription s) {
			if (set(s)) {
				s.request(Long.MAX_VALUE);
			}
		}

		@Override
		public Context currentContext() {
			return main.currentContext();
		}

		@Override
		@Nullable
		public Object scanUnsafe(Attr key) {
			if (key == Attr.ACTUAL) {
				return main;
			}
			return super.scanUnsafe(key);
		}

		@Override
		public void onNext(U t) {
			main.otherNext();
		}

		@Override
		public void onError(Throwable t) {
			main.otherError(t);
		}

		@Override
		public void onComplete() {
			main.otherComplete();
		}
	}
}