Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ successfully. If the `Future` is completed with a failure the stream is failed.

Unlike @ref:[futureSink](futureSink.md) and @ref:[lazyFutureSink](lazyFutureSink.md), this operator materializes the inner sink as soon as the future
completes, even if no elements have arrived yet. This means empty streams complete normally rather than failing
with `NeverMaterializedException`. At most one element that arrives before the future completes is buffered.
with `NeverMaterializedException`. At most one element is prefetched before the inner sink requests it.
If upstream completes with an element buffered, that element is delivered on demand before completion.

The materialized future value is completed with the materialized value of the inner sink once it has been
materialized, or failed if the future itself fails or if materialization of the inner sink fails. Upstream
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,22 @@ package org.apache.pekko.stream.scaladsl
import scala.concurrent.{ Future, Promise }

import org.apache.pekko
import pekko.Done
import pekko.stream.AbruptStageTerminationException
import pekko.stream.Attributes
import pekko.stream.Inlet
import pekko.stream.Materializer
import pekko.stream.Outlet
import pekko.stream.SinkShape
import pekko.stream.SourceShape
import pekko.stream.stage.AsyncCallback
import pekko.stream.stage.GraphStageLogic
import pekko.stream.stage.GraphStageWithMaterializedValue
import pekko.stream.stage.InHandler
import pekko.stream.stage.OutHandler
import pekko.stream.testkit.StreamSpec
import pekko.stream.testkit.Utils._
import pekko.stream.{ AbruptStageTerminationException, Materializer }
import pekko.stream.testkit.scaladsl.StreamTestKit.assertAllStagesStopped

class EagerFutureSinkSpec extends StreamSpec("""
pekko.stream.materializer.initial-input-buffer-size = 1
Expand All @@ -31,6 +44,82 @@ class EagerFutureSinkSpec extends StreamSpec("""

val ex = TE("")

private final class SourceControl(
val firstPull: Future[Done],
signal: AsyncCallback[(Option[Int], Boolean)]) {
def send(value: Int, last: Boolean = false): Future[Done] =
signal.invokeWithFeedback((Some(value), last))

def finish(): Future[Done] = signal.invokeWithFeedback((None, true))
}

private final class ControlledSource extends GraphStageWithMaterializedValue[SourceShape[Int], SourceControl] {
private val out = Outlet[Int]("eagerSinkTestSource.out")
override val shape: SourceShape[Int] = SourceShape(out)

override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, SourceControl) = {
val firstPull = Promise[Done]()
class Logic extends GraphStageLogic(shape) with OutHandler {
val signal: AsyncCallback[(Option[Int], Boolean)] = getAsyncCallback {
case (element, last) =>
element.foreach(push(out, _))
if (last) completeStage()
}
override def onPull(): Unit = {
firstPull.trySuccess(Done)
()
}
setHandler(out, this)
}
val logic = new Logic
(logic, new SourceControl(firstPull.future, logic.signal))
}
}

private final class SinkControl(val demand: AsyncCallback[Unit], val received: Future[Int],
val completed: Future[Done])

private final class ControlledSink extends GraphStageWithMaterializedValue[SinkShape[Int], SinkControl] {
private val in = Inlet[Int]("eagerSinkTestSink.in")
override val shape: SinkShape[Int] = SinkShape(in)

override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, SinkControl) = {
val received = Promise[Int]()
val completed = Promise[Done]()
class Logic extends GraphStageLogic(shape) with InHandler {
val demand: AsyncCallback[Unit] = getAsyncCallback(_ => pull(in))
override def onPush(): Unit = {
received.success(grab(in))
()
}
override def onUpstreamFinish(): Unit = {
completed.success(Done)
completeStage()
}
override def onUpstreamFailure(ex: Throwable): Unit = {
received.tryFailure(ex)
completed.tryFailure(ex)
failStage(ex)
}
setHandler(in, this)
}
val logic = new Logic
(logic, new SinkControl(logic.demand, received.future, completed.future))
}
}

private def startHandoff(): (SourceControl, SinkControl) = {
val sinkPromise = Promise[Sink[Int, SinkControl]]()
// No async boundary: both controlled stages and the eager sink's substream use the same
// interpreter actor. It processes the current graph events before the next test callback.
val (upstream, inner) = Source.fromGraph(new ControlledSource)
.toMat(Sink.eagerFutureSink(sinkPromise.future))(Keep.both)
.run()
upstream.firstPull.futureValue shouldBe Done
sinkPromise.success(Sink.fromGraph(new ControlledSink))
(upstream, inner.futureValue)
}

"Sink.eagerFutureSink" must {

"work with an already-completed future" in {
Expand All @@ -53,6 +142,35 @@ class EagerFutureSinkSpec extends StreamSpec("""
result.futureValue shouldBe Seq(1, 2, 3)
}

"reuse the outstanding prefetch when the inner sink requests first" in assertAllStagesStopped {
val (upstream, inner) = startHandoff()

inner.demand.invokeWithFeedback(()).futureValue shouldBe Done
upstream.send(1).futureValue shouldBe Done
inner.received.futureValue shouldBe 1
upstream.finish().futureValue shouldBe Done
inner.completed.futureValue shouldBe Done
}

"buffer the prefetched element when it arrives before the inner sink requests" in assertAllStagesStopped {
val (upstream, inner) = startHandoff()

upstream.send(2).futureValue shouldBe Done
inner.demand.invokeWithFeedback(()).futureValue shouldBe Done
inner.received.futureValue shouldBe 2
upstream.finish().futureValue shouldBe Done
inner.completed.futureValue shouldBe Done
}

"deliver a buffered last element before completing the inner sink" in assertAllStagesStopped {
val (upstream, inner) = startHandoff()

upstream.send(3, last = true).futureValue shouldBe Done
inner.demand.invokeWithFeedback(()).futureValue shouldBe Done
inner.received.futureValue shouldBe 3
inner.completed.futureValue shouldBe Done
}

"handle an empty stream with an already-completed future" in {
val result = Source
.empty[Int]
Expand Down
16 changes: 12 additions & 4 deletions stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala
Original file line number Diff line number Diff line change
Expand Up @@ -709,10 +709,18 @@ import org.reactivestreams.Subscriber
setHandler(
in,
new InHandler {
override def onPush(): Unit = subOutlet.push(grab(in))
override def onPush(): Unit = {
val elem = grab(in)
// The initial pull may be fulfilled before the newly materialized sink requests an element.
if (subOutlet.isAvailable) subOutlet.push(elem)
else bufferedElement = OptionVal.Some(elem)
}
override def onUpstreamFinish(): Unit = {
subOutlet.complete()
completeStage()
upstreamClosed = true
if (bufferedElement.isEmpty) {
subOutlet.complete()
completeStage()
}
}
override def onUpstreamFailure(ex: Throwable): Unit = {
subOutlet.fail(ex)
Expand All @@ -734,7 +742,7 @@ import org.reactivestreams.Subscriber
if (upstreamClosed) {
subOutlet.complete()
completeStage()
} else if (!isClosed(in)) {
} else if (!isClosed(in) && !hasBeenPulled(in)) {
pull(in)
}
}
Expand Down