From 65f1adea09df314bcec29769d9ee52f6d1b1dc11 Mon Sep 17 00:00:00 2001 From: Tushar Mathur Date: Fri, 24 Mar 2023 18:40:26 +0530 Subject: [PATCH] feature: add Redis --- build.sbt | 6 +++++- .../tailcall/registry/SchemaRegistry.scala | 20 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/build.sbt b/build.sbt index 162c3f3ca0..346db46eaf 100644 --- a/build.sbt +++ b/build.sbt @@ -33,7 +33,11 @@ lazy val server = (project in file("server")).settings( ).dependsOn(runtime, registry) lazy val registry = (project in file("registry")).settings( - libraryDependencies := zioTestDependencies ++ Seq("dev.zio" %% "zio" % zio, "dev.zio" %% "zio-http" % zioHttp) + libraryDependencies := zioTestDependencies ++ Seq( + "dev.zio" %% "zio" % zio, + "dev.zio" %% "zio-http" % zioHttp, + "dev.zio" %% "zio-redis" % "0.1.0", + ) ).dependsOn(runtime) val scala2Version = "2.13.10" diff --git a/registry/src/main/scala/tailcall/registry/SchemaRegistry.scala b/registry/src/main/scala/tailcall/registry/SchemaRegistry.scala index 49dc724f56..949ac6e04b 100644 --- a/registry/src/main/scala/tailcall/registry/SchemaRegistry.scala +++ b/registry/src/main/scala/tailcall/registry/SchemaRegistry.scala @@ -2,6 +2,7 @@ package tailcall.registry import tailcall.runtime.ast.{Blueprint, Digest} import zio._ +import zio.redis.Redis trait SchemaRegistry { def add(blueprint: Blueprint): Task[Digest] @@ -16,6 +17,8 @@ object SchemaRegistry { def memory: ZLayer[Any, Nothing, SchemaRegistry] = ZLayer.fromZIO(for { ref <- Ref.make(Map.empty[Digest, Blueprint]) } yield Memory(ref)) + def redis: ZLayer[Redis, Nothing, SchemaRegistry] = ZLayer.fromFunction(FromRedis(_)) + def add(blueprint: Blueprint): ZIO[SchemaRegistry, Throwable, Digest] = ZIO.serviceWithZIO[SchemaRegistry](_.add(blueprint)) @@ -42,4 +45,21 @@ object SchemaRegistry { override def drop(digest: Digest): UIO[Boolean] = ref.modify(map => if (map.contains(digest)) (true, map - digest) else (false, map)) } + + final case class FromRedis(redis: Redis) extends SchemaRegistry { + override def add(blueprint: Blueprint): Task[Digest] = { + val digest: Digest = blueprint.digest + for { _ <- redis.set(digest.hex, blueprint) } yield digest + } + + override def get(id: Digest): Task[Option[Blueprint]] = redis.get(id.hex).returning[Blueprint] + + override def list(index: RuntimeFlags, max: RuntimeFlags): Task[List[Blueprint]] = + for { + hexes <- redis.keys("*").returning[String] + blueprints <- ZIO.foreach(hexes)(hex => redis.get(hex).returning[Blueprint]) + } yield blueprints.slice(index, index + max).toList.flatMap(_.toList) + + override def drop(digest: Digest): Task[Boolean] = redis.del(digest.hex).map(_ > 0) + } }