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

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

Go to download

Easy Redis Java client and Real-Time Data Platform. Valkey compatible. Sync/Async/RxJava3/Reactive API. Client side caching. Over 50 Redis based Java objects and services: JCache API, Apache Tomcat, Hibernate, Spring, Set, Multimap, SortedSet, Map, List, Queue, Deque, Semaphore, Lock, AtomicLong, Map Reduce, Bloom filter, Scheduler, RPC

The newest version!
/*
 * Copyright (c) 2016-2023 VMware Inc. or its affiliates, 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
 *
 *   https://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.Objects;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;

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

/**
 * Emits the last value from upstream only if there were no newer values emitted
 * during the time window provided by a publisher for that particular last value.
 *
 * @param  the source value type
 * @param  the value type of the duration publisher
 *
 * @see Reactive-Streams-Commons
 */
final class FluxSampleTimeout extends InternalFluxOperator {

	final Function> throttler;

	final Supplier> queueSupplier;

	FluxSampleTimeout(Flux source,
			Function> throttler,
			Supplier> queueSupplier) {
		super(source);
		this.throttler = Objects.requireNonNull(throttler, "throttler");
		this.queueSupplier = Objects.requireNonNull(queueSupplier, "queueSupplier");
	}

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

	@Override
	@SuppressWarnings({"rawtypes", "unchecked"})
	public CoreSubscriber subscribeOrReturn(CoreSubscriber actual) {
		Queue> q = (Queue) queueSupplier.get();

		SampleTimeoutMain main = new SampleTimeoutMain<>(actual, throttler, q);

		actual.onSubscribe(main);

		return main;
	}

	@Override
	public Object scanUnsafe(Attr key) {
		if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
		return super.scanUnsafe(key);
	}

	static final class SampleTimeoutMainimplements InnerOperator {

		final Function> throttler;
		final Queue>             queue;
		final CoreSubscriber                   actual;
		final Context                                     ctx;

		volatile Subscription s;

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

		volatile Subscription other;
		@SuppressWarnings("rawtypes")
		static final AtomicReferenceFieldUpdater
				OTHER = AtomicReferenceFieldUpdater.newUpdater(SampleTimeoutMain.class,
				Subscription.class,
				"other");

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

		volatile int wip;
		@SuppressWarnings("rawtypes")
		static final AtomicIntegerFieldUpdater WIP =
				AtomicIntegerFieldUpdater.newUpdater(SampleTimeoutMain.class, "wip");

		volatile Throwable error;
		@SuppressWarnings("rawtypes")
		static final AtomicReferenceFieldUpdater ERROR =
				AtomicReferenceFieldUpdater.newUpdater(SampleTimeoutMain.class,
						Throwable.class,
						"error");

		volatile boolean done;

		volatile boolean cancelled;

		volatile long index;
		@SuppressWarnings("rawtypes")
		static final AtomicLongFieldUpdater INDEX =
				AtomicLongFieldUpdater.newUpdater(SampleTimeoutMain.class, "index");

		SampleTimeoutMain(CoreSubscriber actual,
				Function> throttler,
				Queue> queue) {
			this.actual = actual;
			this.ctx = actual.currentContext();
			this.throttler = throttler;
			this.queue = queue;
		}

		@Override
		public Stream inners() {
			return Stream.of(Scannable.from(other));
		}

		@Override
		@Nullable
		public Object scanUnsafe(Attr key) {
			if (key == Attr.TERMINATED) return done;
			if (key == Attr.CANCELLED) return cancelled;
			if (key == Attr.PARENT) return s;
			if (key == Attr.ERROR) return error;
			if (key == Attr.REQUESTED_FROM_DOWNSTREAM) return requested;
			if (key == Attr.BUFFERED) return queue.size();
			if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;

			return InnerOperator.super.scanUnsafe(key);
		}

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

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

		@Override
		public void cancel() {
			if (!cancelled) {
				cancelled = true;
				Operators.terminate(S, this);
				Operators.terminate(OTHER, this);
				Operators.onDiscardQueueWithClear(queue, ctx, SampleTimeoutOther::toStream);
			}
		}

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

		@Override
		public void onNext(T t) {
			long idx = INDEX.incrementAndGet(this);

			if (!Operators.set(OTHER, this, Operators.emptySubscription())) {
				return;
			}

			Publisher p;

			try {
				p = Objects.requireNonNull(throttler.apply(t),
						"throttler returned a null publisher");
			}
			catch (Throwable e) {
				onError(Operators.onOperatorError(s, e, t, ctx));
				return;
			}

			SampleTimeoutOther os = new SampleTimeoutOther<>(this, t, idx);

			if (Operators.replace(OTHER, this, os)) {
				p = Operators.toFluxOrMono(p);
				p.subscribe(os);
			}
		}

