-
Notifications
You must be signed in to change notification settings - Fork 181
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Motivation: Publisher.replay provides the ability to keep state that is preserved for multiple subscribers and across resubscribes.
- Loading branch information
1 parent
670cc93
commit fd9369c
Showing
10 changed files
with
1,295 additions
and
106 deletions.
There are no files selected for viewing
225 changes: 162 additions & 63 deletions
225
...cetalk-concurrent-api/src/main/java/io/servicetalk/concurrent/api/MulticastPublisher.java
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
...icetalk-concurrent-api/src/main/java/io/servicetalk/concurrent/api/ReplayAccumulator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
/* | ||
* Copyright © 2023 Apple Inc. and the ServiceTalk project authors | ||
* | ||
* 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 io.servicetalk.concurrent.api; | ||
|
||
import io.servicetalk.concurrent.PublisherSource.Subscriber; | ||
|
||
import java.util.function.Consumer; | ||
import javax.annotation.Nullable; | ||
|
||
/** | ||
* Accumulates signals for the {@link Publisher} replay operator. | ||
* @param <T> The type of data to accumulate. | ||
*/ | ||
public interface ReplayAccumulator<T> { | ||
/** | ||
* Called on each {@link Subscriber#onNext(Object)} and intended to accumulate the signal so that new | ||
* {@link Subscriber}s will see this value via {@link #deliverAccumulation(Consumer)}. | ||
* <p> | ||
* This method won't be called concurrently, but should return quickly to minimize performance impacts. | ||
* @param t An {@link Subscriber#onNext(Object)} to accumulate. | ||
*/ | ||
void accumulate(@Nullable T t); | ||
|
||
/** | ||
* Called to deliver the signals from {@link #accumulate(Object)} to new {@code consumer}. | ||
* @param consumer The consumer of the signals previously aggregated via {@link #accumulate(Object)}. | ||
*/ | ||
void deliverAccumulation(Consumer<T> consumer); | ||
|
||
/** | ||
* Called if the accumulation can be cancelled and any asynchronous resources can be cleaned up (e.g. timers). | ||
*/ | ||
default void cancelAccumulation() { | ||
} | ||
} |
175 changes: 175 additions & 0 deletions
175
servicetalk-concurrent-api/src/main/java/io/servicetalk/concurrent/api/ReplayPublisher.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
/* | ||
* Copyright © 2023 Apple Inc. and the ServiceTalk project authors | ||
* | ||
* 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 io.servicetalk.concurrent.api; | ||
|
||
import io.servicetalk.concurrent.internal.TerminalNotification; | ||
|
||
import java.util.concurrent.atomic.AtomicLongFieldUpdater; | ||
import java.util.function.Function; | ||
import java.util.function.Supplier; | ||
import javax.annotation.Nullable; | ||
|
||
import static io.servicetalk.concurrent.api.SubscriberApiUtils.unwrapNullUnchecked; | ||
import static io.servicetalk.concurrent.api.SubscriberApiUtils.wrapNull; | ||
import static io.servicetalk.concurrent.internal.ConcurrentUtils.releaseLock; | ||
import static io.servicetalk.concurrent.internal.ConcurrentUtils.tryAcquireLock; | ||
import static io.servicetalk.concurrent.internal.TerminalNotification.complete; | ||
import static io.servicetalk.concurrent.internal.TerminalNotification.error; | ||
import static java.util.Objects.requireNonNull; | ||
|
||
final class ReplayPublisher<T> extends MulticastPublisher<T> { | ||
@SuppressWarnings("rawtypes") | ||
private static final AtomicLongFieldUpdater<ReplayPublisher.ReplayState> signalQueuedUpdater = | ||
AtomicLongFieldUpdater.newUpdater(ReplayPublisher.ReplayState.class, "signalsQueued"); | ||
private final Supplier<ReplayAccumulator<T>> accumulatorSupplier; | ||
|
||
private ReplayPublisher( | ||
Publisher<T> original, Supplier<ReplayAccumulator<T>> accumulatorSupplier, int minSubscribers, | ||
boolean cancelUpstream, int maxQueueSize, Function<Throwable, Completable> terminalResubscribe) { | ||
super(original, minSubscribers, false, cancelUpstream, maxQueueSize, terminalResubscribe); | ||
this.accumulatorSupplier = requireNonNull(accumulatorSupplier); | ||
} | ||
|
||
static <T> MulticastPublisher<T> newReplayPublisher( | ||
Publisher<T> original, Supplier<ReplayAccumulator<T>> accumulatorSupplier, int minSubscribers, | ||
boolean cancelUpstream, int maxQueueSize, Function<Throwable, Completable> terminalResubscribe) { | ||
ReplayPublisher<T> publisher = new ReplayPublisher<>(original, accumulatorSupplier, minSubscribers, | ||
cancelUpstream, minSubscribers, terminalResubscribe); | ||
publisher.resetState(maxQueueSize, minSubscribers); | ||
return publisher; | ||
} | ||
|
||
@Override | ||
void resetState(int maxQueueSize, int minSubscribers) { | ||
state = new ReplayState(maxQueueSize, minSubscribers, accumulatorSupplier.get()); | ||
} | ||
|
||
private final class ReplayState extends MulticastPublisher<T>.State { | ||
private final ReplayAccumulator<T> accumulator; | ||
/** | ||
* We could check {@link #subscriptionEvents} is empty, but there are events outside of {@link Subscriber} | ||
* signals in this queue that we don't care about in terms of preserving order so we keep this count instead | ||
* to only queue when necessary. | ||
*/ | ||
volatile long signalsQueued; | ||
|
||
ReplayState(final int maxQueueSize, final int minSubscribers, | ||
ReplayAccumulator<T> accumulator) { | ||
super(maxQueueSize, minSubscribers); | ||
this.accumulator = requireNonNull(accumulator); | ||
} | ||
|
||
@Override | ||
public void onNext(@Nullable final T t) { | ||
// signalsQueued must be 0 or else items maybe delivered out of order. The value will only be increased | ||
// on the Subscriber thread (no concurrency) and decreased on the draining thread. Optimistically check | ||
// the value here and worst case if the queue has been drained of signals and this thread hasn't yet | ||
// observed the value we will queue but still see correct ordering. | ||
if (signalsQueued == 0 && tryAcquireLock(subscriptionLockUpdater, this)) { | ||
try { | ||
// All subscribers must either see this direct onNext signal, or see it through the accumulator. | ||
// Therefore, we accumulate and deliver onNext while locked to avoid either delivering the signal | ||
// twice (accumulator, addSubscriber, and onNext) or not at all (missed due to concurrency). | ||
accumulator.accumulate(t); | ||
super.onNext(t); | ||
} finally { | ||
if (!releaseLock(subscriptionLockUpdater, this)) { | ||
processSubscriptionEvents(); | ||
} | ||
} | ||
} else { | ||
queueOnNext(t); | ||
} | ||
} | ||
|
||
@Override | ||
public void onError(final Throwable t) { | ||
if (signalsQueued == 0 && tryAcquireLock(subscriptionLockUpdater, this)) { | ||
try { | ||
super.onError(t); | ||
} finally { | ||
if (!releaseLock(subscriptionLockUpdater, this)) { | ||
processSubscriptionEvents(); | ||
} | ||
} | ||
} else { | ||
queueTerminal(error(t)); | ||
} | ||
} | ||
|
||
@Override | ||
public void onComplete() { | ||
if (signalsQueued == 0 && tryAcquireLock(subscriptionLockUpdater, this)) { | ||
try { | ||
super.onComplete(); | ||
} finally { | ||
if (!releaseLock(subscriptionLockUpdater, this)) { | ||
processSubscriptionEvents(); | ||
} | ||
} | ||
} else { | ||
queueTerminal(complete()); | ||
} | ||
} | ||
|
||
@Override | ||
void processOnNextEvent(Object wrapped) { | ||
// subscriptionLockUpdater is held | ||
signalQueuedUpdater.decrementAndGet(this); | ||
final T unwrapped = unwrapNullUnchecked(wrapped); | ||
accumulator.accumulate(unwrapped); | ||
super.onNext(unwrapped); | ||
} | ||
|
||
@Override | ||
void processTerminal(TerminalNotification terminalNotification) { | ||
// subscriptionLockUpdater is held | ||
signalQueuedUpdater.decrementAndGet(this); | ||
if (terminalNotification.cause() != null) { | ||
super.onError(terminalNotification.cause()); | ||
} else { | ||
super.onComplete(); | ||
} | ||
} | ||
|
||
@Override | ||
void processSubscribeEvent(MulticastFixedSubscriber<T> subscriber) { | ||
// subscriptionLockUpdater is held | ||
super.processSubscribeEvent(subscriber); | ||
// It is safe to call onNext before onSubscribe as the base class expects onSubscribe to be async and will | ||
// queue/reorder events to preserve ReactiveStreams semantics. | ||
accumulator.deliverAccumulation(subscriber::onNext); | ||
} | ||
|
||
@Override | ||
void upstreamCancelled() { | ||
// subscriptionLockUpdater is held | ||
accumulator.cancelAccumulation(); | ||
} | ||
|
||
private void queueOnNext(@Nullable T t) { | ||
signalQueuedUpdater.incrementAndGet(this); | ||
subscriptionEvents.add(wrapNull(t)); | ||
processSubscriptionEvents(); | ||
} | ||
|
||
private void queueTerminal(TerminalNotification terminalNotification) { | ||
signalQueuedUpdater.incrementAndGet(this); | ||
subscriptionEvents.add(terminalNotification); | ||
processSubscriptionEvents(); | ||
} | ||
} | ||
} |
Oops, something went wrong.