-
Notifications
You must be signed in to change notification settings - Fork 68
Implement PubSub api #714
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
Merged
Merged
Implement PubSub api #714
Changes from 1 commit
Commits
Show all changes
58 commits
Select commit
Hold shift + click to select a range
a280504
Add redis pubsub layer
0pg cd4a3f3
Fix PubSub api
0pg a01213d
Apply changes to t/c
0pg 9541519
Set private accessor
0pg ba89a59
Merge remote-tracking branch 'upstream/master' into impl/pubsub
0pg 9723182
Fix cleanup code
0pg 65b524b
Modify callback and unsubscribe logic in SingleNodeRedisPubSub
0pg 892ba20
Apply changes to t/c
0pg 43edb47
Modify PubSub api
0pg a6f74fa
Apply changes to t/c
0pg c7decb7
Fix typo
0pg b6438f0
Modify accessor
0pg 5fb75e4
Update redis/src/main/scala/zio/redis/Output.scala
0pg ce97f95
Update redis/src/main/scala/zio/redis/Output.scala
0pg a25805b
Modify responsibility to transform streams
0pg fd0b303
Apply changes to t/c
0pg 7cb1491
Move SubscriptionKey into only used place
0pg 2ab2db1
Merge remote-tracking branch 'upstream/master' into impl/pubsub
0pg 87eee71
Fix onSubscribe callback race condition bug
0pg f532e4b
Add pacakge private accessor to PubSubCommand
0pg e9e2a3c
Modify unsubscrption release logic
0pg 014d2e4
Merge remote-tracking branch 'upstream/master' into impl/pubsub
0pg 49c141b
Modify RedisPubSubCommand interface
0pg 8b6ce73
Apply changes to test
0pg f44c7fc
Add pubsub layer in Main
0pg 758ea9b
Remove BinaryCodec layer to RedisPubSub interface
0pg 9febcf8
Modify SingleNodeRedisPubSub failover step
0pg 92aea5e
Merge remote-tracking branch 'upstream/master' into impl/pubsub
0pg 3fc77c0
Separate Publish and Subscribe
0pg 3c8a307
Rename classes
0pg 0ea75a1
Reduce duplication
0pg ef3b9f1
Merge remote-tracking branch 'upstream/master' into impl/pubsub
0pg 478577b
Apply upstream changes
0pg c4105ff
Replace Hub to Queue
0pg f432815
Merge remote-tracking branch 'upstream/master' into impl/pubsub
0pg 149ae4b
Remove unused code
0pg 67652e6
Refine subscription api
0pg 8606409
Rename fields
0pg 6a3f68f
Update modules/redis/src/main/scala/zio/redis/RedisSubscription.scala
0pg 1a0862f
Add newline
0pg 92457c4
Fix broken compile
0pg bf52e26
Formatting
0pg c027295
Fix lint
0pg a154683
Reduce duplications and refactor package layout
0pg 592d327
Commit suggestion
0pg 386fefd
Fix broken compile
0pg 415f75e
Merge remote-tracking branch 'upstream/master' into impl/pubsub
0pg 1699211
Use hub instead of chunks of queue
0pg be11d67
Add release on error
0pg 552e002
Extraact common logic
0pg e218b08
Ensure order of subs/unsubs
0pg ac85cb9
Update modules/redis/src/main/scala/zio/redis/internal/SingleNodeSubs…
0pg dadb5e7
Use ConcurrentMap instead of Map of Ref
0pg 88c3f4e
Add private accessor
0pg 6e50d4d
Fix accessor
0pg 5ca98e7
Add doc
0pg 539ef3f
Add missing params
0pg 63cc263
Fix test codes
0pg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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,25 @@ | ||
| package zio.redis | ||
|
|
||
| import zio.schema.codec.BinaryCodec | ||
| import zio.stream._ | ||
| import zio.{ULayer, ZIO, ZLayer} | ||
|
|
||
| trait RedisPubSub { | ||
| def execute(command: RedisPubSubCommand): ZStream[BinaryCodec, RedisError, PushProtocol] | ||
| } | ||
|
|
||
| object RedisPubSub { | ||
| lazy val layer: ZLayer[RedisConfig with BinaryCodec, RedisError.IOError, RedisPubSub] = | ||
| RedisConnectionLive.layer.fresh >>> pubSublayer | ||
|
|
||
| lazy val local: ZLayer[BinaryCodec, RedisError.IOError, RedisPubSub] = | ||
| RedisConnectionLive.default.fresh >>> pubSublayer | ||
|
|
||
| lazy val test: ULayer[RedisPubSub] = | ||
| TestExecutor.layer | ||
|
|
||
| private lazy val pubSublayer: ZLayer[RedisConnection with BinaryCodec, RedisError.IOError, RedisPubSub] = | ||
| ZLayer.scoped( | ||
| ZIO.service[RedisConnection].flatMap(SingleNodeRedisPubSub.create(_)) | ||
| ) | ||
| } |
This file contains hidden or 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,19 @@ | ||
| package zio.redis | ||
|
|
||
| import zio.ZLayer | ||
| import zio.stream.ZStream | ||
|
|
||
| sealed abstract class RedisPubSubCommand | ||
|
|
||
| object RedisPubSubCommand { | ||
| case class Subscribe(channel: String, channels: List[String]) extends RedisPubSubCommand | ||
| case class PSubscribe(pattern: String, patterns: List[String]) extends RedisPubSubCommand | ||
| case class Unsubscribe(channels: List[String]) extends RedisPubSubCommand | ||
| case class PUnsubscribe(patterns: List[String]) extends RedisPubSubCommand | ||
|
|
||
| def run(command: RedisPubSubCommand): ZStream[Redis, RedisError, PushProtocol] = | ||
| ZStream.serviceWithStream { redis => | ||
| val codecLayer = ZLayer.succeed(redis.codec) | ||
| redis.pubSub.execute(command).provideLayer(codecLayer) | ||
| } | ||
| } |
This file contains hidden or 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
169 changes: 169 additions & 0 deletions
169
redis/src/main/scala/zio/redis/SingleNodeRedisPubSub.scala
This file contains hidden or 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,169 @@ | ||
| package zio.redis | ||
|
|
||
| import zio.redis.Input.{NonEmptyList, StringInput, Varargs} | ||
| import zio.redis.Output.PushProtocolOutput | ||
| import zio.redis.SingleNodeRedisPubSub.{Request, RequestQueueSize, True} | ||
| import zio.redis.api.PubSub | ||
| import zio.schema.codec.BinaryCodec | ||
| import zio.stream._ | ||
| import zio.{Chunk, ChunkBuilder, Hub, Promise, Queue, Ref, Schedule, UIO, ZIO} | ||
|
|
||
| import scala.reflect.ClassTag | ||
|
|
||
| final class SingleNodeRedisPubSub( | ||
| pubSubHubsRef: Ref[Map[SubscriptionKey, Hub[PushProtocol]]], | ||
| reqQueue: Queue[Request], | ||
| connection: RedisConnection | ||
| ) extends RedisPubSub { | ||
|
|
||
| def execute(command: RedisPubSubCommand): ZStream[BinaryCodec, RedisError, PushProtocol] = | ||
| command match { | ||
| case RedisPubSubCommand.Subscribe(channel, channels) => subscribe(channel, channels) | ||
| case RedisPubSubCommand.PSubscribe(pattern, patterns) => pSubscribe(pattern, patterns) | ||
| case RedisPubSubCommand.Unsubscribe(channels) => unsubscribe(channels) | ||
| case RedisPubSubCommand.PUnsubscribe(patterns) => pUnsubscribe(patterns) | ||
| } | ||
|
|
||
| private def subscribe( | ||
| channel: String, | ||
| channels: List[String] | ||
| ): ZStream[BinaryCodec, RedisError, PushProtocol] = | ||
| makeSubscriptionStream(PubSub.Subscribe, SubscriptionKey.Channel(channel), channels.map(SubscriptionKey.Channel(_))) | ||
|
|
||
| private def pSubscribe( | ||
| pattern: String, | ||
| patterns: List[String] | ||
| ): ZStream[BinaryCodec, RedisError, PushProtocol] = | ||
| makeSubscriptionStream( | ||
| PubSub.PSubscribe, | ||
| SubscriptionKey.Pattern(pattern), | ||
| patterns.map(SubscriptionKey.Pattern(_)) | ||
| ) | ||
|
|
||
| private def unsubscribe(channels: List[String]): ZStream[BinaryCodec, RedisError, PushProtocol] = | ||
| makeUnsubscriptionStream(PubSub.Unsubscribe, channels.map(SubscriptionKey.Channel(_))) | ||
|
|
||
| private def pUnsubscribe(patterns: List[String]): ZStream[BinaryCodec, RedisError, PushProtocol] = | ||
| makeUnsubscriptionStream(PubSub.PUnsubscribe, patterns.map(SubscriptionKey.Pattern(_))) | ||
|
|
||
| private def makeSubscriptionStream(command: String, key: SubscriptionKey, keys: List[SubscriptionKey]) = | ||
| ZStream.unwrap[BinaryCodec, RedisError, PushProtocol]( | ||
| ZIO.serviceWithZIO[BinaryCodec] { implicit codec => | ||
| for { | ||
| promise <- Promise.make[RedisError, Unit] | ||
| chunk = StringInput.encode(command) ++ NonEmptyList(StringInput).encode((key.value, keys.map(_.value))) | ||
| stream <- makeStream(key :: keys) | ||
| _ <- reqQueue.offer(Request(chunk, promise)) | ||
| _ <- promise.await | ||
| } yield stream | ||
| } | ||
| ) | ||
|
|
||
| private def makeUnsubscriptionStream[T <: SubscriptionKey: ClassTag](command: String, keys: List[T]) = | ||
| ZStream.unwrap[BinaryCodec, RedisError, PushProtocol]( | ||
| ZIO.serviceWithZIO[BinaryCodec] { implicit codec => | ||
| for { | ||
| targets <- if (keys.isEmpty) pubSubHubsRef.get.map(_.keys.collect { case t: T => t }.toList) | ||
| else ZIO.succeedNow(keys) | ||
| chunk = StringInput.encode(command) ++ Varargs(StringInput).encode(keys.map(_.value)) | ||
| promise <- Promise.make[RedisError, Unit] | ||
| stream <- makeStream(targets) | ||
| _ <- reqQueue.offer(Request(chunk, promise)) | ||
| _ <- promise.await | ||
| } yield stream | ||
| } | ||
| ) | ||
|
|
||
| private def makeStream(keys: List[SubscriptionKey]): UIO[Stream[RedisError, PushProtocol]] = | ||
| for { | ||
| streams <- ZIO.foreach(keys)(getHub(_).map(ZStream.fromHub(_))) | ||
| stream = streams.fold(ZStream.empty)(_ merge _) | ||
| } yield stream | ||
|
|
||
| private def getHub(key: SubscriptionKey) = { | ||
| def makeNewHub = | ||
| Hub | ||
| .unbounded[PushProtocol] | ||
| .tap(hub => pubSubHubsRef.update(_ + (key -> hub))) | ||
|
|
||
| for { | ||
| hubs <- pubSubHubsRef.get | ||
| hub <- ZIO.fromOption(hubs.get(key)).orElse(makeNewHub) | ||
| } yield hub | ||
| } | ||
|
|
||
| private def send = | ||
| reqQueue.takeBetween(1, RequestQueueSize).flatMap { reqs => | ||
| val buffer = ChunkBuilder.make[Byte]() | ||
| val it = reqs.iterator | ||
|
|
||
| while (it.hasNext) { | ||
| val req = it.next() | ||
| buffer ++= RespValue.Array(req.command).serialize | ||
| } | ||
|
|
||
| val bytes = buffer.result() | ||
|
|
||
| connection | ||
| .write(bytes) | ||
| .mapError(RedisError.IOError(_)) | ||
| .tapBoth( | ||
| e => ZIO.foreachDiscard(reqs)(_.promise.fail(e)), | ||
| _ => ZIO.foreachDiscard(reqs)(_.promise.succeed(())) | ||
| ) | ||
| } | ||
|
|
||
| private def receive: ZIO[BinaryCodec, RedisError, Unit] = | ||
| ZIO.serviceWithZIO[BinaryCodec] { implicit codec => | ||
| connection.read | ||
| .mapError(RedisError.IOError(_)) | ||
| .via(RespValue.decoder) | ||
| .collectSome | ||
| .mapZIO(resp => ZIO.attempt(PushProtocolOutput.unsafeDecode(resp))) | ||
| .refineToOrDie[RedisError] | ||
| .foreach(push => getHub(push.key).flatMap(_.offer(push))) | ||
| } | ||
|
|
||
| private def resubscribe: ZIO[BinaryCodec, RedisError, Unit] = | ||
| ZIO.serviceWithZIO[BinaryCodec] { implicit codec => | ||
| def makeCommand(name: String, keys: Set[String]) = | ||
| RespValue.Array(StringInput.encode(name) ++ Varargs(StringInput).encode(keys)).serialize | ||
|
|
||
| for { | ||
| keySet <- pubSubHubsRef.get.map(_.keySet) | ||
| (channels, patterns) = keySet.partition(_.isChannelKey) | ||
| _ <- (connection.write(makeCommand(PubSub.Subscribe, channels.map(_.value))).when(channels.nonEmpty) *> | ||
| connection.write(makeCommand(PubSub.PSubscribe, patterns.map(_.value))).when(patterns.nonEmpty)) | ||
| .mapError(RedisError.IOError(_)) | ||
| .retryWhile(True) | ||
| } yield () | ||
| } | ||
|
|
||
| /** | ||
| * Opens a connection to the server and launches receive operations. All failures are retried by opening a new | ||
| * connection. Only exits by interruption or defect. | ||
| */ | ||
| val run: ZIO[BinaryCodec, RedisError, AnyVal] = | ||
| ZIO.logTrace(s"$this Executable sender and reader has been started") *> | ||
| (send.repeat[BinaryCodec, Long](Schedule.forever) race receive) | ||
| .tapError(e => ZIO.logWarning(s"Reconnecting due to error: $e") *> resubscribe) | ||
| .retryWhile(True) | ||
| .tapError(e => ZIO.logError(s"Executor exiting: $e")) | ||
| } | ||
|
|
||
| object SingleNodeRedisPubSub { | ||
| final case class Request(command: Chunk[RespValue.BulkString], promise: Promise[RedisError, Unit]) | ||
|
|
||
| private final val True: Any => Boolean = _ => true | ||
|
|
||
| private final val RequestQueueSize = 16 | ||
|
|
||
| def create(conn: RedisConnection) = | ||
| for { | ||
| hubRef <- Ref.make(Map.empty[SubscriptionKey, Hub[PushProtocol]]) | ||
| reqQueue <- Queue.bounded[Request](RequestQueueSize) | ||
| pubSub = new SingleNodeRedisPubSub(hubRef, reqQueue, conn) | ||
| _ <- pubSub.run.forkScoped | ||
| _ <- logScopeFinalizer(s"$pubSub Node PubSub is closed") | ||
| } yield pubSub | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.