Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Graceful Shutdown #55

Merged
merged 5 commits into from
Nov 19, 2019
Merged
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
7 changes: 7 additions & 0 deletions src/main/scala/zio/kafka/client/Consumer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ class Consumer private (
): BlockingTask[Map[TopicPartition, Long]] =
consumer.withConsumer(_.endOffsets(partitions.asJava, timeout.asJava).asScala.mapValues(_.longValue()).toMap)

/**
* Stops consumption of data, drains buffered records, and ends the attached
* streams while still serving commit requests.
*/
def stopConsumption: UIO[Unit] =
runloop.deps.gracefulShutdown

def listTopics(timeout: Duration = Duration.Infinity): BlockingTask[Map[String, List[PartitionInfo]]] =
consumer.withConsumer(_.listTopics(timeout.asJava).asScala.mapValues(_.asScala.toList).toMap)

Expand Down
119 changes: 83 additions & 36 deletions src/main/scala/zio/kafka/client/Runloop.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ object Runloop {
partitions: Queue[Take[Throwable, (TopicPartition, ZStreamChunk[Any, Throwable, ByteArrayCommittableRecord])]],
rebalancingRef: Ref[Boolean],
rebalanceListener: ConsumerRebalanceListener,
diagnostics: Diagnostics
diagnostics: Diagnostics,
shutdownRef: Ref[Boolean]
) {
def commit(cmd: Command.Commit) = commitQueue.offer(cmd).unit
def commits = ZStream.fromQueue(commitQueue)
Expand All @@ -60,6 +61,14 @@ object Runloop {
partitions.offer(Take.Value(tp -> data)).unit

def emitIfEnabledDiagnostic(event: DiagnosticEvent) = diagnostics.emitIfEnabled(event)

val isShutdown = shutdownRef.get

def gracefulShutdown: UIO[Unit] =
for {
shutdown <- shutdownRef.modify((_, true))
_ <- partitions.offer(Take.End).when(!shutdown)
} yield ()
}
object Deps {
def make(
Expand All @@ -76,6 +85,12 @@ object Runloop {
.unbounded[
Take[Throwable, (TopicPartition, ZStreamChunk[Any, Throwable, ByteArrayCommittableRecord])]
]
.map { queue =>
queue.mapM {
case Take.End => queue.shutdown.as(Take.End)
case x => ZIO.succeed(x)
}
}
.toManaged(_.shutdown)
listener <- ZIO
.runtime[Blocking]
Expand All @@ -100,6 +115,7 @@ object Runloop {
}
}
.toManaged_
shutdownRef <- Ref.make(false).toManaged_
} yield Deps(
consumer,
pollFrequency,
Expand All @@ -109,7 +125,8 @@ object Runloop {
partitions,
rebalancingRef,
listener,
diagnostics
diagnostics,
shutdownRef
)
}

Expand Down Expand Up @@ -320,38 +337,44 @@ object Runloop {
// is empty because pattern subscriptions start out as empty.
case _: IllegalStateException => null
}
deps.isShutdown.flatMap { shutdown =>
if (shutdown)
ZIO.effectTotal(deps.consumer.consumer.pause(requestedPartitions.asJava)) *>
ZIO.succeed(
(Set(), (state.pendingRequests, Map[TopicPartition, Chunk[ByteArrayConsumerRecord]]()))
)
else if (records eq null)
ZIO.succeed(
(Set(), (state.pendingRequests, Map[TopicPartition, Chunk[ByteArrayConsumerRecord]]()))
)
else {

if (records eq null)
ZIO.succeed(
(Set(), (state.pendingRequests, Map[TopicPartition, Chunk[ByteArrayConsumerRecord]]()))
)
else {

val tpsInResponse = records.partitions.asScala
val currentAssigned = c.assignment().asScala
val newlyAssigned = currentAssigned -- prevAssigned
val revoked = prevAssigned -- currentAssigned
val unrequestedRecords =
bufferUnrequestedPartitions(records, tpsInResponse -- requestedPartitions)

endRevoked(
state.pendingRequests,
state.addBufferedRecords(unrequestedRecords).bufferedRecords,
revoked(_)
).flatMap {
case (pendingRequests, bufferedRecords) =>
for {
output <- fulfillRequests(pendingRequests, bufferedRecords, records)
(notFulfilled, fulfilled) = output
_ <- deps.emitIfEnabledDiagnostic(
DiagnosticEvent.Poll(
requestedPartitions,
fulfilled.keySet,
notFulfilled.map(_.tp).toSet
val tpsInResponse = records.partitions.asScala
val currentAssigned = c.assignment().asScala
val newlyAssigned = currentAssigned -- prevAssigned
val revoked = prevAssigned -- currentAssigned
val unrequestedRecords =
bufferUnrequestedPartitions(records, tpsInResponse -- requestedPartitions)

endRevoked(
state.pendingRequests,
state.addBufferedRecords(unrequestedRecords).bufferedRecords,
revoked(_)
).flatMap {
case (pendingRequests, bufferedRecords) =>
for {
output <- fulfillRequests(pendingRequests, bufferedRecords, records)
(notFulfilled, fulfilled) = output
_ <- deps.emitIfEnabledDiagnostic(
DiagnosticEvent.Poll(
requestedPartitions,
fulfilled.keySet,
notFulfilled.map(_.tp).toSet
)
)
)
} yield output
}.map((newlyAssigned.toSet, _))
} yield output
}.map((newlyAssigned.toSet, _))
}
}
}
}
Expand Down Expand Up @@ -384,17 +407,41 @@ object Runloop {
else doCommit(List(cmd)).as(state)
} yield newState

def handleShutdown(state: State, cmd: Command): BlockingTask[State] = cmd match {
case Command.Poll() =>
state.pendingRequests match {
case h :: t =>
handleShutdown(state, h).flatMap { s =>
handleShutdown(s.copy(pendingRequests = t), cmd)
}
case Nil => handlePoll(state)
}
case Command.Request(tp, cont) =>
state.bufferedRecords.get(tp) match {
case Some(recs) =>
cont
.succeed(recs.map(CommittableRecord(_, commit(_))))
.as(state.removeBufferedRecordsFor(tp))
case None => cont.fail(None).as(state)
}
case cmd @ Command.Commit(_, _) => handleCommit(state, cmd)
}

ZStream
.mergeAll(3, 32)(
deps.polls,
deps.requests,
deps.commits
)
.foldM(State.initial) { (state, cmd) =>
cmd match {
case Command.Poll() => handlePoll(state)
case req @ Command.Request(_, _) => handleRequest(state, req)
case cmd @ Command.Commit(_, _) => handleCommit(state, cmd)
deps.isShutdown.flatMap { shutdown =>
if (shutdown) handleShutdown(state, cmd)
else
cmd match {
case Command.Poll() => handlePoll(state)
case req @ Command.Request(_, _) => handleRequest(state, req)
case cmd @ Command.Commit(_, _) => handleCommit(state, cmd)
}
}
}
.onError { cause =>
Expand Down
15 changes: 15 additions & 0 deletions src/test/scala/zio/kafka/client/ConsumerTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,21 @@ object ConsumerTest
_ => assertCompletes,
_ => assert("result", equalTo("Expected consumeWith to fail"))
)
},
testM("not receive messages after shutting down") {
val kvs = (1 to 5).toList.map(i => (s"key$i", s"msg$i"))
for {
_ <- produceMany("topic150", kvs)
records <- withConsumer("group150", "client150") { consumer =>
consumer.stopConsumption *>
consumer
.subscribeAnd(Subscription.Topics(Set("topic150")))
.plainStream(Serde.string, Serde.string)
.flattenChunks
.take(5)
.runCollect
}
} yield assert(records, isEmpty)
}
).provideManagedShared(KafkaTestUtils.kafkaEnvironment)
)