		void error(Throwable t) {
			if (Exceptions.addThrowable(ERROR, this, t)) {
				done = true;
				drain();
			}
			else {
				Operators.onErrorDropped(t, ctx);
			}
		}

		@Override
		public void onError(Throwable t) {
			Operators.terminate(OTHER, this);

			error(t);
		}

		@Override
		public void onComplete() {
			Subscription o = other;
			if (o instanceof FluxSampleTimeout.SampleTimeoutOther) {
				SampleTimeoutOther os = (SampleTimeoutOther) o;
				os.cancel();
				os.onComplete();
			}
			done = true;
			drain();
		}

		void otherNext(SampleTimeoutOther other) {
			queue.offer(other);
			drain();
		}

		void otherError(long idx, Throwable e) {
			if (idx == index) {
				Operators.terminate(S, this);

				error(e);
			}
			else {
				Operators.onErrorDropped(e, ctx);
			}
		}

		void drain() {
			if (WIP.getAndIncrement(this) != 0) {
				return;
			}

			final Subscriber a = actual;
			final Queue> q = queue;

			int missed = 1;

			for (; ; ) {

				for (; ; ) {
					boolean d = done;

					SampleTimeoutOther o = q.poll();

					boolean empty = o == null;

					if (checkTerminated(d, empty, a, q)) {
						return;
					}

					if (empty) {
						break;
					}

					if (o.index == index) {
						long r = requested;
						if (r != 0) {
							a.onNext(o.value);
							if (r != Long.MAX_VALUE) {
								REQUESTED.decrementAndGet(this);
							}
						}
						else {
							cancel();

							Operators.onDiscardQueueWithClear(q, ctx, SampleTimeoutOther::toStream);

							Throwable e = Exceptions.failWithOverflow(
									"Could not emit value due to lack of requests");
							Exceptions.addThrowable(ERROR, this, e);
							e = Exceptions.terminate(ERROR, this);

							a.onError(e);
							return;
						}
					}
				}

				missed = WIP.addAndGet(this, -missed);
				if (missed == 0) {
					break;
				}
			}
		}

		boolean checkTerminated(boolean d, boolean empty, Subscriber a, Queue> q) {
			if (cancelled) {
				Operators.onDiscardQueueWithClear(q, ctx, SampleTimeoutOther::toStream);
				return true;
			}
			if (d) {
				Throwable e = Exceptions.terminate(ERROR, this);
				if (e != null && e != Exceptions.TERMINATED) {
					cancel();

					Operators.onDiscardQueueWithClear(q, ctx, SampleTimeoutOther::toStream);

					a.onError(e);
					return true;
				}
				else if (empty) {

					a.onComplete();
					return true;
				}
			}
			return false;
		}
	}

	static final class SampleTimeoutOther extends Operators.DeferredSubscription
			implements InnerConsumer {

		final SampleTimeoutMain main;

		final T value;

		final long index;

		volatile int once;
		@SuppressWarnings("rawtypes")
		static final AtomicIntegerFieldUpdater ONCE =
				AtomicIntegerFieldUpdater.newUpdater(SampleTimeoutOther.class, "once");

		SampleTimeoutOther(SampleTimeoutMain main, T value, long index) {
			this.main = main;
			this.value = value;
			this.index = index;
		}

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

		@Override
		@Nullable
		public Object scanUnsafe(Attr key) {
			if (key == Attr.TERMINATED) return once == 1;
			if (key == Attr.ACTUAL) return main;
			if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;

			return super.scanUnsafe(key);
		}

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

		@Override
		public void onNext(U t) {
			if (ONCE.compareAndSet(this, 0, 1)) {
				cancel();

				main.otherNext(this);
			}
		}

		@Override
		public void onError(Throwable t) {
			if (ONCE.compareAndSet(this, 0, 1)) {
				main.otherError(index, t);
			}
			else {
				Operators.onErrorDropped(t, main.currentContext());
			}
		}

		@Override
		public void onComplete() {
			if (ONCE.compareAndSet(this, 0, 1)) {
				main.otherNext(this);
			}
		}

		final Stream toStream() {
			return Stream.of(value);
		}

	}
}