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

Prevent a potential race condition that can cause self assignments to be replaced #148

Merged
merged 1 commit into from
Oct 30, 2024
Merged
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
12 changes: 6 additions & 6 deletions entities/src/main/scala/com/devsisters/shardcake/Sharding.scala
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,14 @@ class Sharding private (

private def updateAssignments(
assignmentsOpt: Map[ShardId, Option[PodAddress]],
fromShardManager: Boolean
replaceAllAssignments: Boolean
): UIO[Unit] = {
val assignments = assignmentsOpt.flatMap { case (k, v) => v.map(k -> _) }
ZIO.logDebug("Received new shard assignments") *>
Metrics.shards
.set(assignmentsOpt.count { case (_, podOpt) => podOpt.contains(address) })
.when(fromShardManager) *>
(if (fromShardManager) shardAssignments.set(assignments)
.when(replaceAllAssignments) *>
(if (replaceAllAssignments) shardAssignments.set(assignments)
else
shardAssignments.update(map =>
// we keep self assignments (we don't override them with the new assignments
Expand All @@ -166,8 +166,8 @@ class Sharding private (
) ++
// then, get assignments changes from Redis
storage.assignmentsStream.map(_ -> false)
_ <- assignmentStream.mapZIO { case (assignmentsOpt, fromShardManager) =>
updateAssignments(assignmentsOpt, fromShardManager) *> latch.succeed(()).when(fromShardManager)
_ <- assignmentStream.mapZIO { case (assignmentsOpt, replaceAllAssignments) =>
updateAssignments(assignmentsOpt, replaceAllAssignments) *> latch.succeed(()).when(replaceAllAssignments)
}.runDrain
.retry(Schedule.fixed(config.refreshAssignmentsRetryInterval))
.interruptible
Expand Down Expand Up @@ -254,7 +254,7 @@ class Sharding private (
(shardManager.notifyUnhealthyPod(pod) *>
// just in case we missed the update from the pubsub, refresh assignments
shardManager.getAssignments
.flatMap[Any, Throwable, Unit](updateAssignments(_, fromShardManager = true))).forkDaemon
.flatMap[Any, Throwable, Unit](updateAssignments(_, replaceAllAssignments = false))).forkDaemon
)
}

Expand Down
Loading