From a4fc34d49febd3483d4f3dad50870815199441c8 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Fri, 19 Nov 2021 13:13:40 -0500 Subject: [PATCH] ZLayer Resurrection (#6061) * zlayer cannot be zlayed * comment out example (dotty macro issue) * undo renaming of ZLayer * more changes --- .scalafmt.conf | 2 + .../zio.internal/CleanCodePrinterSpec.scala | 2 +- .../src/test/scala/zio/RandomSpec.scala | 4 +- .../src/test/scala/zio/ScheduleSpec.scala | 2 +- .../test/scala/zio/TagCorrectnessSpec.scala | 24 +- .../scala/zio/ZEnvironmentIssuesSpec.scala | 4 +- .../shared/src/test/scala/zio/ZIOSpec.scala | 18 +- .../src/test/scala/zio/ZLayerSpec.scala | 450 ++++ .../src/test/scala/zio/ZManagedSpec.scala | 12 +- .../test/scala/zio/ZServiceBuilderSpec.scala | 450 ---- .../src/test/scala/zio/ZStateSpec.scala | 2 +- .../scala/zio/autowire/AutoWireSpec.scala | 196 +- .../InjectParameterizedServicesSpec.scala | 12 +- .../scala/zio/autowire/InjectSomeSpec.scala | 14 +- .../zio/metrics/jvm/DefaultJvmMetrics.scala | 6 +- .../scala/zio/metrics/jvm/JvmMetrics.scala | 10 +- .../main/scala-2/zio/ZIOVersionSpecific.scala | 46 +- ...a => ZLayerCompanionVersionSpecific.scala} | 38 +- .../scala-2/zio/ZManagedVersionSpecific.scala | 52 +- ...MacroUtils.scala => LayerMacroUtils.scala} | 104 +- ...eBuilderMacros.scala => LayerMacros.scala} | 16 +- .../zio/internal/macros/WireMacros.scala | 14 +- .../main/scala-3/zio/ZIOVersionSpecific.scala | 30 +- .../zio/ZLayerCompanionVersionSpecific.scala | 40 + .../scala-3/zio/ZManagedVersionSpecific.scala | 36 +- ...rviceBuilderCompanionVersionSpecific.scala | 40 - ...MacroUtils.scala => LayerMacroUtils.scala} | 48 +- .../zio/internal/macros/LayerMacros.scala | 87 + .../macros/ServiceBuilderMacros.scala | 87 - core/shared/src/main/scala/zio/Clock.scala | 12 +- core/shared/src/main/scala/zio/Console.scala | 8 +- ...ntax.scala => FunctionToLayerSyntax.scala} | 664 ++---- core/shared/src/main/scala/zio/Random.scala | 12 +- core/shared/src/main/scala/zio/Runtime.scala | 28 +- core/shared/src/main/scala/zio/System.scala | 8 +- core/shared/src/main/scala/zio/ZEnv.scala | 6 +- core/shared/src/main/scala/zio/ZIO.scala | 136 +- core/shared/src/main/scala/zio/ZIOApp.scala | 32 +- .../src/main/scala/zio/ZIOAppDefault.scala | 2 +- .../{ZServiceBuilder.scala => ZLayer.scala} | 2092 ++++++++--------- core/shared/src/main/scala/zio/ZManaged.scala | 127 +- core/shared/src/main/scala/zio/ZState.scala | 12 +- .../scala/zio/internal/macros/Graph.scala | 8 +- .../zio/internal/macros/LayerCompose.scala | 36 + ...prBuilder.scala => LayerExprBuilder.scala} | 22 +- .../macros/ServiceBuilderCompose.scala | 39 - core/shared/src/main/scala/zio/package.scala | 28 +- .../src/main/scala/zio/stm/TRandom.scala | 8 +- docs/datatypes/contextual/index.md | 64 +- docs/datatypes/contextual/layer.md | 10 + docs/datatypes/contextual/rlayer.md | 10 + docs/datatypes/contextual/rservicebuilder.md | 10 - docs/datatypes/contextual/servicebuilder.md | 10 - docs/datatypes/contextual/task-layer.md | 10 + .../contextual/task-servicebuilder.md | 10 - docs/datatypes/contextual/ulayer.md | 10 + docs/datatypes/contextual/urlayer.md | 10 + docs/datatypes/contextual/urservicebuilder.md | 10 - docs/datatypes/contextual/uservicebuilder.md | 10 - docs/datatypes/contextual/zlayer.md | 713 ++++++ docs/datatypes/contextual/zservicebuilder.md | 713 ------ docs/datatypes/core/runtime.md | 4 +- docs/datatypes/core/zioapp.md | 4 +- docs/datatypes/index.md | 12 +- docs/datatypes/misc/zstate.md | 8 +- docs/howto/howto-macros.md | 8 +- docs/howto/migrate/migration-guide.md | 164 +- docs/howto/mock-services.md | 36 +- docs/howto/test_effects.md | 10 +- .../resources/ecosystem/community/logstage.md | 6 +- docs/resources/ecosystem/community/quill.md | 2 +- docs/resources/ecosystem/community/tamer.md | 2 +- .../ecosystem/community/tranzactio.md | 8 +- .../ecosystem/community/zio-aws-s3.md | 4 +- docs/resources/ecosystem/community/zio-aws.md | 4 +- .../resources/ecosystem/community/zio-grpc.md | 4 +- .../ecosystem/community/zio-kinesis.md | 4 +- .../ecosystem/community/zio-slick-interop.md | 10 +- .../ecosystem/officials/zio-akka-cluster.md | 12 +- .../ecosystem/officials/zio-kafka.md | 8 +- .../ecosystem/officials/zio-metrics.md | 2 +- .../ecosystem/officials/zio-redis.md | 10 +- docs/resources/ecosystem/officials/zio-sqs.md | 6 +- .../ecosystem/officials/zio-telemetry.md | 6 +- .../macros/AccessibleMacroExample.scala | 4 +- .../scala/zio/examples/InjectExample.scala | 76 + .../ServiceBuilderDefinitionExample.scala | 31 - .../ZServiceBuilderInjectExample.scala | 76 - .../zio/examples/test/MockExampleSpec.scala | 18 +- .../test/ZLayerInjectExampleSpec.scala | 30 + .../ZServiceBuilderInjectExampleSpec.scala | 30 - .../scala-2/zio/macros/AccessibleSpec.scala | 4 +- .../zio/macros/AccessibleSpecFlat.scala | 4 +- .../src/main/scala/fix/ZManagedSpec.scala | 1 + .../output/src/main/scala/fix/ZIOSpec.scala | 16 +- .../src/main/scala/fix/ZManagedSpec.scala | 8 +- .../src/main/scala/fix/Zio2Upgrade.scala | 261 +- .../test/scala/zio/stream/ZStreamSpec.scala | 4 +- .../zio.stream/ZStreamVersionSpecific.scala | 36 +- .../zio.stream/ZStreamVersionSpecific.scala | 28 +- .../src/main/scala/zio/stream/ZStream.scala | 88 +- .../main/scala/zio/test/sbt/ZTestRunner.scala | 6 +- .../zio/test/sbt/ZTestFrameworkSpec.scala | 28 +- .../main/scala/zio/test/sbt/ZTestRunner.scala | 6 +- .../scala/zio/test/sbt/BaseTestTask.scala | 38 +- .../test/scala/zio/test/AutoWireSpec.scala | 70 +- .../scala/zio/test/IntellijRendererSpec.scala | 4 +- .../src/test/scala/zio/test/ManagedSpec.scala | 4 +- .../scala/zio/test/ReportingTestUtils.scala | 16 +- .../src/test/scala/zio/test/SpecSpec.scala | 40 +- .../zio/test/mock/ComposedMockSpec.scala | 2 +- .../scala/zio/test/mock/MockSpecUtils.scala | 8 +- .../test/mock/module/ImpureModuleMock.scala | 6 +- .../zio/test/mock/module/PureModuleMock.scala | 6 +- .../test/mock/module/StreamModuleMock.scala | 6 +- .../scala-2/zio/test/SpecLayerMacros.scala | 23 + .../zio/test/SpecServiceBuilderMacros.scala | 23 - .../zio/test/SpecVersionSpecific.scala | 77 +- .../scala-2/zio/test/mock/MockableMacro.scala | 4 +- .../test/SpecProvideServiceAutoMacros.scala | 12 +- .../zio/test/SpecVersionSpecific.scala | 46 +- .../src/main/scala/zio/test/Annotations.scala | 4 +- .../zio/test/DefaultMutableRunnableSpec.scala | 4 +- .../shared/src/main/scala/zio/test/Live.scala | 6 +- .../scala/zio/test/MutableRunnableSpec.scala | 6 +- .../src/main/scala/zio/test/Sized.scala | 8 +- .../shared/src/main/scala/zio/test/Spec.scala | 183 +- .../src/main/scala/zio/test/TestAspect.scala | 140 +- .../src/main/scala/zio/test/TestClock.scala | 10 +- .../src/main/scala/zio/test/TestConfig.scala | 8 +- .../src/main/scala/zio/test/TestConsole.scala | 14 +- .../main/scala/zio/test/TestExecutor.scala | 6 +- .../src/main/scala/zio/test/TestLogger.scala | 6 +- .../src/main/scala/zio/test/TestRandom.scala | 14 +- .../src/main/scala/zio/test/TestRunner.scala | 2 +- .../src/main/scala/zio/test/TestSystem.scala | 12 +- .../main/scala/zio/test/ZIOSpecAbstract.scala | 8 +- .../main/scala/zio/test/ZIOSpecDefault.scala | 4 +- .../scala/zio/test/mock/Expectation.scala | 26 +- .../src/main/scala/zio/test/mock/Mock.scala | 8 +- .../main/scala/zio/test/mock/MockClock.scala | 4 +- .../scala/zio/test/mock/MockConsole.scala | 6 +- .../main/scala/zio/test/mock/MockRandom.scala | 6 +- .../main/scala/zio/test/mock/MockSystem.scala | 6 +- .../zio/test/mock/internal/ProxyFactory.scala | 6 +- .../src/main/scala/zio/test/package.scala | 10 +- website/sidebars.js | 12 +- website/sidebars.json | 12 +- 148 files changed, 3933 insertions(+), 4788 deletions(-) create mode 100644 core-tests/shared/src/test/scala/zio/ZLayerSpec.scala delete mode 100644 core-tests/shared/src/test/scala/zio/ZServiceBuilderSpec.scala rename core/shared/src/main/scala-2/zio/{ZServiceBuilderCompanionVersionSpecific.scala => ZLayerCompanionVersionSpecific.scala} (52%) rename core/shared/src/main/scala-2/zio/internal/macros/{ServiceBuilderMacroUtils.scala => LayerMacroUtils.scala} (63%) rename core/shared/src/main/scala-2/zio/internal/macros/{ServiceBuilderMacros.scala => LayerMacros.scala} (71%) create mode 100644 core/shared/src/main/scala-3/zio/ZLayerCompanionVersionSpecific.scala delete mode 100644 core/shared/src/main/scala-3/zio/ZServiceBuilderCompanionVersionSpecific.scala rename core/shared/src/main/scala-3/zio/internal/macros/{ServiceBuilderMacroUtils.scala => LayerMacroUtils.scala} (51%) create mode 100644 core/shared/src/main/scala-3/zio/internal/macros/LayerMacros.scala delete mode 100644 core/shared/src/main/scala-3/zio/internal/macros/ServiceBuilderMacros.scala rename core/shared/src/main/scala/zio/{FunctionToServiceBuilderSyntax.scala => FunctionToLayerSyntax.scala} (62%) rename core/shared/src/main/scala/zio/{ZServiceBuilder.scala => ZLayer.scala} (67%) create mode 100644 core/shared/src/main/scala/zio/internal/macros/LayerCompose.scala rename core/shared/src/main/scala/zio/internal/macros/{ServiceBuilderExprBuilder.scala => LayerExprBuilder.scala} (85%) delete mode 100644 core/shared/src/main/scala/zio/internal/macros/ServiceBuilderCompose.scala create mode 100644 docs/datatypes/contextual/layer.md create mode 100644 docs/datatypes/contextual/rlayer.md delete mode 100644 docs/datatypes/contextual/rservicebuilder.md delete mode 100644 docs/datatypes/contextual/servicebuilder.md create mode 100644 docs/datatypes/contextual/task-layer.md delete mode 100644 docs/datatypes/contextual/task-servicebuilder.md create mode 100644 docs/datatypes/contextual/ulayer.md create mode 100644 docs/datatypes/contextual/urlayer.md delete mode 100644 docs/datatypes/contextual/urservicebuilder.md delete mode 100644 docs/datatypes/contextual/uservicebuilder.md create mode 100644 docs/datatypes/contextual/zlayer.md delete mode 100644 docs/datatypes/contextual/zservicebuilder.md create mode 100644 examples/shared/src/main/scala/zio/examples/InjectExample.scala delete mode 100644 examples/shared/src/main/scala/zio/examples/ServiceBuilderDefinitionExample.scala delete mode 100644 examples/shared/src/main/scala/zio/examples/ZServiceBuilderInjectExample.scala create mode 100644 examples/shared/src/test/scala/zio/examples/test/ZLayerInjectExampleSpec.scala delete mode 100644 examples/shared/src/test/scala/zio/examples/test/ZServiceBuilderInjectExampleSpec.scala create mode 100644 test/shared/src/main/scala-2/zio/test/SpecLayerMacros.scala delete mode 100644 test/shared/src/main/scala-2/zio/test/SpecServiceBuilderMacros.scala diff --git a/.scalafmt.conf b/.scalafmt.conf index cc50283640b0..24950e287a7f 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -14,6 +14,8 @@ newlines.alwaysBeforeMultilineDef = false runner.dialect = scala213 rewrite.rules = [RedundantBraces] +project.excludePaths = ["glob:**/scalafix/input/**", "glob:**/scalafix/output/**"] + rewrite.redundantBraces.generalExpressions = false rewriteTokens = { "⇒": "=>" diff --git a/core-tests/shared/src/test/scala-2.x/zio.internal/CleanCodePrinterSpec.scala b/core-tests/shared/src/test/scala-2.x/zio.internal/CleanCodePrinterSpec.scala index 788340195163..67b8541828ec 100644 --- a/core-tests/shared/src/test/scala-2.x/zio.internal/CleanCodePrinterSpec.scala +++ b/core-tests/shared/src/test/scala-2.x/zio.internal/CleanCodePrinterSpec.scala @@ -14,7 +14,7 @@ object CleanCodePrinterSpec extends ZIOBaseSpec { Assertion.assertion("containsStringWithoutAnsi")(param(element))(_.removingAnsiCodes.contains(element)) def spec: ZSpec[Environment, Failure] = - suite("AutoServiceBuilderSpec")( + suite("AutoLayerSpec")( suite(".showTree") { test("prints trees for expressions") { import nested.{Service => Nested} diff --git a/core-tests/shared/src/test/scala/zio/RandomSpec.scala b/core-tests/shared/src/test/scala/zio/RandomSpec.scala index a86d64c6f924..048e3538d1fa 100644 --- a/core-tests/shared/src/test/scala/zio/RandomSpec.scala +++ b/core-tests/shared/src/test/scala/zio/RandomSpec.scala @@ -50,8 +50,8 @@ object RandomSpec extends ZIOBaseSpec { } }, test("scalaRandom") { - val serviceBuilder = ZServiceBuilder.fromZIO(ZIO.succeed(new scala.util.Random)) >>> Random.scalaRandom - val sample = ZIO.replicateZIO(5)((Random.setSeed(91) *> Random.nextInt).provideSome(serviceBuilder.fresh)) + val layer = ZLayer.fromZIO(ZIO.succeed(new scala.util.Random)) >>> Random.scalaRandom + val sample = ZIO.replicateZIO(5)((Random.setSeed(91) *> Random.nextInt).provideSome(layer.fresh)) for { values <- ZIO.collectAllPar(ZIO.replicate(5)(sample)) } yield assertTrue(values.toSet.size == 1) diff --git a/core-tests/shared/src/test/scala/zio/ScheduleSpec.scala b/core-tests/shared/src/test/scala/zio/ScheduleSpec.scala index 2903642e067c..3e5d9a7ab52b 100644 --- a/core-tests/shared/src/test/scala/zio/ScheduleSpec.scala +++ b/core-tests/shared/src/test/scala/zio/ScheduleSpec.scala @@ -722,6 +722,6 @@ object ScheduleSpec extends ZIOBaseSpec { object Logging { trait Service - val live: ZServiceBuilder[Any, Nothing, Logging] = ZServiceBuilder.succeed(new Logging.Service {}) + val live: ZLayer[Any, Nothing, Logging] = ZLayer.succeed(new Logging.Service {}) } } diff --git a/core-tests/shared/src/test/scala/zio/TagCorrectnessSpec.scala b/core-tests/shared/src/test/scala/zio/TagCorrectnessSpec.scala index 1992654f1e31..3831424e8f2f 100644 --- a/core-tests/shared/src/test/scala/zio/TagCorrectnessSpec.scala +++ b/core-tests/shared/src/test/scala/zio/TagCorrectnessSpec.scala @@ -10,7 +10,7 @@ object TagCorrectnessSpec extends DefaultRunnableSpec { test("Issue #4802") { ZIO .serviceWithZIO[Ref[Int]](_.get) - .inject(Ref.make(10).toServiceBuilder) + .inject(Ref.make(10).toLayer) .map { int => assertTrue(int == 10) } @@ -39,8 +39,8 @@ object TagCorrectnessSpec extends DefaultRunnableSpec { } object Service { - val live: UServiceBuilder[Service[Int]] = - ZServiceBuilder.succeed { + val live: ULayer[Service[Int]] = + ZLayer.succeed { new Service[Int] { def foo(t: Int) = ZIO.succeed(t) @@ -58,10 +58,10 @@ object TagCorrectnessSpec extends DefaultRunnableSpec { // https://github.com/zio/zio/issues/4564 test("Issue #4564") { trait Svc[A] - def testBaseLayer[R, A: Tag]: ZServiceBuilder[R, Nothing, Svc[A]] = - ZIO.environmentWith[R](_ => new Svc[A] {}).toServiceBuilder[Svc[A]] - def testSecondLayer[A: Tag]: ZServiceBuilder[Svc[A], Nothing, Svc[A]] = - ZServiceBuilder.fromFunction[Svc[A], Svc[A]] { environment => + def testBaseLayer[R, A: Tag]: ZLayer[R, Nothing, Svc[A]] = + ZIO.environmentWith[R](_ => new Svc[A] {}).toLayer[Svc[A]] + def testSecondLayer[A: Tag]: ZLayer[Svc[A], Nothing, Svc[A]] = + ZLayer.fromFunction[Svc[A], Svc[A]] { environment => environment.get } @@ -79,8 +79,8 @@ object TagCorrectnessSpec extends DefaultRunnableSpec { def provide: IO[Throwable, D] } - def layer[A: Tag, D <: Container[A]: Tag](container: D): UServiceBuilder[ContainerProvider[A, D]] = - ZServiceBuilder.succeed { + def layer[A: Tag, D <: Container[A]: Tag](container: D): ULayer[ContainerProvider[A, D]] = + ZLayer.succeed { new Service[A, D] { def provide: IO[Throwable, D] = IO.succeed(container) } @@ -116,8 +116,8 @@ object HigherKindedTagCorrectness extends DefaultRunnableSpec { object Cache { def live[F[_], K, V]( f: Option[V] => F[V] - )(implicit tag: Tag[Cache[F, K, V]]): ZServiceBuilder[Any, Nothing, Cache[F, K, V]] = - ZServiceBuilder { + )(implicit tag: Tag[Cache[F, K, V]]): ZLayer[Any, Nothing, Cache[F, K, V]] = + ZLayer { for { cache <- Ref.make(Map.empty[K, V]) } yield new Cache[F, K, V] { @@ -136,7 +136,7 @@ object HigherKindedTagCorrectness extends DefaultRunnableSpec { ZIO.serviceWithZIO(_.put(key, value)) } - val myCache: ZServiceBuilder[Any, Nothing, Cache[Option, Int, String]] = + val myCache: ZLayer[Any, Nothing, Cache[Option, Int, String]] = Cache.live[Option, Int, String](identity) def spec = diff --git a/core-tests/shared/src/test/scala/zio/ZEnvironmentIssuesSpec.scala b/core-tests/shared/src/test/scala/zio/ZEnvironmentIssuesSpec.scala index 9db2d7eeadff..4b93fb2502ea 100644 --- a/core-tests/shared/src/test/scala/zio/ZEnvironmentIssuesSpec.scala +++ b/core-tests/shared/src/test/scala/zio/ZEnvironmentIssuesSpec.scala @@ -14,8 +14,8 @@ object ZEnvironmentIssuesSpec extends DefaultRunnableSpec { val zio: URIO[Animal, Animal] = ZIO.service[Animal] // Provides a Dog - val dog: Dog = new Dog {} - val dogService: UServiceBuilder[Dog] = ZServiceBuilder.succeed(dog) + val dog: Dog = new Dog {} + val dogService: ULayer[Dog] = ZLayer.succeed(dog) zio.provide(dogService).map { result => assertTrue(result == dog) diff --git a/core-tests/shared/src/test/scala/zio/ZIOSpec.scala b/core-tests/shared/src/test/scala/zio/ZIOSpec.scala index b5b7e1ef47b0..862d86a03e3f 100644 --- a/core-tests/shared/src/test/scala/zio/ZIOSpec.scala +++ b/core-tests/shared/src/test/scala/zio/ZIOSpec.scala @@ -1835,17 +1835,17 @@ object ZIOSpec extends ZIOBaseSpec { ), suite("provideCustom")( test("provides the part of the environment that is not part of the `ZEnv`") { - val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = Logging.live - val zio: ZIO[ZEnv with Logging, Nothing, Unit] = ZIO.unit - val zio2: URIO[ZEnv, Unit] = zio.provideCustom(loggingServiceBuilder) + val loggingLayer: ZLayer[Any, Nothing, Logging] = Logging.live + val zio: ZIO[ZEnv with Logging, Nothing, Unit] = ZIO.unit + val zio2: URIO[ZEnv, Unit] = zio.provideCustom(loggingLayer) assertM(zio2)(anything) } ), suite("provideSome")( test("can split environment into two parts") { - val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = Clock.live - val zio: ZIO[Clock with Random, Nothing, Unit] = ZIO.unit - val zio2: URIO[Random, Unit] = zio.provideSome[Random](clockServiceBuilder) + val clockLayer: ZLayer[Any, Nothing, Clock] = Clock.live + val zio: ZIO[Clock with Random, Nothing, Unit] = ZIO.unit + val zio2: URIO[Random, Unit] = zio.provideSome[Random](clockLayer) assertM(zio2)(anything) } ), @@ -3302,7 +3302,7 @@ object ZIOSpec extends ZIOBaseSpec { suite("serviceWith")( test("effectfully accesses a service in the environment") { val zio = ZIO.serviceWithZIO[Int](int => UIO(int + 3)) - assertM(zio.inject(ZServiceBuilder.succeed(0)))(equalTo(3)) + assertM(zio.inject(ZLayer.succeed(0)))(equalTo(3)) } ), suite("schedule")( @@ -3600,7 +3600,7 @@ object ZIOSpec extends ZIOBaseSpec { a <- ZIO.service[Int].updateService[Int](_ + 1) b <- ZIO.service[Int] } yield (a, b) - assertM(zio.provide(ZServiceBuilder.succeed(0)))(equalTo((1, 0))) + assertM(zio.provide(ZLayer.succeed(0)))(equalTo((1, 0))) } ), suite("validate")( @@ -4054,7 +4054,7 @@ object ZIOSpec extends ZIOBaseSpec { object Logging { trait Service - val live: ZServiceBuilder[Any, Nothing, Logging] = ZServiceBuilder.succeed(new Logging.Service {}) + val live: ZLayer[Any, Nothing, Logging] = ZLayer.succeed(new Logging.Service {}) } } diff --git a/core-tests/shared/src/test/scala/zio/ZLayerSpec.scala b/core-tests/shared/src/test/scala/zio/ZLayerSpec.scala new file mode 100644 index 000000000000..10f9b26422d1 --- /dev/null +++ b/core-tests/shared/src/test/scala/zio/ZLayerSpec.scala @@ -0,0 +1,450 @@ +package zio + +import zio.test.Assertion._ +import zio.test.TestAspect.nonFlaky +import zio.test._ + +object ZLayerSpec extends ZIOBaseSpec { + + import ZIOTag._ + + trait Animal + trait Dog extends Animal + trait Cat extends Animal + + def testSize[R](layer: Layer[Nothing, R], n: Int, label: String = ""): UIO[TestResult] = + layer.build.use(env => ZIO.succeed(assert(env.size)(if (label == "") equalTo(n) else equalTo(n) ?? label))) + + val acquire1 = "Acquiring Module 1" + val acquire2 = "Acquiring Module 2" + val acquire3 = "Acquiring Module 3" + val release1 = "Releasing Module 1" + val release2 = "Releasing Module 2" + val release3 = "Releasing Module 3" + + type Module1 = Module1.Service + + object Module1 { + trait Service + } + + def makeLayer1(ref: Ref[Vector[String]]): ZLayer[Any, Nothing, Module1] = + ZLayer { + ZManaged.acquireReleaseWith(ref.update(_ :+ acquire1).as(new Module1.Service {}))(_ => ref.update(_ :+ release1)) + } + + type Module2 = Module2.Service + + object Module2 { + trait Service + } + + def makeLayer2(ref: Ref[Vector[String]]): ZLayer[Any, Nothing, Module2] = + ZLayer { + ZManaged.acquireReleaseWith(ref.update(_ :+ acquire2).as(new Module2.Service {}))(_ => ref.update(_ :+ release2)) + } + + type Module3 = Module3.Service + + object Module3 { + trait Service + } + + def makeLayer3(ref: Ref[Vector[String]]): ZLayer[Any, Nothing, Module3] = + ZLayer { + ZManaged.acquireReleaseWith(ref.update(_ :+ acquire3).as(new Module3.Service {}))(_ => ref.update(_ :+ release3)) + } + + def makeRef: UIO[Ref[Vector[String]]] = + Ref.make(Vector.empty) + + def spec = + suite("ZLayerSpec")( + test("Size of >>> (1)") { + val layer = ZLayer.succeed(1) >>> ((i: Int) => i.toString).toLayer + + testSize(layer, 1) + }, + test("Size of >>> (2)") { + val layer = ZLayer.succeed(1) >>> + (((i: Int) => i.toString).toLayer ++ + ((i: Int) => i % 2 == 0).toLayer) + + testSize(layer, 2) + }, + test("Size of Test layers") { + for { + r1 <- testSize(Annotations.live, 1, "Annotations.live") + r2 <- testSize(ZEnv.live >>> Live.default >>> TestConsole.debug, 1, "TestConsole.default") + r3 <- testSize(ZEnv.live >>> Live.default, 1, "Live.default") + r4 <- testSize(ZEnv.live >>> TestRandom.deterministic, 1, "TestRandom.live") + r5 <- testSize(Sized.live(100), 1, "Sized.live(100)") + r6 <- testSize(TestSystem.default, 1, "TestSystem.default") + } yield r1 && r2 && r3 && r4 && r5 && r6 + }, + test("Size of >>> (9)") { + val layer = ZEnv.live >>> + (Annotations.live ++ (Live.default >>> TestConsole.debug) ++ + Live.default ++ TestRandom.deterministic ++ Sized.live(100) + ++ TestSystem.default) + + testSize(layer, 6) + }, + test("sharing with ++") { + val expected = Vector(acquire1, release1) + for { + ref <- makeRef + layer1 = makeLayer1(ref) + env = (layer1 ++ layer1).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual)(equalTo(expected)) + } @@ nonFlaky, + test("sharing itself with ++") { + val m1 = new Module1.Service {} + val layer1 = ZLayer.succeed(m1) + val env = layer1 ++ (layer1 ++ layer1) + env.build.use(m => ZIO(assert(m.get)(equalTo(m1)))) + } @@ nonFlaky, + test("sharing with >>>") { + val expected = Vector(acquire1, release1) + for { + ref <- makeRef + layer1 = makeLayer1(ref) + env = (layer1 >>> layer1).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual)(equalTo(expected)) + } @@ nonFlaky, + test("sharing with multiple layers") { + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + layer3 = makeLayer3(ref) + env = ((layer1 >>> layer2) ++ (layer1 >>> layer3)).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual(0))(equalTo(acquire1)) && + assert(actual.slice(1, 3))(hasSameElements(Vector(acquire2, acquire3))) && + assert(actual.slice(3, 5))(hasSameElements(Vector(release2, release3))) && + assert(actual(5))(equalTo(release1)) + } @@ nonFlaky, + test("finalizers with ++") { + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + env = (layer1 ++ layer2).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual.slice(0, 2))(hasSameElements(Vector(acquire1, acquire2))) && + assert(actual.slice(2, 4))(hasSameElements(Vector(release1, release2))) + } @@ nonFlaky, + test("finalizers with >>>") { + val expected = Vector(acquire1, acquire2, release2, release1) + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + env = (layer1 >>> layer2).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual)(equalTo(expected)) + } @@ nonFlaky, + test("finalizers with multiple layers") { + val expected = + Vector(acquire1, acquire2, acquire3, release3, release2, release1) + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + layer3 = makeLayer3(ref) + env = (layer1 >>> layer2 >>> layer3).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual)(equalTo(expected)) + } @@ nonFlaky, + test("map does not interfere with sharing") { + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + layer3 = makeLayer3(ref) + env = ((layer1.map(identity) >>> layer2) ++ (layer1 >>> layer3)).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual(0))(equalTo(acquire1)) && + assert(actual.slice(1, 3))(hasSameElements(Vector(acquire2, acquire3))) && + assert(actual.slice(3, 5))(hasSameElements(Vector(release2, release3))) && + assert(actual(5))(equalTo(release1)) + } @@ nonFlaky, + test("mapError does not interfere with sharing") { + implicit val canFail = CanFail + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + layer3 = makeLayer3(ref) + env = + ((layer1.mapError(identity) >>> layer2) ++ (layer1 >>> layer3)).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual(0))(equalTo(acquire1)) && + assert(actual.slice(1, 3))(hasSameElements(Vector(acquire2, acquire3))) && + assert(actual.slice(3, 5))(hasSameElements(Vector(release2, release3))) && + assert(actual(5))(equalTo(release1)) + } @@ nonFlaky, + test("orDie does not interfere with sharing") { + implicit val canFail = CanFail + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + layer3 = makeLayer3(ref) + env = ((layer1.orDie >>> layer2) ++ (layer1 >>> layer3)).build + _ <- env.useDiscard(ZIO.unit) + actual <- ref.get + } yield assert(actual(0))(equalTo(acquire1)) && + assert(actual.slice(1, 3))(hasSameElements(Vector(acquire2, acquire3))) && + assert(actual.slice(3, 5))(hasSameElements(Vector(release2, release3))) && + assert(actual(5))(equalTo(release1)) + } @@ nonFlaky, + test("interruption with ++") { + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + env = (layer1 ++ layer2).build + fiber <- env.useDiscard(ZIO.unit).fork + _ <- fiber.interrupt + actual <- ref.get + } yield (assert(actual)(contains(acquire1)) ==> assert(actual)(contains(release1))) && + (assert(actual)(contains(acquire2)) ==> assert(actual)(contains(release2))) + } @@ zioTag(interruption) @@ nonFlaky, + test("interruption with >>>") { + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + env = (layer1 >>> layer2).build + fiber <- env.useDiscard(ZIO.unit).fork + _ <- fiber.interrupt + actual <- ref.get + } yield (assert(actual)(contains(acquire1)) ==> assert(actual)(contains(release1))) && + (assert(actual)(contains(acquire2)) ==> assert(actual)(contains(release2))) + } @@ zioTag(interruption) @@ nonFlaky, + test("interruption with multiple layers") { + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + layer3 = makeLayer3(ref) + env = ((layer1 >>> layer2) ++ (layer1 >>> layer3)).build + fiber <- env.useDiscard(ZIO.unit).fork + _ <- fiber.interrupt + actual <- ref.get + } yield (assert(actual)(contains(acquire1)) ==> assert(actual)(contains(release1))) && + (assert(actual)(contains(acquire2)) ==> assert(actual)(contains(release2))) && + (assert(actual)(contains(acquire3)) ==> assert(actual)(contains(release3))) + } @@ zioTag(interruption) @@ nonFlaky, + test("layers can be acquired in parallel") { + for { + promise <- Promise.make[Nothing, Unit] + layer1 = ZLayer(ZManaged.never) + layer2 = + ZLayer(Managed.acquireReleaseWith(promise.succeed(()).map(ZEnvironment(_)))(_ => ZIO.unit)) + env = (layer1 ++ layer2).build + _ <- env.useDiscard(ZIO.unit).forkDaemon + _ <- promise.await + } yield assertCompletes + }, + test("map can map a layer to an unrelated type") { + case class A(name: String, value: Int) + case class B(name: String) + val l1: Layer[Nothing, A] = ZLayer.succeed(A("name", 1)) + val l2: ZLayer[String, Nothing, B] = (B.apply _).toLayer + val live: Layer[Nothing, B] = l1.map(a => ZEnvironment(a.get[A].name)) >>> l2 + assertM(ZIO.service[B].inject(live))(equalTo(B("name"))) + }, + test("memoization") { + val expected = Vector(acquire1, release1) + for { + ref <- makeRef + memoized = makeLayer1(ref).memoize + _ <- memoized.use { layer => + for { + _ <- ZIO.environment[Module1].provide(layer) + _ <- ZIO.environment[Module1].provide(layer) + } yield () + } + actual <- ref.get + } yield assert(actual)(equalTo(expected)) + } @@ nonFlaky, + test("orElse") { + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + env = ((layer1 >>> ZLayer.fail("fail")) orElse layer2).build + fiber <- env.useDiscard(ZIO.unit).fork + _ <- fiber.interrupt + actual <- ref.get + } yield (assert(actual)(contains(acquire1)) ==> assert(actual)(contains(release1))) && + (assert(actual)(contains(acquire2)) ==> assert(actual)(contains(release2))) + } @@ nonFlaky, + test("passthrough") { + val layer: ZLayer[Int, Nothing, String] = + ((_: Int).toString).toLayer + val live: ZLayer[Any, Nothing, Int with String] = + ZLayer.succeed(1) >>> layer.passthrough + val zio = for { + i <- ZIO.service[Int] + s <- ZIO.service[String] + } yield (i, s) + assertM(zio.inject(live))(equalTo((1, "1"))) + }, + test("fresh with ++") { + val expected = Vector(acquire1, acquire1, release1, release1) + for { + ref <- makeRef + layer1 = makeLayer1(ref) + env = (layer1 ++ layer1.fresh).build + _ <- env.useNow + result <- ref.get + } yield assert(result)(equalTo(expected)) + } @@ nonFlaky, + test("fresh with >>>") { + val expected = Vector(acquire1, acquire1, release1, release1) + for { + ref <- makeRef + layer1 = makeLayer1(ref) + env = (layer1 >>> layer1.fresh).build + _ <- env.useNow + result <- ref.get + } yield assert(result)(equalTo(expected)) + } @@ nonFlaky, + test("fresh with multiple layers") { + val expected = Vector(acquire1, acquire1, release1, release1) + for { + ref <- makeRef + layer1 = makeLayer1(ref) + env = ((layer1 ++ layer1) ++ (layer1 ++ layer1).fresh).build + _ <- env.useNow + result <- ref.get + } yield assert(result)(equalTo(expected)) + } @@ nonFlaky, + test("fresh with identical fresh layers") { + for { + ref <- makeRef + layer1 = makeLayer1(ref) + layer2 = makeLayer2(ref) + layer3 = makeLayer3(ref) + env = ((layer1.fresh >>> layer2) ++ (layer1.fresh >>> layer3)).build + _ <- env.useNow + result <- ref.get + } yield assert(result)(hasSize(equalTo(8))) + } @@ nonFlaky, + test("preserves identity of acquired resources") { + for { + testRef <- Ref.make(Vector[String]()) + layer = ZLayer { + for { + ref <- + Ref.make[Vector[String]](Vector()).toManagedWith(ref => ref.get.flatMap(testRef.set)) + _ <- ZManaged.unit + } yield ref + } + _ <- layer.build.use(_.get.update(_ :+ "test")) + result <- testRef.get + } yield assert(result)(equalTo(Vector("test"))) + }, + test("retry") { + for { + ref <- Ref.make(0) + effect = ref.update(_ + 1) *> ZIO.fail("fail") + layer = ZLayer.fromZIOEnvironment(effect).retry(Schedule.recurs(3)) + _ <- layer.build.useNow.ignore + result <- ref.get + } yield assert(result)(equalTo(4)) + }, + test("error handling") { + val sleep = ZIO.sleep(100.milliseconds).inject(Clock.live) + val layer1 = ZLayer.fail("foo") + val layer2 = ZLayer.succeed("bar") + val layer3 = ZLayer.succeed("baz") + val layer4 = ZManaged.acquireReleaseWith(sleep)(_ => sleep).toLayer + val env = layer1 ++ ((layer2 ++ layer3) >+> layer4) + assertM(ZIO.unit.provideCustom(env).exit)(fails(equalTo("foo"))) + }, + test("project") { + final case class Person(name: String, age: Int) + val personLayer = ZLayer.succeed(Person("User", 42)) + val ageLayer = personLayer.project(_.age) + assertM(ZIO.service[Int].inject(ageLayer))(equalTo(42)) + }, + test("tap") { + for { + ref <- Ref.make("foo") + layer = ZLayer.succeed("bar").tap(r => ref.set(r.get)) + _ <- layer.build.useNow + value <- ref.get + } yield assert(value)(equalTo("bar")) + }, + test("provides a partial environment to an effect") { + val needsIntAndString = ZIO.environment[Int & String] + val providesInt = ZLayer.succeed(10) + val needsString = ZIO.provide(providesInt)(needsIntAndString) + needsString + .inject(ZLayer.succeed("hi")) + .map { result => + assertTrue( + result.get[Int] == 10, + result.get[String] == "hi" + ) + } + }, + test(">>> provides a partial environment to another layer") { + final case class FooService(ref: Ref[Int], string: String, boolean: Boolean) { + def get: UIO[(Int, String, Boolean)] = ref.get.map(i => (i, string, boolean)) + } + val fooBuilder = (FooService.apply _).toLayer + val provideRefInt = Ref.make(10).toLayer + + val needsStringAndBoolean = provideRefInt >>> fooBuilder + + ZIO + .serviceWithZIO[FooService](_.get) + .inject(needsStringAndBoolean, ZLayer.succeed("hi"), ZLayer.succeed(true)) + .map { case (int, string, boolean) => + assertTrue( + int == 10, + string == "hi", + boolean == true + ) + } + }, + test(">+> provides a partial environment to another layer") { + final case class FooService(ref: Ref[Int], string: String, boolean: Boolean) { + def get: UIO[(Int, String, Boolean)] = ref.get.map(i => (i, string, boolean)) + } + val fooBuilder = (FooService.apply _).toLayer + val provideRefInt = Ref.make(10).toLayer + + val needsStringAndBoolean = provideRefInt >+> fooBuilder + + ZIO + .serviceWithZIO[FooService](_.get) + .zip(ZIO.serviceWithZIO[Ref[Int]](_.get)) + .inject(needsStringAndBoolean, ZLayer.succeed("hi"), ZLayer.succeed(true)) + .map { case (int, string, boolean, int2) => + assertTrue( + int == 10, + int2 == 10, + string == "hi", + boolean == true + ) + } + } + ) +} diff --git a/core-tests/shared/src/test/scala/zio/ZManagedSpec.scala b/core-tests/shared/src/test/scala/zio/ZManagedSpec.scala index a913200e465e..280c28ff0e94 100644 --- a/core-tests/shared/src/test/scala/zio/ZManagedSpec.scala +++ b/core-tests/shared/src/test/scala/zio/ZManagedSpec.scala @@ -1274,12 +1274,12 @@ object ZManagedSpec extends ZIOBaseSpec { } yield assert(res)(isNone) } ), - suite("toServiceBuilderMany")( - test("converts a managed effect to a service builder") { - val managed = ZEnv.live.build - val serviceBuilder = managed.toServiceBuilderEnvironment - val zio1 = ZIO.environment[ZEnv] - val zio2 = zio1.provide(serviceBuilder) + suite("toLayerMany")( + test("converts a managed effect to a layer") { + val managed = ZEnv.live.build + val layer = managed.toLayerEnvironment + val zio1 = ZIO.environment[ZEnv] + val zio2 = zio1.provide(layer) assertM(zio2)(anything) } ), diff --git a/core-tests/shared/src/test/scala/zio/ZServiceBuilderSpec.scala b/core-tests/shared/src/test/scala/zio/ZServiceBuilderSpec.scala deleted file mode 100644 index 824a245482e5..000000000000 --- a/core-tests/shared/src/test/scala/zio/ZServiceBuilderSpec.scala +++ /dev/null @@ -1,450 +0,0 @@ -package zio - -import zio.test.Assertion._ -import zio.test.TestAspect.nonFlaky -import zio.test._ - -object ZServiceBuilderSpec extends ZIOBaseSpec { - - import ZIOTag._ - - trait Animal - trait Dog extends Animal - trait Cat extends Animal - - def testSize[R](serviceBuilder: ServiceBuilder[Nothing, R], n: Int, label: String = ""): UIO[TestResult] = - serviceBuilder.build.use(env => ZIO.succeed(assert(env.size)(if (label == "") equalTo(n) else equalTo(n) ?? label))) - - val acquire1 = "Acquiring Module 1" - val acquire2 = "Acquiring Module 2" - val acquire3 = "Acquiring Module 3" - val release1 = "Releasing Module 1" - val release2 = "Releasing Module 2" - val release3 = "Releasing Module 3" - - type Module1 = Module1.Service - - object Module1 { - trait Service - } - - def makeServiceBuilder1(ref: Ref[Vector[String]]): ZServiceBuilder[Any, Nothing, Module1] = - ZServiceBuilder { - ZManaged.acquireReleaseWith(ref.update(_ :+ acquire1).as(new Module1.Service {}))(_ => ref.update(_ :+ release1)) - } - - type Module2 = Module2.Service - - object Module2 { - trait Service - } - - def makeServiceBuilder2(ref: Ref[Vector[String]]): ZServiceBuilder[Any, Nothing, Module2] = - ZServiceBuilder { - ZManaged.acquireReleaseWith(ref.update(_ :+ acquire2).as(new Module2.Service {}))(_ => ref.update(_ :+ release2)) - } - - type Module3 = Module3.Service - - object Module3 { - trait Service - } - - def makeServiceBuilder3(ref: Ref[Vector[String]]): ZServiceBuilder[Any, Nothing, Module3] = - ZServiceBuilder { - ZManaged.acquireReleaseWith(ref.update(_ :+ acquire3).as(new Module3.Service {}))(_ => ref.update(_ :+ release3)) - } - - def makeRef: UIO[Ref[Vector[String]]] = - Ref.make(Vector.empty) - - def spec = - suite("ZServiceBuilderSpec")( - test("Size of >>> (1)") { - val serviceBuilder = ZServiceBuilder.succeed(1) >>> ((i: Int) => i.toString).toServiceBuilder - - testSize(serviceBuilder, 1) - }, - test("Size of >>> (2)") { - val serviceBuilder = ZServiceBuilder.succeed(1) >>> - (((i: Int) => i.toString).toServiceBuilder ++ - ((i: Int) => i % 2 == 0).toServiceBuilder) - - testSize(serviceBuilder, 2) - }, - test("Size of Test service builders") { - for { - r1 <- testSize(Annotations.live, 1, "Annotations.live") - r2 <- testSize(ZEnv.live >>> Live.default >>> TestConsole.debug, 1, "TestConsole.default") - r3 <- testSize(ZEnv.live >>> Live.default, 1, "Live.default") - r4 <- testSize(ZEnv.live >>> TestRandom.deterministic, 1, "TestRandom.live") - r5 <- testSize(Sized.live(100), 1, "Sized.live(100)") - r6 <- testSize(TestSystem.default, 1, "TestSystem.default") - } yield r1 && r2 && r3 && r4 && r5 && r6 - }, - test("Size of >>> (9)") { - val serviceBuilder = ZEnv.live >>> - (Annotations.live ++ (Live.default >>> TestConsole.debug) ++ - Live.default ++ TestRandom.deterministic ++ Sized.live(100) - ++ TestSystem.default) - - testSize(serviceBuilder, 6) - }, - test("sharing with ++") { - val expected = Vector(acquire1, release1) - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - env = (serviceBuilder1 ++ serviceBuilder1).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual)(equalTo(expected)) - } @@ nonFlaky, - test("sharing itself with ++") { - val m1 = new Module1.Service {} - val serviceBuilder1 = ZServiceBuilder.succeed(m1) - val env = serviceBuilder1 ++ (serviceBuilder1 ++ serviceBuilder1) - env.build.use(m => ZIO(assert(m.get)(equalTo(m1)))) - } @@ nonFlaky, - test("sharing with >>>") { - val expected = Vector(acquire1, release1) - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - env = (serviceBuilder1 >>> serviceBuilder1).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual)(equalTo(expected)) - } @@ nonFlaky, - test("sharing with multiple service builders") { - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - serviceBuilder3 = makeServiceBuilder3(ref) - env = ((serviceBuilder1 >>> serviceBuilder2) ++ (serviceBuilder1 >>> serviceBuilder3)).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual(0))(equalTo(acquire1)) && - assert(actual.slice(1, 3))(hasSameElements(Vector(acquire2, acquire3))) && - assert(actual.slice(3, 5))(hasSameElements(Vector(release2, release3))) && - assert(actual(5))(equalTo(release1)) - } @@ nonFlaky, - test("finalizers with ++") { - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - env = (serviceBuilder1 ++ serviceBuilder2).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual.slice(0, 2))(hasSameElements(Vector(acquire1, acquire2))) && - assert(actual.slice(2, 4))(hasSameElements(Vector(release1, release2))) - } @@ nonFlaky, - test("finalizers with >>>") { - val expected = Vector(acquire1, acquire2, release2, release1) - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - env = (serviceBuilder1 >>> serviceBuilder2).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual)(equalTo(expected)) - } @@ nonFlaky, - test("finalizers with multiple service builders") { - val expected = - Vector(acquire1, acquire2, acquire3, release3, release2, release1) - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - serviceBuilder3 = makeServiceBuilder3(ref) - env = (serviceBuilder1 >>> serviceBuilder2 >>> serviceBuilder3).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual)(equalTo(expected)) - } @@ nonFlaky, - test("map does not interfere with sharing") { - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - serviceBuilder3 = makeServiceBuilder3(ref) - env = ((serviceBuilder1.map(identity) >>> serviceBuilder2) ++ (serviceBuilder1 >>> serviceBuilder3)).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual(0))(equalTo(acquire1)) && - assert(actual.slice(1, 3))(hasSameElements(Vector(acquire2, acquire3))) && - assert(actual.slice(3, 5))(hasSameElements(Vector(release2, release3))) && - assert(actual(5))(equalTo(release1)) - } @@ nonFlaky, - test("mapError does not interfere with sharing") { - implicit val canFail = CanFail - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - serviceBuilder3 = makeServiceBuilder3(ref) - env = - ((serviceBuilder1.mapError(identity) >>> serviceBuilder2) ++ (serviceBuilder1 >>> serviceBuilder3)).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual(0))(equalTo(acquire1)) && - assert(actual.slice(1, 3))(hasSameElements(Vector(acquire2, acquire3))) && - assert(actual.slice(3, 5))(hasSameElements(Vector(release2, release3))) && - assert(actual(5))(equalTo(release1)) - } @@ nonFlaky, - test("orDie does not interfere with sharing") { - implicit val canFail = CanFail - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - serviceBuilder3 = makeServiceBuilder3(ref) - env = ((serviceBuilder1.orDie >>> serviceBuilder2) ++ (serviceBuilder1 >>> serviceBuilder3)).build - _ <- env.useDiscard(ZIO.unit) - actual <- ref.get - } yield assert(actual(0))(equalTo(acquire1)) && - assert(actual.slice(1, 3))(hasSameElements(Vector(acquire2, acquire3))) && - assert(actual.slice(3, 5))(hasSameElements(Vector(release2, release3))) && - assert(actual(5))(equalTo(release1)) - } @@ nonFlaky, - test("interruption with ++") { - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - env = (serviceBuilder1 ++ serviceBuilder2).build - fiber <- env.useDiscard(ZIO.unit).fork - _ <- fiber.interrupt - actual <- ref.get - } yield (assert(actual)(contains(acquire1)) ==> assert(actual)(contains(release1))) && - (assert(actual)(contains(acquire2)) ==> assert(actual)(contains(release2))) - } @@ zioTag(interruption) @@ nonFlaky, - test("interruption with >>>") { - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - env = (serviceBuilder1 >>> serviceBuilder2).build - fiber <- env.useDiscard(ZIO.unit).fork - _ <- fiber.interrupt - actual <- ref.get - } yield (assert(actual)(contains(acquire1)) ==> assert(actual)(contains(release1))) && - (assert(actual)(contains(acquire2)) ==> assert(actual)(contains(release2))) - } @@ zioTag(interruption) @@ nonFlaky, - test("interruption with multiple service builders") { - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - serviceBuilder3 = makeServiceBuilder3(ref) - env = ((serviceBuilder1 >>> serviceBuilder2) ++ (serviceBuilder1 >>> serviceBuilder3)).build - fiber <- env.useDiscard(ZIO.unit).fork - _ <- fiber.interrupt - actual <- ref.get - } yield (assert(actual)(contains(acquire1)) ==> assert(actual)(contains(release1))) && - (assert(actual)(contains(acquire2)) ==> assert(actual)(contains(release2))) && - (assert(actual)(contains(acquire3)) ==> assert(actual)(contains(release3))) - } @@ zioTag(interruption) @@ nonFlaky, - test("service builders can be acquired in parallel") { - for { - promise <- Promise.make[Nothing, Unit] - serviceBuilder1 = ZServiceBuilder(ZManaged.never) - serviceBuilder2 = - ZServiceBuilder(Managed.acquireReleaseWith(promise.succeed(()).map(ZEnvironment(_)))(_ => ZIO.unit)) - env = (serviceBuilder1 ++ serviceBuilder2).build - _ <- env.useDiscard(ZIO.unit).forkDaemon - _ <- promise.await - } yield assertCompletes - }, - test("map can map a service builder to an unrelated type") { - case class A(name: String, value: Int) - case class B(name: String) - val l1: ServiceBuilder[Nothing, A] = ZServiceBuilder.succeed(A("name", 1)) - val l2: ZServiceBuilder[String, Nothing, B] = (B.apply _).toServiceBuilder - val live: ServiceBuilder[Nothing, B] = l1.map(a => ZEnvironment(a.get[A].name)) >>> l2 - assertM(ZIO.service[B].inject(live))(equalTo(B("name"))) - }, - test("memoization") { - val expected = Vector(acquire1, release1) - for { - ref <- makeRef - memoized = makeServiceBuilder1(ref).memoize - _ <- memoized.use { serviceBuilder => - for { - _ <- ZIO.environment[Module1].provide(serviceBuilder) - _ <- ZIO.environment[Module1].provide(serviceBuilder) - } yield () - } - actual <- ref.get - } yield assert(actual)(equalTo(expected)) - } @@ nonFlaky, - test("orElse") { - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - env = ((serviceBuilder1 >>> ZServiceBuilder.fail("fail")) orElse serviceBuilder2).build - fiber <- env.useDiscard(ZIO.unit).fork - _ <- fiber.interrupt - actual <- ref.get - } yield (assert(actual)(contains(acquire1)) ==> assert(actual)(contains(release1))) && - (assert(actual)(contains(acquire2)) ==> assert(actual)(contains(release2))) - } @@ nonFlaky, - test("passthrough") { - val serviceBuilder: ZServiceBuilder[Int, Nothing, String] = - ((_: Int).toString).toServiceBuilder - val live: ZServiceBuilder[Any, Nothing, Int with String] = - ZServiceBuilder.succeed(1) >>> serviceBuilder.passthrough - val zio = for { - i <- ZIO.service[Int] - s <- ZIO.service[String] - } yield (i, s) - assertM(zio.inject(live))(equalTo((1, "1"))) - }, - test("fresh with ++") { - val expected = Vector(acquire1, acquire1, release1, release1) - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - env = (serviceBuilder1 ++ serviceBuilder1.fresh).build - _ <- env.useNow - result <- ref.get - } yield assert(result)(equalTo(expected)) - } @@ nonFlaky, - test("fresh with >>>") { - val expected = Vector(acquire1, acquire1, release1, release1) - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - env = (serviceBuilder1 >>> serviceBuilder1.fresh).build - _ <- env.useNow - result <- ref.get - } yield assert(result)(equalTo(expected)) - } @@ nonFlaky, - test("fresh with multiple service builders") { - val expected = Vector(acquire1, acquire1, release1, release1) - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - env = ((serviceBuilder1 ++ serviceBuilder1) ++ (serviceBuilder1 ++ serviceBuilder1).fresh).build - _ <- env.useNow - result <- ref.get - } yield assert(result)(equalTo(expected)) - } @@ nonFlaky, - test("fresh with identical fresh service builders") { - for { - ref <- makeRef - serviceBuilder1 = makeServiceBuilder1(ref) - serviceBuilder2 = makeServiceBuilder2(ref) - serviceBuilder3 = makeServiceBuilder3(ref) - env = ((serviceBuilder1.fresh >>> serviceBuilder2) ++ (serviceBuilder1.fresh >>> serviceBuilder3)).build - _ <- env.useNow - result <- ref.get - } yield assert(result)(hasSize(equalTo(8))) - } @@ nonFlaky, - test("preserves identity of acquired resources") { - for { - testRef <- Ref.make(Vector[String]()) - serviceBuilder = ZServiceBuilder { - for { - ref <- - Ref.make[Vector[String]](Vector()).toManagedWith(ref => ref.get.flatMap(testRef.set)) - _ <- ZManaged.unit - } yield ref - } - _ <- serviceBuilder.build.use(_.get.update(_ :+ "test")) - result <- testRef.get - } yield assert(result)(equalTo(Vector("test"))) - }, - test("retry") { - for { - ref <- Ref.make(0) - effect = ref.update(_ + 1) *> ZIO.fail("fail") - serviceBuilder = ZServiceBuilder.fromZIOEnvironment(effect).retry(Schedule.recurs(3)) - _ <- serviceBuilder.build.useNow.ignore - result <- ref.get - } yield assert(result)(equalTo(4)) - }, - test("error handling") { - val sleep = ZIO.sleep(100.milliseconds).inject(Clock.live) - val serviceBuilder1 = ZServiceBuilder.fail("foo") - val serviceBuilder2 = ZServiceBuilder.succeed("bar") - val serviceBuilder3 = ZServiceBuilder.succeed("baz") - val serviceBuilder4 = ZManaged.acquireReleaseWith(sleep)(_ => sleep).toServiceBuilder - val env = serviceBuilder1 ++ ((serviceBuilder2 ++ serviceBuilder3) >+> serviceBuilder4) - assertM(ZIO.unit.provideCustom(env).exit)(fails(equalTo("foo"))) - }, - test("project") { - final case class Person(name: String, age: Int) - val personServiceBuilder = ZServiceBuilder.succeed(Person("User", 42)) - val ageServiceBuilder = personServiceBuilder.project(_.age) - assertM(ZIO.service[Int].inject(ageServiceBuilder))(equalTo(42)) - }, - test("tap") { - for { - ref <- Ref.make("foo") - serviceBuilder = ZServiceBuilder.succeed("bar").tap(r => ref.set(r.get)) - _ <- serviceBuilder.build.useNow - value <- ref.get - } yield assert(value)(equalTo("bar")) - }, - test("provides a partial environment to an effect") { - val needsIntAndString = ZIO.environment[Int & String] - val providesInt = ZServiceBuilder.succeed(10) - val needsString = ZIO.provide(providesInt)(needsIntAndString) - needsString - .inject(ZServiceBuilder.succeed("hi")) - .map { result => - assertTrue( - result.get[Int] == 10, - result.get[String] == "hi" - ) - } - }, - test(">>> provides a partial environment to another service builder") { - final case class FooService(ref: Ref[Int], string: String, boolean: Boolean) { - def get: UIO[(Int, String, Boolean)] = ref.get.map(i => (i, string, boolean)) - } - val fooBuilder = (FooService.apply _).toServiceBuilder - val provideRefInt = Ref.make(10).toServiceBuilder - - val needsStringAndBoolean = provideRefInt >>> fooBuilder - - ZIO - .serviceWithZIO[FooService](_.get) - .inject(needsStringAndBoolean, ZServiceBuilder.succeed("hi"), ZServiceBuilder.succeed(true)) - .map { case (int, string, boolean) => - assertTrue( - int == 10, - string == "hi", - boolean == true - ) - } - }, - test(">+> provides a partial environment to another service builder") { - final case class FooService(ref: Ref[Int], string: String, boolean: Boolean) { - def get: UIO[(Int, String, Boolean)] = ref.get.map(i => (i, string, boolean)) - } - val fooBuilder = (FooService.apply _).toServiceBuilder - val provideRefInt = Ref.make(10).toServiceBuilder - - val needsStringAndBoolean = provideRefInt >+> fooBuilder - - ZIO - .serviceWithZIO[FooService](_.get) - .zip(ZIO.serviceWithZIO[Ref[Int]](_.get)) - .inject(needsStringAndBoolean, ZServiceBuilder.succeed("hi"), ZServiceBuilder.succeed(true)) - .map { case (int, string, boolean, int2) => - assertTrue( - int == 10, - int2 == 10, - string == "hi", - boolean == true - ) - } - } - ) -} diff --git a/core-tests/shared/src/test/scala/zio/ZStateSpec.scala b/core-tests/shared/src/test/scala/zio/ZStateSpec.scala index 61d7f9ea10b7..869097631d07 100644 --- a/core-tests/shared/src/test/scala/zio/ZStateSpec.scala +++ b/core-tests/shared/src/test/scala/zio/ZStateSpec.scala @@ -14,7 +14,7 @@ object ZStateSpec extends DefaultRunnableSpec { _ <- ZIO.updateState[MyState](state => state.copy(counter = state.counter + 1)) count <- ZIO.getStateWith[MyState](_.counter) } yield count - assertM(zio.provide(ZState.make(MyState(0)).toServiceBuilder))(equalTo(1)) + assertM(zio.provide(ZState.make(MyState(0)).toLayer))(equalTo(1)) } ) @@ exceptDotty } diff --git a/core-tests/shared/src/test/scala/zio/autowire/AutoWireSpec.scala b/core-tests/shared/src/test/scala/zio/autowire/AutoWireSpec.scala index 019074014ccb..dc1e2bafc021 100644 --- a/core-tests/shared/src/test/scala/zio/autowire/AutoWireSpec.scala +++ b/core-tests/shared/src/test/scala/zio/autowire/AutoWireSpec.scala @@ -15,11 +15,11 @@ object AutoWireSpec extends ZIOBaseSpec { suite("AutoWireSpec")( suite("ZIO")( suite("`zio.inject`")( - test("automatically constructs a service builder from its dependencies") { - val doubleServiceBuilder: UServiceBuilder[Double] = ZServiceBuilder.succeed(100.1) - val stringServiceBuilder = ZServiceBuilder.succeed("this string is 28 chars long") - val intServiceBuilder = - ZServiceBuilder { + test("automatically constructs a layer from its dependencies") { + val doubleLayer: ULayer[Double] = ZLayer.succeed(100.1) + val stringLayer = ZLayer.succeed("this string is 28 chars long") + val intLayer = + ZLayer { for { str <- ZIO.service[String] double <- ZIO.service[Double] @@ -28,54 +28,54 @@ object AutoWireSpec extends ZIOBaseSpec { val program: URIO[Int, Int] = ZIO.service[Int] val injected: ZIO[Any, Nothing, Int] = - program.inject(intServiceBuilder, stringServiceBuilder, doubleServiceBuilder) + program.inject(intLayer, stringLayer, doubleLayer) injected.map(result => assertTrue(result == 128)) }, - test("automatically memoizes non-val service builders") { - def sideEffectingServiceBuilder(ref: Ref[Int]): ZServiceBuilder[Any, Nothing, String] = - ref.update(_ + 1).as("Howdy").toServiceBuilder + test("automatically memoizes non-val layers") { + def sideEffectingLayer(ref: Ref[Int]): ZLayer[Any, Nothing, String] = + ref.update(_ + 1).as("Howdy").toLayer - val serviceBuilderA: URServiceBuilder[String, Int] = ZServiceBuilder.succeed(1) - val serviceBuilderB: URServiceBuilder[String, Boolean] = ZServiceBuilder.succeed(true) + val layerA: URLayer[String, Int] = ZLayer.succeed(1) + val layerB: URLayer[String, Boolean] = ZLayer.succeed(true) for { ref <- Ref.make(0) _ <- (ZIO.service[Int] <*> ZIO.service[Boolean]) - .inject(serviceBuilderA, serviceBuilderB, sideEffectingServiceBuilder(ref)) + .inject(layerA, layerB, sideEffectingLayer(ref)) result <- ref.get } yield assertTrue(result == 1) }, - test("reports duplicate service builders") { + test("reports duplicate layers") { val checked = - typeCheck("ZIO.service[Int].inject(ZServiceBuilder.succeed(12), ZServiceBuilder.succeed(13))") + typeCheck("ZIO.service[Int].inject(ZLayer.succeed(12), ZLayer.succeed(13))") assertM(checked)( isLeft( - containsStringWithoutAnsi("Int is provided by multiple service builders") && - containsStringWithoutAnsi("ZServiceBuilder.succeed(12)") && - containsStringWithoutAnsi("ZServiceBuilder.succeed(13)") + containsStringWithoutAnsi("Int is provided by multiple layers") && + containsStringWithoutAnsi("ZLayer.succeed(12)") && + containsStringWithoutAnsi("ZLayer.succeed(13)") ) ) } @@ TestAspect.exceptDotty, - test("reports unused, extra service builders") { - val someServiceBuilder: URServiceBuilder[Double, String] = ZServiceBuilder.succeed("hello") - val doubleServiceBuilder: UServiceBuilder[Double] = ZServiceBuilder.succeed(1.0) - val _ = (someServiceBuilder, doubleServiceBuilder) + test("reports unused, extra layers") { + val someLayer: URLayer[Double, String] = ZLayer.succeed("hello") + val doubleLayer: ULayer[Double] = ZLayer.succeed(1.0) + val _ = (someLayer, doubleLayer) val checked = typeCheck( - "ZIO.service[Int].inject(ZServiceBuilder.succeed(12), doubleServiceBuilder, someServiceBuilder)" + "ZIO.service[Int].inject(ZLayer.succeed(12), doubleLayer, someLayer)" ) assertM(checked)(isLeft(containsStringWithoutAnsi("unused"))) } @@ TestAspect.exceptDotty, - test("reports missing top-level service builders") { + test("reports missing top-level layers") { val program: URIO[String with Int, String] = UIO("test") val _ = program - val checked = typeCheck("program.inject(ZServiceBuilder.succeed(3))") + val checked = typeCheck("program.inject(ZLayer.succeed(3))") assertM(checked)(isLeft(containsStringWithoutAnsi("missing String"))) } @@ TestAspect.exceptDotty, - test("reports multiple missing top-level service builders") { + test("reports multiple missing top-level layers") { val program: URIO[String with Int, String] = UIO("test") val _ = program @@ -85,79 +85,79 @@ object AutoWireSpec extends ZIOBaseSpec { ) } @@ TestAspect.exceptDotty, test("reports missing transitive dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URIO[OldLady, Boolean] = ZIO.service[OldLady].flatMap(_.willDie) val _ = program val checked = typeCheck("program.inject(OldLady.live)") assertM(checked)( isLeft( - containsStringWithoutAnsi("missing zio.autowire.AutoWireSpec.TestServiceBuilder.Fly") && - containsStringWithoutAnsi("for TestServiceBuilder.OldLady.live") + containsStringWithoutAnsi("missing zio.autowire.AutoWireSpec.TestLayer.Fly") && + containsStringWithoutAnsi("for TestLayer.OldLady.live") ) ) } @@ TestAspect.exceptDotty, test("reports nested missing transitive dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URIO[OldLady, Boolean] = ZIO.service[OldLady].flatMap(_.willDie) val _ = program val checked = typeCheck("program.inject(OldLady.live, Fly.live)") assertM(checked)( isLeft( - containsStringWithoutAnsi("missing zio.autowire.AutoWireSpec.TestServiceBuilder.Spider") && - containsStringWithoutAnsi("for TestServiceBuilder.Fly.live") + containsStringWithoutAnsi("missing zio.autowire.AutoWireSpec.TestLayer.Spider") && + containsStringWithoutAnsi("for TestLayer.Fly.live") ) ) } @@ TestAspect.exceptDotty, test("reports circular dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URIO[OldLady, Boolean] = ZIO.service[OldLady].flatMap(_.willDie) val _ = program val checked = typeCheck("program.inject(OldLady.live, Fly.manEatingFly)") assertM(checked)( isLeft( - containsStringWithoutAnsi("TestServiceBuilder.Fly.manEatingFly") && + containsStringWithoutAnsi("TestLayer.Fly.manEatingFly") && containsStringWithoutAnsi( - "both requires and is transitively required by TestServiceBuilder.OldLady.live" + "both requires and is transitively required by TestLayer.OldLady.live" ) ) ) } @@ TestAspect.exceptDotty ), suite("injectCustom")( - test("automatically constructs a service builder, leaving off ZEnv") { - val stringServiceBuilder = Console.readLine.orDie.toServiceBuilder - val program = ZIO.service[String].zipWith(Random.nextInt)((str, int) => s"$str $int") + test("automatically constructs a layer, leaving off ZEnv") { + val stringLayer = Console.readLine.orDie.toLayer + val program = ZIO.service[String].zipWith(Random.nextInt)((str, int) => s"$str $int") val provided = TestConsole.feedLines("Your Lucky Number is:") *> - program.injectCustom(stringServiceBuilder) + program.injectCustom(stringLayer) assertM(provided)(equalTo("Your Lucky Number is: -1295463240")) } ), suite("injectSome")( - test("automatically constructs a service builder, leaving off some environment") { - val stringServiceBuilder = Console.readLine.orDie.toServiceBuilder - val program = ZIO.service[String].zipWith(Random.nextInt)((str, int) => s"$str $int") + test("automatically constructs a layer, leaving off some environment") { + val stringLayer = Console.readLine.orDie.toLayer + val program = ZIO.service[String].zipWith(Random.nextInt)((str, int) => s"$str $int") val provided = TestConsole.feedLines("Your Lucky Number is:") *> - program.injectSome[Random with Console](stringServiceBuilder) + program.injectSome[Random with Console](stringLayer) assertM(provided)(equalTo("Your Lucky Number is: -1295463240")) } ), - suite("`ZServiceBuilder.wire`")( - test("automatically constructs a service builder") { - val doubleServiceBuilder = ZServiceBuilder.succeed(100.1) - val stringServiceBuilder: UServiceBuilder[String] = - ZServiceBuilder.succeed("this string is 28 chars long") - val intServiceBuilder = (ZIO.service[String] <*> ZIO.service[Double]).map { case (str, double) => + suite("`ZLayer.wire`")( + test("automatically constructs a layer") { + val doubleLayer = ZLayer.succeed(100.1) + val stringLayer: ULayer[String] = + ZLayer.succeed("this string is 28 chars long") + val intLayer = (ZIO.service[String] <*> ZIO.service[Double]).map { case (str, double) => str.length + double.toInt - }.toServiceBuilder + }.toLayer - val serviceBuilder = - ZServiceBuilder.wire[Int](intServiceBuilder, stringServiceBuilder, doubleServiceBuilder) - val provided = ZIO.service[Int].provide(serviceBuilder) + val layer = + ZLayer.wire[Int](intLayer, stringLayer, doubleLayer) + val provided = ZIO.service[Int].provide(layer) assertM(provided)(equalTo(128)) }, test("correctly decomposes nested, aliased intersection types") { @@ -167,7 +167,7 @@ object AutoWireSpec extends ZIOBaseSpec { type FinalAlias = And2[Int, StringAlias] with HasBooleanDoubleAlias val _ = ZIO.environment[FinalAlias] - val checked = typeCheck("ZServiceBuilder.wire[FinalAlias]()") + val checked = typeCheck("ZLayer.wire[FinalAlias]()") assertM(checked)( isLeft( containsStringWithoutAnsi("missing Int") && @@ -178,19 +178,19 @@ object AutoWireSpec extends ZIOBaseSpec { ) } @@ TestAspect.exceptDotty ), - suite("`ZServiceBuilder.wireSome`")( - test("automatically constructs a service builder, leaving off some remainder") { - val stringServiceBuilder = ZServiceBuilder.succeed("this string is 28 chars long") - val intServiceBuilder = (ZIO.service[String] <*> ZIO.service[Double]).map { case (str, double) => + suite("`ZLayer.wireSome`")( + test("automatically constructs a layer, leaving off some remainder") { + val stringLayer = ZLayer.succeed("this string is 28 chars long") + val intLayer = (ZIO.service[String] <*> ZIO.service[Double]).map { case (str, double) => str.length + double.toInt - }.toServiceBuilder + }.toLayer val program = ZIO.service[Int] - val serviceBuilder = - ZServiceBuilder.wireSome[Double with Boolean, Int](intServiceBuilder, stringServiceBuilder) + val layer = + ZLayer.wireSome[Double with Boolean, Int](intLayer, stringLayer) val provided = program.provide( - ZServiceBuilder.succeed(true) ++ ZServiceBuilder.succeed(100.1) >>> serviceBuilder + ZLayer.succeed(true) ++ ZLayer.succeed(100.1) >>> layer ) assertM(provided)(equalTo(128)) } @@ -198,11 +198,11 @@ object AutoWireSpec extends ZIOBaseSpec { ), suite("ZManaged")( suite("`zmanaged.inject`")( - test("automatically constructs a service builder") { - val doubleServiceBuilder = ZServiceBuilder.succeed(100.1) - val stringServiceBuilder = ZServiceBuilder.succeed("this string is 28 chars long") - val intServiceBuilder = - ZServiceBuilder { + test("automatically constructs a layer") { + val doubleLayer = ZLayer.succeed(100.1) + val stringLayer = ZLayer.succeed("this string is 28 chars long") + val intLayer = + ZLayer { for { str <- ZManaged.service[String] double <- ZManaged.service[Double] @@ -210,31 +210,31 @@ object AutoWireSpec extends ZIOBaseSpec { } val program = ZManaged.service[Int] - val provided = program.inject(intServiceBuilder, stringServiceBuilder, doubleServiceBuilder) + val provided = program.inject(intLayer, stringLayer, doubleLayer) assertM(provided.useNow)(equalTo(128)) }, - test("automatically memoizes non-val service builders") { - def sideEffectingServiceBuilder(ref: Ref[Int]): ZServiceBuilder[Any, Nothing, String] = - ref.update(_ + 1).as("Howdy").toServiceBuilder + test("automatically memoizes non-val layers") { + def sideEffectingLayer(ref: Ref[Int]): ZLayer[Any, Nothing, String] = + ref.update(_ + 1).as("Howdy").toLayer - val serviceBuilderA: URServiceBuilder[String, Int] = ZServiceBuilder.succeed(1) - val serviceBuilderB: URServiceBuilder[String, Boolean] = ZServiceBuilder.succeed(true) + val layerA: URLayer[String, Int] = ZLayer.succeed(1) + val layerB: URLayer[String, Boolean] = ZLayer.succeed(true) (for { ref <- Ref.make(0).toManaged _ <- (ZManaged.service[Int] <*> ZManaged.service[Boolean]) - .inject(serviceBuilderA, serviceBuilderB, sideEffectingServiceBuilder(ref)) + .inject(layerA, layerB, sideEffectingLayer(ref)) result <- ref.get.toManaged } yield assert(result)(equalTo(1))).useNow }, - test("reports missing top-level service builders") { + test("reports missing top-level layers") { val program: ZManaged[String with Int, Nothing, String] = ZManaged.succeed("test") val _ = program - val checked = typeCheck("program.inject(ZServiceBuilder.succeed(3))") + val checked = typeCheck("program.inject(ZLayer.succeed(3))") assertM(checked)(isLeft(containsStringWithoutAnsi("missing String"))) } @@ TestAspect.exceptDotty, - test("reports multiple missing top-level service builders") { + test("reports multiple missing top-level layers") { val program: ZManaged[String with Int, Nothing, String] = ZManaged.succeed("test") val _ = program @@ -244,63 +244,63 @@ object AutoWireSpec extends ZIOBaseSpec { ) } @@ TestAspect.exceptDotty, test("reports missing transitive dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URManaged[OldLady, Boolean] = ZManaged.service[OldLady].flatMap(_.willDie.toManaged) val _ = program val checked = typeCheck("program.inject(OldLady.live)") assertM(checked)( isLeft( - containsStringWithoutAnsi("missing zio.autowire.AutoWireSpec.TestServiceBuilder.Fly") && - containsStringWithoutAnsi("for TestServiceBuilder.OldLady.live") + containsStringWithoutAnsi("missing zio.autowire.AutoWireSpec.TestLayer.Fly") && + containsStringWithoutAnsi("for TestLayer.OldLady.live") ) ) } @@ TestAspect.exceptDotty, test("reports nested missing transitive dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URManaged[OldLady, Boolean] = ZManaged.service[OldLady].flatMap(_.willDie.toManaged) val _ = program val checked = typeCheck("program.inject(OldLady.live, Fly.live)") assertM(checked)( isLeft( - containsStringWithoutAnsi("missing zio.autowire.AutoWireSpec.TestServiceBuilder.Spider") && - containsStringWithoutAnsi("for TestServiceBuilder.Fly.live") + containsStringWithoutAnsi("missing zio.autowire.AutoWireSpec.TestLayer.Spider") && + containsStringWithoutAnsi("for TestLayer.Fly.live") ) ) } @@ TestAspect.exceptDotty, test("reports circular dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URManaged[OldLady, Boolean] = ZManaged.service[OldLady].flatMap(_.willDie.toManaged) val _ = program val checked = typeCheck("program.inject(OldLady.live, Fly.manEatingFly)") assertM(checked)( isLeft( - containsStringWithoutAnsi("TestServiceBuilder.Fly.manEatingFly") && + containsStringWithoutAnsi("TestLayer.Fly.manEatingFly") && containsStringWithoutAnsi( - "both requires and is transitively required by TestServiceBuilder.OldLady.live" + "both requires and is transitively required by TestLayer.OldLady.live" ) ) ) } @@ TestAspect.exceptDotty ), suite("injectCustom")( - test("automatically constructs a service builder, leaving off ZEnv") { - val stringServiceBuilder = Console.readLine.orDie.toServiceBuilder - val program = ZManaged.service[String].zipWith(Random.nextInt.toManaged)((str, int) => s"$str $int") + test("automatically constructs a layer, leaving off ZEnv") { + val stringLayer = Console.readLine.orDie.toLayer + val program = ZManaged.service[String].zipWith(Random.nextInt.toManaged)((str, int) => s"$str $int") val provided = TestConsole.feedLines("Your Lucky Number is:").toManaged *> - program.injectCustom(stringServiceBuilder) + program.injectCustom(stringLayer) assertM(provided.useNow)(equalTo("Your Lucky Number is: -1295463240")) } ), suite("injectSome")( - test("automatically constructs a service builder, leaving off some environment") { - val stringServiceBuilder = Console.readLine.orDie.toServiceBuilder - val program = ZManaged.service[String].zipWith(Random.nextInt.toManaged)((str, int) => s"$str $int") + test("automatically constructs a layer, leaving off some environment") { + val stringLayer = Console.readLine.orDie.toLayer + val program = ZManaged.service[String].zipWith(Random.nextInt.toManaged)((str, int) => s"$str $int") val provided = TestConsole.feedLines("Your Lucky Number is:").toManaged *> - program.injectSome[Random with Console](stringServiceBuilder) + program.injectSome[Random with Console](stringLayer) assertM(provided.useNow)(equalTo("Your Lucky Number is: -1295463240")) } @@ -308,26 +308,26 @@ object AutoWireSpec extends ZIOBaseSpec { ) ) - object TestServiceBuilder { + object TestLayer { trait OldLady { def willDie: UIO[Boolean] } object OldLady { - def live: URServiceBuilder[Fly, OldLady] = ZServiceBuilder.succeed(new OldLady { + def live: URLayer[Fly, OldLady] = ZLayer.succeed(new OldLady { override def willDie: UIO[Boolean] = UIO(false) }) } trait Fly {} object Fly { - def live: URServiceBuilder[Spider, Fly] = ZServiceBuilder.succeed(new Fly {}) - def manEatingFly: URServiceBuilder[OldLady, Fly] = ZServiceBuilder.succeed(new Fly {}) + def live: URLayer[Spider, Fly] = ZLayer.succeed(new Fly {}) + def manEatingFly: URLayer[OldLady, Fly] = ZLayer.succeed(new Fly {}) } trait Spider {} object Spider { - def live: UServiceBuilder[Spider] = ZServiceBuilder.succeed(new Spider {}) + def live: ULayer[Spider] = ZLayer.succeed(new Spider {}) } } } diff --git a/core-tests/shared/src/test/scala/zio/autowire/InjectParameterizedServicesSpec.scala b/core-tests/shared/src/test/scala/zio/autowire/InjectParameterizedServicesSpec.scala index 64d45d845d2b..e1f9dd1b0325 100644 --- a/core-tests/shared/src/test/scala/zio/autowire/InjectParameterizedServicesSpec.scala +++ b/core-tests/shared/src/test/scala/zio/autowire/InjectParameterizedServicesSpec.scala @@ -1,8 +1,8 @@ package zio.autowire -import zio.{Tag, UIO, ZIO, ZServiceBuilder} +import zio.{Tag, UIO, ZIO, ZLayer} import zio.test._ -import zio.UServiceBuilder +import zio.ULayer // https://github.com/kitlangton/zio-magic/issues/76 object InjectParameterizedServicesSpec extends DefaultRunnableSpec { @@ -38,15 +38,15 @@ object InjectParameterizedServicesSpec extends DefaultRunnableSpec { object ParameterizedServiceWithTypeAlias { type Alias = String - val live: UServiceBuilder[ParameterizedService[Alias]] = - ZServiceBuilder.succeed(new ParameterizedService[Alias] { + val live: ULayer[ParameterizedService[Alias]] = + ZLayer.succeed(new ParameterizedService[Alias] { override def something: UIO[Unit] = ZIO.unit }) } object ParameterisedServiceWithoutTypeAlias { - val live: UServiceBuilder[ParameterizedService[String]] = - ZServiceBuilder.succeed(new ParameterizedService[String] { + val live: ULayer[ParameterizedService[String]] = + ZLayer.succeed(new ParameterizedService[String] { override def something: UIO[Unit] = ZIO.unit }) } diff --git a/core-tests/shared/src/test/scala/zio/autowire/InjectSomeSpec.scala b/core-tests/shared/src/test/scala/zio/autowire/InjectSomeSpec.scala index eedbbb79d069..ded60fd3bb3f 100644 --- a/core-tests/shared/src/test/scala/zio/autowire/InjectSomeSpec.scala +++ b/core-tests/shared/src/test/scala/zio/autowire/InjectSomeSpec.scala @@ -18,15 +18,15 @@ object InjectSomeSpec extends DefaultRunnableSpec { } object TestService { - val live: ZServiceBuilder[Clock with Console, Nothing, TestService] = - (TestService.apply _).toServiceBuilder + val live: ZLayer[Clock with Console, Nothing, TestService] = + (TestService.apply _).toLayer } - val partial: ZServiceBuilder[Console, Nothing, Clock with Console with TestService] = - (Clock.live ++ ZServiceBuilder.service[Console]) >+> TestService.live + val partial: ZLayer[Console, Nothing, Clock with Console with TestService] = + (Clock.live ++ ZLayer.service[Console]) >+> TestService.live - val partialServiceBuilder: ZServiceBuilder[Console, Nothing, TestService with Clock] = - ZServiceBuilder.wireSome[Console, TestService with Clock]( + val partialLayer: ZLayer[Console, Nothing, TestService with Clock] = + ZLayer.wireSome[Console, TestService with Clock]( Clock.live, TestService.live ) @@ -59,7 +59,7 @@ object InjectSomeSpec extends DefaultRunnableSpec { .injectSome[Console](Clock.live) }, test("wireSome") { - testCase("wireSome").provideSome[Console](partialServiceBuilder) + testCase("wireSome").provideSome[Console](partialLayer) } ) @@ TestAspect.silent } diff --git a/core/jvm/src/main/scala/zio/metrics/jvm/DefaultJvmMetrics.scala b/core/jvm/src/main/scala/zio/metrics/jvm/DefaultJvmMetrics.scala index 6f9590bdbbf4..9a56fb9f66f6 100644 --- a/core/jvm/src/main/scala/zio/metrics/jvm/DefaultJvmMetrics.scala +++ b/core/jvm/src/main/scala/zio/metrics/jvm/DefaultJvmMetrics.scala @@ -23,10 +23,10 @@ trait DefaultJvmMetrics extends MultipleJvmMetrics { ) /** - * Service builder that starts collecting the same JVM metrics as the - * Prometheus Java client's default exporters + * Layer that starts collecting the same JVM metrics as the Prometheus Java + * client's default exporters */ - lazy val live: ZServiceBuilder[ + lazy val live: ZLayer[ Clock with System, Throwable, BufferPools with ClassLoading with GarbageCollector with MemoryAllocation with MemoryPools with Standard with Thread with VersionInfo diff --git a/core/jvm/src/main/scala/zio/metrics/jvm/JvmMetrics.scala b/core/jvm/src/main/scala/zio/metrics/jvm/JvmMetrics.scala index 7d155df2aec5..4f743f337569 100644 --- a/core/jvm/src/main/scala/zio/metrics/jvm/JvmMetrics.scala +++ b/core/jvm/src/main/scala/zio/metrics/jvm/JvmMetrics.scala @@ -15,12 +15,12 @@ trait JvmMetrics { self => def collectMetrics(implicit trace: ZTraceElement): ZManaged[Clock with System, Throwable, Feature] /** - * A service builder that when constructed forks a fiber that periodically - * updates the JVM metrics + * A layer that when constructed forks a fiber that periodically updates the + * JVM metrics */ - lazy val live: ZServiceBuilder[Clock with System, Throwable, Feature] = { + lazy val live: ZLayer[Clock with System, Throwable, Feature] = { implicit val trace: ZTraceElement = Tracer.newTrace - collectMetrics.toServiceBuilder(featureTag, IsNotIntersection[Feature], trace) + collectMetrics.toLayer(featureTag, IsNotIntersection[Feature], trace) } /** A ZIO application that periodically updates the JVM metrics */ @@ -29,7 +29,7 @@ trait JvmMetrics { self => private implicit val trace: ZTraceElement = Tracer.newTrace override val tag: Tag[Environment] = Tag[Environment] override type Environment = Clock with System with Feature - override val serviceBuilder: ZServiceBuilder[ZIOAppArgs, Any, Environment] = { + override val layer: ZLayer[ZIOAppArgs, Any, Environment] = { Clock.live ++ System.live >+> live } override def run: ZIO[Environment with ZIOAppArgs, Any, Any] = ZIO.unit diff --git a/core/shared/src/main/scala-2/zio/ZIOVersionSpecific.scala b/core/shared/src/main/scala-2/zio/ZIOVersionSpecific.scala index 5a4fde9a0bda..4806abd7abb0 100644 --- a/core/shared/src/main/scala-2/zio/ZIOVersionSpecific.scala +++ b/core/shared/src/main/scala-2/zio/ZIOVersionSpecific.scala @@ -16,7 +16,7 @@ package zio -import zio.internal.macros.ServiceBuilderMacros +import zio.internal.macros.LayerMacros private[zio] trait ZIOVersionSpecific[-R, +E, +A] { self: ZIO[R, E, A] => @@ -28,58 +28,52 @@ private[zio] trait ZIOVersionSpecific[-R, +E, +A] { self: ZIO[R, E, A] => * * {{{ * val zio: ZIO[OldLady with Console, Nothing, Unit] = ??? - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The ZEnv you use later will provide both Blocking to flyServiceBuilder and Console to zio - * val zio2 : ZIO[ZEnv, Nothing, Unit] = zio.injectCustom(oldLadyServiceBuilder, flyServiceBuilder) + * // The ZEnv you use later will provide both Blocking to flyLayer and Console to zio + * val zio2 : ZIO[ZEnv, Nothing, Unit] = zio.injectCustom(oldLadyLayer, flyLayer) * }}} */ - def injectCustom[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZIO[ZEnv, E1, A] = - macro ServiceBuilderMacros.injectSomeImpl[ZIO, ZEnv, R, E1, A] + def injectCustom[E1 >: E](layer: ZLayer[_, E1, _]*): ZIO[ZEnv, E1, A] = + macro LayerMacros.injectSomeImpl[ZIO, ZEnv, R, E1, A] /** * Splits the environment into two parts, assembling one part using the - * specified service builder and leaving the remainder `R0`. + * specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val zio: ZIO[Clock with Random, Nothing, Unit] = ??? * - * val zio2 = zio.injectSome[Random](clockServiceBuilder) + * val zio2 = zio.injectSome[Random](clockLayer) * }}} */ def injectSome[R0]: ProvideSomePartiallyApplied[R0, R, E, A] = new ProvideSomePartiallyApplied[R0, R, E, A](self) /** - * Automatically assembles a service builder for the ZIO effect. + * Automatically assembles a layer for the ZIO effect. */ - def inject[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZIO[Any, E1, A] = - macro ServiceBuilderMacros.injectImpl[ZIO, R, E1, A] + def inject[E1 >: E](layer: ZLayer[_, E1, _]*): ZIO[Any, E1, A] = + macro LayerMacros.injectImpl[ZIO, R, E1, A] } private final class ProvideSomePartiallyApplied[R0, -R, +E, +A](val self: ZIO[R, E, A]) extends AnyVal { def provide[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R], trace: ZTraceElement): ZIO[R0, E1, A] = - self.provide(serviceBuilder) + self.provide(layer) @deprecated("use provide", "2.0.0") def provideLayer[E1 >: E, R1]( - layer: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R], trace: ZTraceElement): ZIO[R0, E1, A] = provide(layer) - @deprecated("use provide", "2.0.0") - def provideServices[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] - )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R], trace: ZTraceElement): ZIO[R0, E1, A] = - provide(serviceBuilder) - def provideSome[R0]: ZIO.ProvideSome[R0, R, E, A] = new ZIO.ProvideSome[R0, R, E, A](self) @@ -87,10 +81,6 @@ private final class ProvideSomePartiallyApplied[R0, -R, +E, +A](val self: ZIO[R, def provideSomeLayer[R0]: ZIO.ProvideSome[R0, R, E, A] = provideSome - @deprecated("use provideSome", "2.0.0") - def provideSomeServices[R0]: ZIO.ProvideSome[R0, R, E, A] = - provideSome - - def apply[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZIO[R0, E1, A] = - macro ServiceBuilderMacros.injectSomeImpl[ZIO, R0, R, E1, A] + def apply[E1 >: E](layer: ZLayer[_, E1, _]*): ZIO[R0, E1, A] = + macro LayerMacros.injectSomeImpl[ZIO, R0, R, E1, A] } diff --git a/core/shared/src/main/scala-2/zio/ZServiceBuilderCompanionVersionSpecific.scala b/core/shared/src/main/scala-2/zio/ZLayerCompanionVersionSpecific.scala similarity index 52% rename from core/shared/src/main/scala-2/zio/ZServiceBuilderCompanionVersionSpecific.scala rename to core/shared/src/main/scala-2/zio/ZLayerCompanionVersionSpecific.scala index 81bf55aadb73..c860b4950fe8 100644 --- a/core/shared/src/main/scala-2/zio/ZServiceBuilderCompanionVersionSpecific.scala +++ b/core/shared/src/main/scala-2/zio/ZLayerCompanionVersionSpecific.scala @@ -18,43 +18,43 @@ package zio import zio.internal.macros.{DummyK, WireMacros} -private[zio] trait ZServiceBuilderCompanionVersionSpecific { +private[zio] trait ZLayerCompanionVersionSpecific { /** - * Automatically assembles a service builder for the provided type. + * Automatically assembles a layer for the provided type. * * {{{ - * ZServiceBuilder.wire[Car](carServiceBuilder, wheelsServiceBuilder, engineServiceBuilder) + * ZLayer.wire[Car](carLayer, wheelsLayer, engineLayer) * }}} */ def wire[R]: WirePartiallyApplied[R] = new WirePartiallyApplied[R] /** - * Automatically constructs a service builder for the provided type `R`, - * leaving a remainder `R0`. + * Automatically constructs a layer for the provided type `R`, leaving a + * remainder `R0`. * * {{{ - * val carServiceBuilder: ZServiceBuilder[Engine with Wheels, Nothing, Car] = ??? - * val wheelsServiceBuilder: ZServiceBuilder[Any, Nothing, Wheels] = ??? + * val carLayer: ZLayer[Engine with Wheels, Nothing, Car] = ??? + * val wheelsLayer: ZLayer[Any, Nothing, Wheels] = ??? * - * val serviceBuilder = ZServiceBuilder.wireSome[Engine, Car](carServiceBuilder, wheelsServiceBuilder) + * val layer = ZLayer.wireSome[Engine, Car](carLayer, wheelsLayer) * }}} */ def wireSome[R0, R]: WireSomePartiallyApplied[R0, R] = new WireSomePartiallyApplied[R0, R] /** - * Automatically constructs a service builder for the provided type `R`, - * leaving a remainder `ZEnv`. This will satisfy all transitive `ZEnv` - * requirements with `ZEnv.any`, allowing them to be provided later. + * Automatically constructs a layer for the provided type `R`, leaving a + * remainder `ZEnv`. This will satisfy all transitive `ZEnv` requirements with + * `ZEnv.any`, allowing them to be provided later. * * {{{ - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The ZEnv you use later will provide both Blocking to flyServiceBuilder and Console to zio - * val serviceBuilder : ZServiceBuilder[ZEnv, Nothing, OldLady] = ZServiceBuilder.wireCustom[OldLady](oldLadyServiceBuilder, flyServiceBuilder) + * // The ZEnv you use later will provide both Blocking to flyLayer and Console to zio + * val layer : ZLayer[ZEnv, Nothing, OldLady] = ZLayer.wireCustom[OldLady](oldLadyLayer, flyLayer) * }}} */ def wireCustom[R]: WireSomePartiallyApplied[ZEnv, R] = @@ -64,8 +64,8 @@ private[zio] trait ZServiceBuilderCompanionVersionSpecific { private[zio] final class WirePartiallyApplied[R](val dummy: Boolean = true) extends AnyVal { def apply[E]( - serviceBuilder: ZServiceBuilder[_, E, _]* - )(implicit dummyKRemainder: DummyK[Any], dummyK: DummyK[R]): ZServiceBuilder[Any, E, R] = + layer: ZLayer[_, E, _]* + )(implicit dummyKRemainder: DummyK[Any], dummyK: DummyK[R]): ZLayer[Any, E, R] = macro WireMacros.wireImpl[E, Any, R] } @@ -73,7 +73,7 @@ private[zio] final class WireSomePartiallyApplied[R0, R]( val dummy: Boolean = true ) extends AnyVal { def apply[E]( - serviceBuilder: ZServiceBuilder[_, E, _]* - )(implicit dummyKRemainder: DummyK[R0], dummyK: DummyK[R]): ZServiceBuilder[R0, E, R] = + layer: ZLayer[_, E, _]* + )(implicit dummyKRemainder: DummyK[R0], dummyK: DummyK[R]): ZLayer[R0, E, R] = macro WireMacros.wireImpl[E, R0, R] } diff --git a/core/shared/src/main/scala-2/zio/ZManagedVersionSpecific.scala b/core/shared/src/main/scala-2/zio/ZManagedVersionSpecific.scala index cf2d12525961..eee72823d9a4 100644 --- a/core/shared/src/main/scala-2/zio/ZManagedVersionSpecific.scala +++ b/core/shared/src/main/scala-2/zio/ZManagedVersionSpecific.scala @@ -16,7 +16,7 @@ package zio -import zio.internal.macros.ServiceBuilderMacros +import zio.internal.macros.LayerMacros private[zio] trait ZManagedVersionSpecific[-R, +E, +A] { self: ZManaged[R, E, A] => @@ -28,57 +28,51 @@ private[zio] trait ZManagedVersionSpecific[-R, +E, +A] { self: ZManaged[R, E, A] * * {{{ * val managed: ZManaged[OldLady with Console, Nothing, Unit] = ??? - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The ZEnv you use later will provide both Blocking to flyServiceBuilder and Console to managed - * val managed2 : ZManaged[ZEnv, Nothing, Unit] = managed.injectCustom(oldLadyServiceBuilder, flyServiceBuilder) + * // The ZEnv you use later will provide both Blocking to flyLayer and Console to managed + * val managed2 : ZManaged[ZEnv, Nothing, Unit] = managed.injectCustom(oldLadyLayer, flyLayer) * }}} */ - def injectCustom[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZManaged[ZEnv, E1, A] = - macro ServiceBuilderMacros.injectSomeImpl[ZManaged, ZEnv, R, E1, A] + def injectCustom[E1 >: E](layer: ZLayer[_, E1, _]*): ZManaged[ZEnv, E1, A] = + macro LayerMacros.injectSomeImpl[ZManaged, ZEnv, R, E1, A] /** * Splits the environment into two parts, assembling one part using the - * specified service builder and leaving the remainder `R0`. + * specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val managed: ZManaged[Clock with Random, Nothing, Unit] = ??? * - * val managed2 = managed.injectSome[Random](clockServiceBuilder) + * val managed2 = managed.injectSome[Random](clockLayer) * }}} */ - def injectSome[R0]: ProvideSomeServiceBuilderManagedPartiallyApplied[R0, R, E, A] = - new ProvideSomeServiceBuilderManagedPartiallyApplied[R0, R, E, A](self) + def injectSome[R0]: ProvideSomeLayerManagedPartiallyApplied[R0, R, E, A] = + new ProvideSomeLayerManagedPartiallyApplied[R0, R, E, A](self) /** - * Automatically assembles a service builder for the ZManaged effect. + * Automatically assembles a layer for the ZManaged effect. */ - def inject[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZManaged[Any, E1, A] = - macro ServiceBuilderMacros.injectImpl[ZManaged, R, E1, A] + def inject[E1 >: E](layer: ZLayer[_, E1, _]*): ZManaged[Any, E1, A] = + macro LayerMacros.injectImpl[ZManaged, R, E1, A] } -private final class ProvideSomeServiceBuilderManagedPartiallyApplied[R0, -R, +E, +A]( +private final class ProvideSomeLayerManagedPartiallyApplied[R0, -R, +E, +A]( val self: ZManaged[R, E, A] ) extends AnyVal { def provide[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R], trace: ZTraceElement): ZManaged[R0, E1, A] = - self.provide(serviceBuilder) + self.provide(layer) @deprecated("use provide", "2.0.0") def provideLayer[E1 >: E, R1]( - layer: ZServiceBuilder[R0, E1, R1] - )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R], trace: ZTraceElement): ZManaged[R0, E1, A] = - provide(layer) - - @deprecated("use provide", "2.0.0") - def provideServices[E1 >: E, R1]( - layer: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R], trace: ZTraceElement): ZManaged[R0, E1, A] = provide(layer) @@ -89,10 +83,6 @@ private final class ProvideSomeServiceBuilderManagedPartiallyApplied[R0, -R, +E, def provideSomeLayer[R0]: ZManaged.ProvideSome[R0, R, E, A] = provideSome - @deprecated("use provideSome", "2.0.0") - def provideSomeServices[R0]: ZManaged.ProvideSome[R0, R, E, A] = - provideSome - - def apply[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZManaged[R0, E1, A] = - macro ServiceBuilderMacros.injectSomeImpl[ZManaged, R0, R, E1, A] + def apply[E1 >: E](layer: ZLayer[_, E1, _]*): ZManaged[R0, E1, A] = + macro LayerMacros.injectSomeImpl[ZManaged, R0, R, E1, A] } diff --git a/core/shared/src/main/scala-2/zio/internal/macros/ServiceBuilderMacroUtils.scala b/core/shared/src/main/scala-2/zio/internal/macros/LayerMacroUtils.scala similarity index 63% rename from core/shared/src/main/scala-2/zio/internal/macros/ServiceBuilderMacroUtils.scala rename to core/shared/src/main/scala-2/zio/internal/macros/LayerMacroUtils.scala index b622c462c1f9..7aba07c67fed 100644 --- a/core/shared/src/main/scala-2/zio/internal/macros/ServiceBuilderMacroUtils.scala +++ b/core/shared/src/main/scala-2/zio/internal/macros/LayerMacroUtils.scala @@ -7,21 +7,21 @@ import java.nio.charset.StandardCharsets import java.util.Base64 import scala.reflect.macros.blackbox -private[zio] trait ServiceBuilderMacroUtils { +private[zio] trait LayerMacroUtils { val c: blackbox.Context import c.universe._ - type ServiceBuilderExpr = c.Expr[ZServiceBuilder[_, _, _]] + type LayerExpr = c.Expr[ZLayer[_, _, _]] def generateExprGraph( - serviceBuilder: Seq[ServiceBuilderExpr] - ): ZServiceBuilderExprBuilder[c.Type, ServiceBuilderExpr] = - generateExprGraph(serviceBuilder.map(getNode).toList) + layer: Seq[LayerExpr] + ): ZLayerExprBuilder[c.Type, LayerExpr] = + generateExprGraph(layer.map(getNode).toList) def generateExprGraph( - nodes: List[Node[c.Type, ServiceBuilderExpr]] - ): ZServiceBuilderExprBuilder[c.Type, ServiceBuilderExpr] = - ZServiceBuilderExprBuilder[c.Type, ServiceBuilderExpr]( + nodes: List[Node[c.Type, LayerExpr]] + ): ZLayerExprBuilder[c.Type, LayerExpr] = + ZLayerExprBuilder[c.Type, LayerExpr]( graph = Graph( nodes = nodes, // They must be `.toString`-ed as a backup in the case of refinement @@ -31,111 +31,111 @@ private[zio] trait ServiceBuilderMacroUtils { showKey = tpe => tpe.toString, showExpr = expr => CleanCodePrinter.show(c)(expr.tree), abort = c.abort(c.enclosingPosition, _), - emptyExpr = reify(ZServiceBuilder.succeed(())), + emptyExpr = reify(ZLayer.succeed(())), composeH = (lhs, rhs) => c.Expr(q"""$lhs ++ $rhs"""), composeV = (lhs, rhs) => c.Expr(q"""$lhs >>> $rhs""") ) - def buildMemoizedServiceBuilder( - exprGraph: ZServiceBuilderExprBuilder[c.Type, ServiceBuilderExpr], + def buildMemoizedLayer( + exprGraph: ZLayerExprBuilder[c.Type, LayerExpr], requirements: List[c.Type] - ): ServiceBuilderExpr = { + ): LayerExpr = { // This is run for its side effects: Reporting compile errors with the original source names. - val _ = exprGraph.buildServiceBuilderFor(requirements) + val _ = exprGraph.buildLayerFor(requirements) val nodes = exprGraph.graph.nodes val memoizedNodes = nodes.map { node => - val freshName = c.freshName("serviceBuilder") + val freshName = c.freshName("layer") val termName = TermName(freshName) - node.copy(value = c.Expr[ZServiceBuilder[_, _, _]](q"$termName")) + node.copy(value = c.Expr[ZLayer[_, _, _]](q"$termName")) } val definitions = memoizedNodes.zip(nodes).map { case (memoizedNode, node) => ValDef(Modifiers(), TermName(memoizedNode.value.tree.toString()), TypeTree(), node.value.tree) } - val serviceBuilderExpr = exprGraph - .copy(graph = Graph[c.Type, ServiceBuilderExpr](memoizedNodes, exprGraph.graph.keyEquals)) - .buildServiceBuilderFor(requirements) + val layerExpr = exprGraph + .copy(graph = Graph[c.Type, LayerExpr](memoizedNodes, exprGraph.graph.keyEquals)) + .buildLayerFor(requirements) c.Expr(q""" ..$definitions - ${serviceBuilderExpr.tree} + ${layerExpr.tree} """) } - def getNode(serviceBuilder: ServiceBuilderExpr): Node[c.Type, ServiceBuilderExpr] = { - val typeArgs = serviceBuilder.actualType.dealias.typeArgs + def getNode(layer: LayerExpr): Node[c.Type, LayerExpr] = { + val typeArgs = layer.actualType.dealias.typeArgs // ZIO[in, _, out] val in = typeArgs.head val out = typeArgs(2) - Node(getRequirements(in), getRequirements(out), serviceBuilder) + Node(getRequirements(in), getRequirements(out), layer) } def getRequirements[T: c.WeakTypeTag]: List[c.Type] = getRequirements(weakTypeOf[T]) def injectBaseImpl[F[_, _, _], R0: c.WeakTypeTag, R: c.WeakTypeTag, E, A]( - serviceBuilder: Seq[c.Expr[ZServiceBuilder[_, E, _]]], + layer: Seq[c.Expr[ZLayer[_, E, _]]], method: String ): c.Expr[F[R0, E, A]] = { - val expr = constructServiceBuilder[R0, R, E](serviceBuilder) + val expr = constructLayer[R0, R, E](layer) c.Expr[F[R0, E, A]](q"${c.prefix}.${TermName(method)}(${expr.tree})") } - def constructServiceBuilder[R0: c.WeakTypeTag, R: c.WeakTypeTag, E]( - serviceBuilder0: Seq[c.Expr[ZServiceBuilder[_, E, _]]] - ): c.Expr[ZServiceBuilder[Any, E, R]] = { - assertProperVarArgs(serviceBuilder0) + def constructLayer[R0: c.WeakTypeTag, R: c.WeakTypeTag, E]( + layer0: Seq[c.Expr[ZLayer[_, E, _]]] + ): c.Expr[ZLayer[Any, E, R]] = { + assertProperVarArgs(layer0) - val debug = serviceBuilder0.collectFirst { + val debug = layer0.collectFirst { _.tree match { - case q"zio.ZServiceBuilder.Debug.tree" => ZServiceBuilder.Debug.Tree - case q"zio.ZServiceBuilder.Debug.mermaid" => ZServiceBuilder.Debug.Mermaid + case q"zio.ZLayer.Debug.tree" => ZLayer.Debug.Tree + case q"zio.ZLayer.Debug.mermaid" => ZLayer.Debug.Mermaid } } - val serviceBuilder = serviceBuilder0.filter { + val layer = layer0.filter { _.tree match { - case q"zio.ZServiceBuilder.Debug.tree" | q"zio.ZServiceBuilder.Debug.mermaid" => false - case _ => true + case q"zio.ZLayer.Debug.tree" | q"zio.ZLayer.Debug.mermaid" => false + case _ => true } } val remainderExpr = if (weakTypeOf[R0] =:= weakTypeOf[ZEnv]) reify(ZEnv.any) - else reify(ZServiceBuilder.environment[R0]) + else reify(ZLayer.environment[R0]) val remainderNode = if (weakTypeOf[R0] =:= weakTypeOf[Any]) List.empty else List(Node(List.empty, getRequirements[R0], remainderExpr)) - val nodes = remainderNode ++ serviceBuilder.map(getNode) + val nodes = remainderNode ++ layer.map(getNode) val graph = generateExprGraph(nodes) val requirements = getRequirements[R] - val expr = buildMemoizedServiceBuilder(graph, requirements) + val expr = buildMemoizedLayer(graph, requirements) debug.foreach { debug => - debugServiceBuilder(debug, graph, requirements) + debugLayer(debug, graph, requirements) } - expr.asInstanceOf[c.Expr[ZServiceBuilder[Any, E, R]]] + expr.asInstanceOf[c.Expr[ZLayer[Any, E, R]]] } - private def debugServiceBuilder( - debug: ZServiceBuilder.Debug, - graph: ZServiceBuilderExprBuilder[c.Type, ServiceBuilderExpr], + private def debugLayer( + debug: ZLayer.Debug, + graph: ZLayerExprBuilder[c.Type, LayerExpr], requirements: List[c.Type] ): Unit = { val graphString: String = eitherToOption( graph.graph - .map(serviceBuilder => RenderedGraph(serviceBuilder.showTree)) + .map(layer => RenderedGraph(layer.showTree)) .buildComplete(requirements) ).get .fold[RenderedGraph](RenderedGraph.Row(List.empty), identity, _ ++ _, _ >>> _) .render - val title = " ZServiceBuilder Wiring Graph ".yellow.bold.inverted + val title = " ZLayer Wiring Graph ".yellow.bold.inverted val builder = new StringBuilder builder ++= "\n" + title + "\n\n" + graphString + "\n\n" - if (debug == ZServiceBuilder.Debug.Mermaid) { + if (debug == ZLayer.Debug.Mermaid) { val mermaidLink: String = generateMermaidJsLink(requirements, graph) builder ++= "Mermaid Live Editor Link".underlined + "\n" + mermaidLink.faint + "\n\n" } @@ -160,11 +160,11 @@ private[zio] trait ServiceBuilderMacroUtils { .distinct } - def assertProperVarArgs(serviceBuilder: Seq[c.Expr[_]]): Unit = { - val _ = serviceBuilder.map(_.tree) collect { case Typed(_, Ident(typeNames.WILDCARD_STAR)) => + def assertProperVarArgs(layer: Seq[c.Expr[_]]): Unit = { + val _ = layer.map(_.tree) collect { case Typed(_, Ident(typeNames.WILDCARD_STAR)) => c.abort( c.enclosingPosition, - "Auto-construction cannot work with `someList: _*` syntax.\nPlease pass the service builders themselves into this method." + "Auto-construction cannot work with `someList: _*` syntax.\nPlease pass the layers themselves into this method." ) } } @@ -191,16 +191,16 @@ private[zio] trait ServiceBuilderMacroUtils { } /** - * Generates a link of the service builder graph for the Mermaid.js graph viz - * library's live-editor (https://mermaid-js.github.io/mermaid-live-editor) + * Generates a link of the layer graph for the Mermaid.js graph viz library's + * live-editor (https://mermaid-js.github.io/mermaid-live-editor) */ private def generateMermaidJsLink[R: c.WeakTypeTag, R0: c.WeakTypeTag, E]( requirements: List[c.Type], - graph: ZServiceBuilderExprBuilder[c.Type, ServiceBuilderExpr] + graph: ZLayerExprBuilder[c.Type, LayerExpr] ): String = { val cool = eitherToOption( graph.graph - .map(serviceBuilder => serviceBuilder.showTree) + .map(layer => layer.showTree) .buildComplete(requirements) ).get diff --git a/core/shared/src/main/scala-2/zio/internal/macros/ServiceBuilderMacros.scala b/core/shared/src/main/scala-2/zio/internal/macros/LayerMacros.scala similarity index 71% rename from core/shared/src/main/scala-2/zio/internal/macros/ServiceBuilderMacros.scala rename to core/shared/src/main/scala-2/zio/internal/macros/LayerMacros.scala index 2fd3cbe6365f..c62d562bdeec 100644 --- a/core/shared/src/main/scala-2/zio/internal/macros/ServiceBuilderMacros.scala +++ b/core/shared/src/main/scala-2/zio/internal/macros/LayerMacros.scala @@ -5,19 +5,19 @@ import zio.internal.ansi.AnsiStringOps import scala.reflect.macros.blackbox -private[zio] class ServiceBuilderMacros(val c: blackbox.Context) extends ServiceBuilderMacroUtils { +private[zio] class LayerMacros(val c: blackbox.Context) extends LayerMacroUtils { import c.universe._ def injectImpl[F[_, _, _], R: c.WeakTypeTag, E, A]( - serviceBuilder: c.Expr[ZServiceBuilder[_, E, _]]* + layer: c.Expr[ZLayer[_, E, _]]* ): c.Expr[F[Any, E, A]] = - injectBaseImpl[F, Any, R, E, A](serviceBuilder, "provide") + injectBaseImpl[F, Any, R, E, A](layer, "provide") def injectSomeImpl[F[_, _, _], R0: c.WeakTypeTag, R: c.WeakTypeTag, E, A]( - serviceBuilder: c.Expr[ZServiceBuilder[_, E, _]]* + layer: c.Expr[ZLayer[_, E, _]]* ): c.Expr[F[R0, E, A]] = { assertEnvIsNotNothing[R0]() - injectBaseImpl[F, R0, R, E, A](serviceBuilder, "provide") + injectBaseImpl[F, R0, R, E, A](layer, "provide") } def debugGetRequirements[R: c.WeakTypeTag]: c.Expr[List[String]] = @@ -38,7 +38,7 @@ private[zio] class ServiceBuilderMacros(val c: blackbox.Context) extends Service if (outType =:= nothingType) { val errorMessage = s""" -${" ZServiceBuilder Wiring Error ".red.bold.inverted} +${" ZLayer Wiring Error ".red.bold.inverted} You must provide a type to ${"injectSome".cyan.bold} (e.g. ${"foo.injectSome".cyan.bold}${"[UserService with Config".red.bold.underlined}${"(AnotherService.live)".cyan.bold}) @@ -52,7 +52,7 @@ This type represents the services you are ${"not".underlined} currently injectin } private[zio] object MacroUnitTestUtils { - def getRequirements[R]: List[String] = macro ServiceBuilderMacros.debugGetRequirements[R] + def getRequirements[R]: List[String] = macro LayerMacros.debugGetRequirements[R] - def showTree(any: Any): String = macro ServiceBuilderMacros.debugShowTree + def showTree(any: Any): String = macro LayerMacros.debugShowTree } diff --git a/core/shared/src/main/scala-2/zio/internal/macros/WireMacros.scala b/core/shared/src/main/scala-2/zio/internal/macros/WireMacros.scala index 5e8725aa48ef..67c886007e0b 100644 --- a/core/shared/src/main/scala-2/zio/internal/macros/WireMacros.scala +++ b/core/shared/src/main/scala-2/zio/internal/macros/WireMacros.scala @@ -1,24 +1,24 @@ package zio.internal.macros import zio.internal.ansi.AnsiStringOps -import zio.ZServiceBuilder +import zio.ZLayer import scala.reflect.macros.blackbox -final class WireMacros(val c: blackbox.Context) extends ServiceBuilderMacroUtils { +final class WireMacros(val c: blackbox.Context) extends LayerMacroUtils { import c.universe._ def wireImpl[ E, R0: c.WeakTypeTag, R: c.WeakTypeTag - ](serviceBuilder: c.Expr[ZServiceBuilder[_, E, _]]*)( + ](layer: c.Expr[ZLayer[_, E, _]]*)( dummyKRemainder: c.Expr[DummyK[R0]], dummyK: c.Expr[DummyK[R]] - ): c.Expr[ZServiceBuilder[R0, E, R]] = { + ): c.Expr[ZLayer[R0, E, R]] = { val _ = (dummyK, dummyKRemainder) assertEnvIsNotNothing[R]() - constructServiceBuilder[R0, R, E](serviceBuilder) + constructLayer[R0, R, E](layer) } /** @@ -31,9 +31,9 @@ final class WireMacros(val c: blackbox.Context) extends ServiceBuilderMacroUtils if (outType == nothingType) { val errorMessage = s""" -${" ZServiceBuilder Wiring Error ".red.bold.inverted} +${" ZLayer Wiring Error ".red.bold.inverted} -You must provide a type to ${"wire".cyan.bold} (e.g. ${"ZServiceBuilder.wire".cyan.bold}${"[A with B]".cyan.bold.underlined}${"(A.live, B.live)".cyan.bold}) +You must provide a type to ${"wire".cyan.bold} (e.g. ${"ZLayer.wire".cyan.bold}${"[A with B]".cyan.bold.underlined}${"(A.live, B.live)".cyan.bold}) """ c.abort(c.enclosingPosition, errorMessage) diff --git a/core/shared/src/main/scala-3/zio/ZIOVersionSpecific.scala b/core/shared/src/main/scala-3/zio/ZIOVersionSpecific.scala index 7a8a7ef7b4dd..7dca40b47ea8 100644 --- a/core/shared/src/main/scala-3/zio/ZIOVersionSpecific.scala +++ b/core/shared/src/main/scala-3/zio/ZIOVersionSpecific.scala @@ -1,6 +1,6 @@ package zio -import zio.internal.macros.ServiceBuilderMacros +import zio.internal.macros.LayerMacros trait ZIOVersionSpecific[-R, +E, +A] { self: ZIO[R, E, A] => /** @@ -10,41 +10,41 @@ trait ZIOVersionSpecific[-R, +E, +A] { self: ZIO[R, E, A] => * * {{{ * val zio: ZIO[OldLady with Console, Nothing, Unit] = ??? - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The ZEnv you use later will provide both Blocking to flyServiceBuilder and Console to zio - * val zio2 : ZIO[ZEnv, Nothing, Unit] = zio.injectCustom(oldLadyServiceBuilder, flyServiceBuilder) + * // The ZEnv you use later will provide both Blocking to flyLayer and Console to zio + * val zio2 : ZIO[ZEnv, Nothing, Unit] = zio.injectCustom(oldLadyLayer, flyLayer) * }}} */ - inline def injectCustom[E1 >: E](inline serviceBuilder: ZServiceBuilder[_,E1,_]*): ZIO[ZEnv, E1, A] = - ${ServiceBuilderMacros.injectImpl[ZEnv, R, E1,A]('self, 'serviceBuilder)} + inline def injectCustom[E1 >: E](inline layer: ZLayer[_,E1,_]*): ZIO[ZEnv, E1, A] = + ${LayerMacros.injectImpl[ZEnv, R, E1,A]('self, 'layer)} /** * Splits the environment into two parts, assembling one part using the - * specified service builder and leaving the remainder `R0`. + * specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val zio: ZIO[Clock with Random, Nothing, Unit] = ??? * - * val zio2 = zio.injectSome[Random](clockServiceBuilder) + * val zio2 = zio.injectSome[Random](clockLayer) * }}} */ def injectSome[R0] = new InjectSomePartiallyApplied[R0, R, E, A](self) /** - * Automatically assembles a service builder for the ZIO effect, which + * Automatically assembles a layer for the ZIO effect, which * translates it to another level. */ - inline def inject[E1 >: E](inline serviceBuilder: ZServiceBuilder[_,E1,_]*): ZIO[Any, E1, A] = - ${ServiceBuilderMacros.injectImpl[Any,R,E1, A]('self, 'serviceBuilder)} + inline def inject[E1 >: E](inline layer: ZLayer[_,E1,_]*): ZIO[Any, E1, A] = + ${LayerMacros.injectImpl[Any,R,E1, A]('self, 'layer)} } private final class InjectSomePartiallyApplied[R0, -R, +E, +A](val self: ZIO[R, E, A]) extends AnyVal { - inline def apply[E1 >: E](inline serviceBuilder: ZServiceBuilder[_, E1, _]*): ZIO[R0, E1, A] = - ${ServiceBuilderMacros.injectImpl[R0, R, E1, A]('self, 'serviceBuilder)} + inline def apply[E1 >: E](inline layer: ZLayer[_, E1, _]*): ZIO[R0, E1, A] = + ${LayerMacros.injectImpl[R0, R, E1, A]('self, 'layer)} } diff --git a/core/shared/src/main/scala-3/zio/ZLayerCompanionVersionSpecific.scala b/core/shared/src/main/scala-3/zio/ZLayerCompanionVersionSpecific.scala new file mode 100644 index 000000000000..0fb196ae74a7 --- /dev/null +++ b/core/shared/src/main/scala-3/zio/ZLayerCompanionVersionSpecific.scala @@ -0,0 +1,40 @@ +package zio + +import zio.internal.macros.LayerMacros + +final class WirePartiallyApplied[R](val dummy: Boolean = true) extends AnyVal { + inline def apply[E](inline layer: ZLayer[_, E, _]*): ZLayer[Any, E, R] = + ${LayerMacros.fromAutoImpl[Any, R, E]('layer)} +} + +final class WireSomePartiallyApplied[R0, R](val dummy: Boolean = true) extends AnyVal { + inline def apply[E](inline layer: ZLayer[_, E, _]*): ZLayer[R0, E, R] = + ${LayerMacros.fromAutoImpl[R0, R, E]('layer)} +} + +trait ZLayerCompanionVersionSpecific { + + /** + * Automatically assembles a layer for the provided type. + * + * {{{ + * val layer = ZLayer.wire[Car](carLayer, wheelsLayer, engineLayer) + * }}} + */ + inline def wire[R]: WirePartiallyApplied[R] = + new WirePartiallyApplied[R]() + + /** + * Automatically assembles a layer for the provided type `R`, + * leaving a remainder `R0`. + * + * {{{ + * val carLayer: ZLayer[Engine with Wheels, Nothing, Car] = ??? + * val wheelsLayer: ZLayer[Any, Nothing, Wheels] = ??? + * + * val layer = ZLayer.wireSome[Engine, Car](carLayer, wheelsLayer) + * }}} + */ + def wireSome[R0, R] = + new WireSomePartiallyApplied[R0, R] +} diff --git a/core/shared/src/main/scala-3/zio/ZManagedVersionSpecific.scala b/core/shared/src/main/scala-3/zio/ZManagedVersionSpecific.scala index 5035dd212cf7..f8a440d34c9c 100644 --- a/core/shared/src/main/scala-3/zio/ZManagedVersionSpecific.scala +++ b/core/shared/src/main/scala-3/zio/ZManagedVersionSpecific.scala @@ -1,6 +1,6 @@ package zio -import zio.internal.macros.ServiceBuilderMacros +import zio.internal.macros.LayerMacros trait ZManagedVersionSpecific[-R, +E, +A] { self: ZManaged[R, E, A] => /** @@ -10,54 +10,54 @@ trait ZManagedVersionSpecific[-R, +E, +A] { self: ZManaged[R, E, A] => * * {{{ * val managed: ZManaged[OldLady with Console, Nothing, Unit] = ??? - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The ZEnv you use later will provide both Blocking to flyServiceBuilder and Console to managed - * val managed2 : ZManaged[ZEnv, Nothing, Unit] = managed.injectCustom(oldLadyServiceBuilder, flyServiceBuilder) + * // The ZEnv you use later will provide both Blocking to flyLayer and Console to managed + * val managed2 : ZManaged[ZEnv, Nothing, Unit] = managed.injectCustom(oldLadyLayer, flyLayer) * }}} */ - inline def injectCustom[E1 >: E](inline serviceBuilder: ZServiceBuilder[_,E1,_]*): ZManaged[ZEnv, E1, A] = - ${ZManagedMacros.injectImpl[ZEnv, R, E1, A]('self, 'serviceBuilder)} + inline def injectCustom[E1 >: E](inline layer: ZLayer[_,E1,_]*): ZManaged[ZEnv, E1, A] = + ${ZManagedMacros.injectImpl[ZEnv, R, E1, A]('self, 'layer)} /** * Splits the environment into two parts, assembling one part using the - * specified service builder and leaving the remainder `R0`. + * specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val managed: ZIO[Clock with Random, Nothing, Unit] = ??? * - * val managed2 = managed.injectSome[Random](clockServiceBuilder) + * val managed2 = managed.injectSome[Random](clockLayer) * }}} */ def injectSome[R0] = new InjectSomeZManagedPartiallyApplied[R0, R, E, A](self) /** - * Automatically assembles a service builder for the ZManaged effect, + * Automatically assembles a layer for the ZManaged effect, * which translates it to another level. */ - inline def inject[E1 >: E](inline serviceBuilder: ZServiceBuilder[_,E1,_]*): ZManaged[Any, E1, A] = - ${ZManagedMacros.injectImpl[Any, R, E1, A]('self, 'serviceBuilder)} + inline def inject[E1 >: E](inline layer: ZLayer[_,E1,_]*): ZManaged[Any, E1, A] = + ${ZManagedMacros.injectImpl[Any, R, E1, A]('self, 'layer)} } private final class InjectSomeZManagedPartiallyApplied[R0, -R, +E, +A](val self: ZManaged[R, E, A]) extends AnyVal { - inline def apply[E1 >: E](inline serviceBuilder: ZServiceBuilder[_, E1, _]*): ZManaged[R0, E1, A] = - ${ZManagedMacros.injectImpl[R0, R, E1, A]('self, 'serviceBuilder)} + inline def apply[E1 >: E](inline layer: ZLayer[_, E1, _]*): ZManaged[R0, E1, A] = + ${ZManagedMacros.injectImpl[R0, R, E1, A]('self, 'layer)} } object ZManagedMacros { import scala.quoted._ - def injectImpl[R0: Type, R: Type, E: Type, A: Type](schedule: Expr[ZManaged[R, E, A]], serviceBuilder: Expr[Seq[ZServiceBuilder[_, E, _]]])(using Quotes): + def injectImpl[R0: Type, R: Type, E: Type, A: Type](schedule: Expr[ZManaged[R, E, A]], layer: Expr[Seq[ZLayer[_, E, _]]])(using Quotes): Expr[ZManaged[R0, E, A]] = { - val serviceBuilderExpr = ServiceBuilderMacros.fromAutoImpl[R0, R, E](serviceBuilder) + val layerExpr = LayerMacros.fromAutoImpl[R0, R, E](layer) '{ - $schedule.provide($serviceBuilderExpr.asInstanceOf[ZServiceBuilder[R0, E, R]]) + $schedule.provide($layerExpr.asInstanceOf[ZLayer[R0, E, R]]) } } } diff --git a/core/shared/src/main/scala-3/zio/ZServiceBuilderCompanionVersionSpecific.scala b/core/shared/src/main/scala-3/zio/ZServiceBuilderCompanionVersionSpecific.scala deleted file mode 100644 index 25f04de3d788..000000000000 --- a/core/shared/src/main/scala-3/zio/ZServiceBuilderCompanionVersionSpecific.scala +++ /dev/null @@ -1,40 +0,0 @@ -package zio - -import zio.internal.macros.ServiceBuilderMacros - -final class WirePartiallyApplied[R](val dummy: Boolean = true) extends AnyVal { - inline def apply[E](inline serviceBuilder: ZServiceBuilder[_, E, _]*): ZServiceBuilder[Any, E, R] = - ${ServiceBuilderMacros.fromAutoImpl[Any, R, E]('serviceBuilder)} -} - -final class WireSomePartiallyApplied[R0, R](val dummy: Boolean = true) extends AnyVal { - inline def apply[E](inline serviceBuilder: ZServiceBuilder[_, E, _]*): ZServiceBuilder[R0, E, R] = - ${ServiceBuilderMacros.fromAutoImpl[R0, R, E]('serviceBuilder)} -} - -trait ZServiceBuilderCompanionVersionSpecific { - - /** - * Automatically assembles a service builder for the provided type. - * - * {{{ - * val serviceBuilder = ZServiceBuilder.wire[Car](carServiceBuilder, wheelsServiceBuilder, engineServiceBuilder) - * }}} - */ - inline def wire[R]: WirePartiallyApplied[R] = - new WirePartiallyApplied[R]() - - /** - * Automatically assembles a service builder for the provided type `R`, - * leaving a remainder `R0`. - * - * {{{ - * val carServiceBuilder: ZServiceBuilder[Engine with Wheels, Nothing, Car] = ??? - * val wheelsServiceBuilder: ZServiceBuilder[Any, Nothing, Wheels] = ??? - * - * val serviceBuilder = ZServiceBuilder.wireSome[Engine, Car](carServiceBuilder, wheelsServiceBuilder) - * }}} - */ - def wireSome[R0, R] = - new WireSomePartiallyApplied[R0, R] -} diff --git a/core/shared/src/main/scala-3/zio/internal/macros/ServiceBuilderMacroUtils.scala b/core/shared/src/main/scala-3/zio/internal/macros/LayerMacroUtils.scala similarity index 51% rename from core/shared/src/main/scala-3/zio/internal/macros/ServiceBuilderMacroUtils.scala rename to core/shared/src/main/scala-3/zio/internal/macros/LayerMacroUtils.scala index e703119714ec..71b1c69478e6 100644 --- a/core/shared/src/main/scala-3/zio/internal/macros/ServiceBuilderMacroUtils.scala +++ b/core/shared/src/main/scala-3/zio/internal/macros/LayerMacroUtils.scala @@ -6,56 +6,56 @@ import scala.compiletime._ import zio.internal.macros.StringUtils.StringOps import zio.internal.ansi.AnsiStringOps -private [zio] object ServiceBuilderMacroUtils { - type ServiceBuilderExpr = Expr[ZServiceBuilder[_,_,_]] +private [zio] object LayerMacroUtils { + type LayerExpr = Expr[ZLayer[_,_,_]] def renderExpr[A](expr: Expr[A])(using Quotes): String = { import quotes.reflect._ expr.asTerm.pos.sourceCode.getOrElse(expr.show) } - def buildMemoizedServiceBuilder(ctx: Quotes)(exprGraph: ZServiceBuilderExprBuilder[ctx.reflect.TypeRepr, ServiceBuilderExpr], requirements: List[ctx.reflect.TypeRepr]) : ServiceBuilderExpr = { + def buildMemoizedLayer(ctx: Quotes)(exprGraph: ZLayerExprBuilder[ctx.reflect.TypeRepr, LayerExpr], requirements: List[ctx.reflect.TypeRepr]) : LayerExpr = { import ctx.reflect._ // This is run for its side effects: Reporting compile errors with the original source names. - val _ = exprGraph.buildServiceBuilderFor(requirements) + val _ = exprGraph.buildLayerFor(requirements) - val serviceBuilderExprs = exprGraph.graph.nodes.map(_.value) + val layerExprs = exprGraph.graph.nodes.map(_.value) - ValDef.let(Symbol.spliceOwner, serviceBuilderExprs.map(_.asTerm)) { idents => - val exprMap = serviceBuilderExprs.zip(idents).toMap + ValDef.let(Symbol.spliceOwner, layerExprs.map(_.asTerm)) { idents => + val exprMap = layerExprs.zip(idents).toMap val valGraph = exprGraph.copy( graph = exprGraph.graph.map { node => val ident = exprMap(node) - ident.asExpr.asInstanceOf[ServiceBuilderExpr] + ident.asExpr.asInstanceOf[LayerExpr] } ) - valGraph.buildServiceBuilderFor(requirements).asTerm - }.asExpr.asInstanceOf[ServiceBuilderExpr] + valGraph.buildLayerFor(requirements).asTerm + }.asExpr.asInstanceOf[LayerExpr] } - def getNodes(serviceBuilder: Expr[Seq[ZServiceBuilder[_,_,_]]])(using ctx:Quotes): List[Node[ctx.reflect.TypeRepr, ServiceBuilderExpr]] = { + def getNodes(layer: Expr[Seq[ZLayer[_,_,_]]])(using ctx:Quotes): List[Node[ctx.reflect.TypeRepr, LayerExpr]] = { import quotes.reflect._ - serviceBuilder match { - case Varargs(serviceBuilder) => - getNodes(serviceBuilder) + layer match { + case Varargs(layer) => + getNodes(layer) case other => report.throwError( - " ZServiceBuilder Wiring Error ".yellow.inverted + "\n" + - "Auto-construction cannot work with `someList: _*` syntax.\nPlease pass the service builders themselves into this method." + " ZLayer Wiring Error ".yellow.inverted + "\n" + + "Auto-construction cannot work with `someList: _*` syntax.\nPlease pass the layers themselves into this method." ) } } - def getNodes(serviceBuilder: Seq[Expr[ZServiceBuilder[_,_,_]]])(using ctx:Quotes): List[Node[ctx.reflect.TypeRepr, ServiceBuilderExpr]] = { + def getNodes(layer: Seq[Expr[ZLayer[_,_,_]]])(using ctx:Quotes): List[Node[ctx.reflect.TypeRepr, LayerExpr]] = { import quotes.reflect._ - serviceBuilder.map { - case '{$serviceBuilder: ZServiceBuilder[in, e, out]} => - val inputs = getRequirements[in]("Input for " + serviceBuilder.show.cyan.bold) - val outputs = getRequirements[out]("Output for " + serviceBuilder.show.cyan.bold) - Node(inputs, outputs, serviceBuilder) + layer.map { + case '{$layer: ZLayer[in, e, out]} => + val inputs = getRequirements[in]("Input for " + layer.show.cyan.bold) + val outputs = getRequirements[out]("Output for " + layer.show.cyan.bold) + Node(inputs, outputs, layer) }.toList } @@ -94,10 +94,10 @@ private [zio] object ServiceBuilderMacroUtils { private[zio] object MacroUnitTestUtils { // def getRequirements[R]: List[String] = '{ -// ServiceBuilderMacros.debugGetRequirements[R] +// LayerMacros.debugGetRequirements[R] // } // // def showTree(any: Any): String = '{ -// ServiceBuilderMacros.debugShowTree +// LayerMacros.debugShowTree // } } diff --git a/core/shared/src/main/scala-3/zio/internal/macros/LayerMacros.scala b/core/shared/src/main/scala-3/zio/internal/macros/LayerMacros.scala new file mode 100644 index 000000000000..d213996958ab --- /dev/null +++ b/core/shared/src/main/scala-3/zio/internal/macros/LayerMacros.scala @@ -0,0 +1,87 @@ +package zio.internal.macros + +import zio.internal.ansi.AnsiStringOps +import zio._ +import scala.quoted._ +import scala.compiletime._ +import zio.internal.macros.StringUtils.StringOps + +import LayerMacroUtils._ + +object LayerMacros { + def injectImpl[R0: Type, R: Type, E: Type, A: Type](zio: Expr[ZIO[R,E,A]], layer: Expr[Seq[ZLayer[_,E,_]]])(using Quotes): Expr[ZIO[R0,E,A]] = { + val layerExpr = fromAutoImpl[R0, R, E](layer) + '{$zio.provide($layerExpr.asInstanceOf[ZLayer[R0,E,R]])} + } + + def fromAutoImpl[R0: Type, R: Type, E: Type](layer0: Expr[Seq[ZLayer[_,E,_]]])(using ctx: Quotes): Expr[ZLayer[R0,E,R]] = { + val deferredRequirements = getRequirements[R0]("Specified Remainder") + val requirements = getRequirements[R](s"Target Environment") + + val (layer, debug) = + layer0 match { + case Varargs(layer0) => + val debug = layer0.collectFirst { + case '{ZLayer.Debug.tree} => ZLayer.Debug.Tree + case '{ZLayer.Debug.mermaid} => ZLayer.Debug.Mermaid + } + val layer = layer0.filter { + case '{ZLayer.Debug.tree} | '{ZLayer.Debug.mermaid} => false + case _ => true + } + (layer, debug) + } + + val zEnvLayer: List[Node[ctx.reflect.TypeRepr, LayerExpr]] = + if (deferredRequirements.nonEmpty) List(Node(List.empty, deferredRequirements, '{ZLayer.environment[R0]})) + else List.empty + + val nodes = zEnvLayer ++ getNodes(layer) + + val dep = buildMemoizedLayer(ctx)(ZLayerExprBuilder.fromNodes(ctx)(nodes), requirements) + '{$dep.asInstanceOf[ZLayer[R0,E,R]] } + } +} + + +trait ExprGraphCompileVariants { self : ZLayerExprBuilder.type => + def fromNodes(ctx: Quotes)(nodes: List[Node[ctx.reflect.TypeRepr, LayerExpr]]): ZLayerExprBuilder[ctx.reflect.TypeRepr, LayerExpr] = { + import ctx.reflect._ + implicit val qcx: ctx.type = ctx + + def renderTypeRepr(typeRepr: TypeRepr)(using Quotes): String = { + import quotes.reflect._ + typeRepr.show + } + + def compileError(message: String) : Nothing = report.throwError(message) + def empty: LayerExpr = '{ZLayer.succeed(())} + def composeH(lhs: LayerExpr, rhs: LayerExpr): LayerExpr = + lhs match { + case '{$lhs: ZLayer[i, e, o]} => + rhs match { + case '{$rhs: ZLayer[i2, e2, o2]} => + '{$lhs.++($rhs)} + } + } + + def composeV(lhs: LayerExpr, rhs: LayerExpr): LayerExpr = + lhs match { + case '{$lhs: ZLayer[i, e, o]} => + rhs match { + case '{$rhs: ZLayer[i2, e2, o2]} => + '{$lhs >>> $rhs.asInstanceOf[ZLayer[o,e2,o2]]} + } + } + + ZLayerExprBuilder( + Graph(nodes, _ <:< _), + renderTypeRepr, + renderExpr, + compileError, + empty, + composeH, + composeV + ) + } +} \ No newline at end of file diff --git a/core/shared/src/main/scala-3/zio/internal/macros/ServiceBuilderMacros.scala b/core/shared/src/main/scala-3/zio/internal/macros/ServiceBuilderMacros.scala deleted file mode 100644 index 24cf08b1ec47..000000000000 --- a/core/shared/src/main/scala-3/zio/internal/macros/ServiceBuilderMacros.scala +++ /dev/null @@ -1,87 +0,0 @@ -package zio.internal.macros - -import zio.internal.ansi.AnsiStringOps -import zio._ -import scala.quoted._ -import scala.compiletime._ -import zio.internal.macros.StringUtils.StringOps - -import ServiceBuilderMacroUtils._ - -object ServiceBuilderMacros { - def injectImpl[R0: Type, R: Type, E: Type, A: Type](zio: Expr[ZIO[R,E,A]], serviceBuilder: Expr[Seq[ZServiceBuilder[_,E,_]]])(using Quotes): Expr[ZIO[R0,E,A]] = { - val serviceBuilderExpr = fromAutoImpl[R0, R, E](serviceBuilder) - '{$zio.provide($serviceBuilderExpr.asInstanceOf[ZServiceBuilder[R0,E,R]])} - } - - def fromAutoImpl[R0: Type, R: Type, E: Type](serviceBuilder0: Expr[Seq[ZServiceBuilder[_,E,_]]])(using ctx: Quotes): Expr[ZServiceBuilder[R0,E,R]] = { - val deferredRequirements = getRequirements[R0]("Specified Remainder") - val requirements = getRequirements[R](s"Target Environment") - - val (serviceBuilder, debug) = - serviceBuilder0 match { - case Varargs(serviceBuilder0) => - val debug = serviceBuilder0.collectFirst { - case '{ZServiceBuilder.Debug.tree} => ZServiceBuilder.Debug.Tree - case '{ZServiceBuilder.Debug.mermaid} => ZServiceBuilder.Debug.Mermaid - } - val serviceBuilder = serviceBuilder0.filter { - case '{ZServiceBuilder.Debug.tree} | '{ZServiceBuilder.Debug.mermaid} => false - case _ => true - } - (serviceBuilder, debug) - } - - val zEnvServiceBuilder: List[Node[ctx.reflect.TypeRepr, ServiceBuilderExpr]] = - if (deferredRequirements.nonEmpty) List(Node(List.empty, deferredRequirements, '{ZServiceBuilder.environment[R0]})) - else List.empty - - val nodes = zEnvServiceBuilder ++ getNodes(serviceBuilder) - - val dep = buildMemoizedServiceBuilder(ctx)(ZServiceBuilderExprBuilder.fromNodes(ctx)(nodes), requirements) - '{$dep.asInstanceOf[ZServiceBuilder[R0,E,R]] } - } -} - - -trait ExprGraphCompileVariants { self : ZServiceBuilderExprBuilder.type => - def fromNodes(ctx: Quotes)(nodes: List[Node[ctx.reflect.TypeRepr, ServiceBuilderExpr]]): ZServiceBuilderExprBuilder[ctx.reflect.TypeRepr, ServiceBuilderExpr] = { - import ctx.reflect._ - implicit val qcx: ctx.type = ctx - - def renderTypeRepr(typeRepr: TypeRepr)(using Quotes): String = { - import quotes.reflect._ - typeRepr.show - } - - def compileError(message: String) : Nothing = report.throwError(message) - def empty: ServiceBuilderExpr = '{ZServiceBuilder.succeed(())} - def composeH(lhs: ServiceBuilderExpr, rhs: ServiceBuilderExpr): ServiceBuilderExpr = - lhs match { - case '{$lhs: ZServiceBuilder[i, e, o]} => - rhs match { - case '{$rhs: ZServiceBuilder[i2, e2, o2]} => - '{$lhs.++($rhs)} - } - } - - def composeV(lhs: ServiceBuilderExpr, rhs: ServiceBuilderExpr): ServiceBuilderExpr = - lhs match { - case '{$lhs: ZServiceBuilder[i, e, o]} => - rhs match { - case '{$rhs: ZServiceBuilder[i2, e2, o2]} => - '{$lhs >>> $rhs.asInstanceOf[ZServiceBuilder[o,e2,o2]]} - } - } - - ZServiceBuilderExprBuilder( - Graph(nodes, _ <:< _), - renderTypeRepr, - renderExpr, - compileError, - empty, - composeH, - composeV - ) - } -} \ No newline at end of file diff --git a/core/shared/src/main/scala/zio/Clock.scala b/core/shared/src/main/scala/zio/Clock.scala index 06dadedf3a82..ca7aab086c09 100644 --- a/core/shared/src/main/scala/zio/Clock.scala +++ b/core/shared/src/main/scala/zio/Clock.scala @@ -172,23 +172,23 @@ trait Clock extends Serializable { object Clock extends ClockPlatformSpecific with Serializable { - val any: ZServiceBuilder[Clock, Nothing, Clock] = - ZServiceBuilder.service[Clock](Tag[Clock], IsNotIntersection[Clock], Tracer.newTrace) + val any: ZLayer[Clock, Nothing, Clock] = + ZLayer.service[Clock](Tag[Clock], IsNotIntersection[Clock], Tracer.newTrace) /** * Constructs a `Clock` service from a `java.time.Clock`. */ - val javaClock: ZServiceBuilder[java.time.Clock, Nothing, Clock] = { + val javaClock: ZLayer[java.time.Clock, Nothing, Clock] = { implicit val trace = Tracer.newTrace - ZServiceBuilder[java.time.Clock, Nothing, Clock] { + ZLayer[java.time.Clock, Nothing, Clock] { for { clock <- ZIO.service[java.time.Clock] } yield ClockJava(clock) } } - val live: ServiceBuilder[Nothing, Clock] = - ZServiceBuilder.succeed[Clock](ClockLive)(Tag[Clock], IsNotIntersection[Clock], Tracer.newTrace) + val live: Layer[Nothing, Clock] = + ZLayer.succeed[Clock](ClockLive)(Tag[Clock], IsNotIntersection[Clock], Tracer.newTrace) /** * An implementation of the `Clock` service backed by a `java.time.Clock`. diff --git a/core/shared/src/main/scala/zio/Console.scala b/core/shared/src/main/scala/zio/Console.scala index eee2f2f8a095..8267d3459ebd 100644 --- a/core/shared/src/main/scala/zio/Console.scala +++ b/core/shared/src/main/scala/zio/Console.scala @@ -52,11 +52,11 @@ trait Console extends Serializable { object Console extends Serializable { - val any: ZServiceBuilder[Console, Nothing, Console] = - ZServiceBuilder.service[Console](Tag[Console], IsNotIntersection[Console], Tracer.newTrace) + val any: ZLayer[Console, Nothing, Console] = + ZLayer.service[Console](Tag[Console], IsNotIntersection[Console], Tracer.newTrace) - val live: ServiceBuilder[Nothing, Console] = - ZServiceBuilder.succeed[Console](ConsoleLive)(Tag[Console], IsNotIntersection[Console], Tracer.newTrace) + val live: Layer[Nothing, Console] = + ZLayer.succeed[Console](ConsoleLive)(Tag[Console], IsNotIntersection[Console], Tracer.newTrace) object ConsoleLive extends Console { diff --git a/core/shared/src/main/scala/zio/FunctionToServiceBuilderSyntax.scala b/core/shared/src/main/scala/zio/FunctionToLayerSyntax.scala similarity index 62% rename from core/shared/src/main/scala/zio/FunctionToServiceBuilderSyntax.scala rename to core/shared/src/main/scala/zio/FunctionToLayerSyntax.scala index 1c250961b950..9c33e030f08a 100644 --- a/core/shared/src/main/scala/zio/FunctionToServiceBuilderSyntax.scala +++ b/core/shared/src/main/scala/zio/FunctionToLayerSyntax.scala @@ -18,21 +18,8 @@ package zio import zio.stacktracer.TracingImplicits.disableAutoTrace -trait FunctionToServiceBuilderOps { - implicit final class Function0ToServiceBuilderSyntax[A: Tag: IsNotIntersection](self: () => A) { - - /** - * Converts this function to a ServiceBuilder. - * - * {{{ - * case class FooLive() extends Foo - * - * val live: UServiceBuilder[Foo] = - * FooLive.toServiceBuilder - * }}} - */ - def toServiceBuilder[A1 >: A: Tag: IsNotIntersection](implicit trace: ZTraceElement): URServiceBuilder[Any, A1] = - UIO(self()).toServiceBuilder +trait FunctionToLayerSyntax { + implicit final class Function0ToLayerOps[A: Tag: IsNotIntersection](self: () => A) { /** * Converts this function to a Layer. @@ -44,28 +31,14 @@ trait FunctionToServiceBuilderOps { * FooLive.toLayer * }}} */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[A1 >: A: Tag: IsNotIntersection](implicit trace: ZTraceElement): URServiceBuilder[Any, A1] = - toServiceBuilder + def toLayer[A1 >: A: Tag: IsNotIntersection](implicit trace: ZTraceElement): URLayer[Any, A1] = + UIO(self()).toLayer } - implicit final class Function1ToServiceBuilderSyntax[A: Tag: IsNotIntersection, B: Tag: IsNotIntersection]( + implicit final class Function1ToLayerOps[A: Tag: IsNotIntersection, B: Tag: IsNotIntersection]( self: A => B ) { - /** - * Converts this function to a ServiceBuilder that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config) extends Foo - * - * val live: URServiceBuilder[Config, Foo] = - * FooLive.toServiceBuilder - * }}} - */ - def toServiceBuilder[B1 >: B: Tag: IsNotIntersection](implicit trace: ZTraceElement): URServiceBuilder[A, B1] = - ZIO.serviceWith[A](self).toServiceBuilder - /** * Converts this function to a Layer that depends upon its inputs. * @@ -76,12 +49,11 @@ trait FunctionToServiceBuilderOps { * FooLive.toLayer * }}} */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[B1 >: B: Tag: IsNotIntersection](implicit trace: ZTraceElement): URServiceBuilder[A, B1] = - toServiceBuilder + def toLayer[B1 >: B: Tag: IsNotIntersection](implicit trace: ZTraceElement): URLayer[A, B1] = + ZIO.serviceWith[A](self).toLayer } - implicit final class Function2ToServiceBuilderSyntax[ + implicit final class Function2ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection @@ -90,40 +62,26 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[C1 >: C: Tag: IsNotIntersection](implicit + def toLayer[C1 >: C: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B, C1] = { + ): URLayer[A with B, C1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] } yield self(a, b) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[C1 >: C: Tag: IsNotIntersection](implicit trace: ZTraceElement): URServiceBuilder[A with B, C1] = - toServiceBuilder + }.toLayer } - implicit final class Function3ToServiceBuilderSyntax[ + implicit final class Function3ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -131,43 +89,27 @@ trait FunctionToServiceBuilderOps { ](self: (A, B, C) => D) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[D1 >: D: Tag: IsNotIntersection](implicit + def toLayer[D1 >: D: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C, D1] = { + ): URLayer[A with B with C, D1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] c <- ZIO.service[C] } yield self(a, b, c) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[D1 >: D: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C, D1] = - toServiceBuilder + }.toLayer } - implicit final class Function4ToServiceBuilderSyntax[ + implicit final class Function4ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -178,44 +120,28 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[E1 >: E: Tag: IsNotIntersection](implicit + def toLayer[E1 >: E: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D, E1] = { + ): URLayer[A with B with C with D, E1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] c <- ZIO.service[C] d <- ZIO.service[D] } yield self(a, b, c, d) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[E1 >: E: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D, E1] = - toServiceBuilder + }.toLayer } - implicit final class Function5ToServiceBuilderSyntax[ + implicit final class Function5ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -227,18 +153,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[F1 >: F: Tag: IsNotIntersection](implicit + def toLayer[F1 >: F: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E, F1] = { + ): URLayer[A with B with C with D with E, F1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -246,26 +172,10 @@ trait FunctionToServiceBuilderOps { d <- ZIO.service[D] e <- ZIO.service[E] } yield self(a, b, c, d, e) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[F1 >: F: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E, F1] = - toServiceBuilder + }.toLayer } - implicit final class Function6ToServiceBuilderSyntax[ + implicit final class Function6ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -278,18 +188,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[G1 >: G: Tag: IsNotIntersection](implicit + def toLayer[G1 >: G: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F, G1] = { + ): URLayer[A with B with C with D with E with F, G1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -298,26 +208,10 @@ trait FunctionToServiceBuilderOps { e <- ZIO.service[E] f <- ZIO.service[F] } yield self(a, b, c, d, e, f) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[G1 >: G: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F, G1] = - toServiceBuilder + }.toLayer } - implicit final class Function7ToServiceBuilderSyntax[ + implicit final class Function7ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -331,18 +225,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[H1 >: H: Tag: IsNotIntersection](implicit + def toLayer[H1 >: H: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G, H1] = { + ): URLayer[A with B with C with D with E with F with G, H1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -352,26 +246,10 @@ trait FunctionToServiceBuilderOps { f <- ZIO.service[F] g <- ZIO.service[G] } yield self(a, b, c, d, e, f, g) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[H1 >: H: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G, H1] = - toServiceBuilder + }.toLayer } - implicit final class Function8ToServiceBuilderSyntax[ + implicit final class Function8ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -386,18 +264,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[I1 >: I: Tag: IsNotIntersection](implicit + def toLayer[I1 >: I: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H, I1] = { + ): URLayer[A with B with C with D with E with F with G with H, I1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -408,26 +286,10 @@ trait FunctionToServiceBuilderOps { g <- ZIO.service[G] h <- ZIO.service[H] } yield self(a, b, c, d, e, f, g, h) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[I1 >: I: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H, I1] = - toServiceBuilder + }.toLayer } - implicit final class Function9ToServiceBuilderSyntax[ + implicit final class Function9ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -443,18 +305,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[J1 >: J: Tag: IsNotIntersection](implicit + def toLayer[J1 >: J: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I, J1] = { + ): URLayer[A with B with C with D with E with F with G with H with I, J1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -466,26 +328,10 @@ trait FunctionToServiceBuilderOps { h <- ZIO.service[H] i <- ZIO.service[I] } yield self(a, b, c, d, e, f, g, h, i) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[J1 >: J: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I, J1] = - toServiceBuilder + }.toLayer } - implicit final class Function10ToServiceBuilderSyntax[ + implicit final class Function10ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -502,18 +348,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[K1 >: K: Tag: IsNotIntersection](implicit + def toLayer[K1 >: K: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I with J, K1] = { + ): URLayer[A with B with C with D with E with F with G with H with I with J, K1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -526,26 +372,10 @@ trait FunctionToServiceBuilderOps { i <- ZIO.service[I] j <- ZIO.service[J] } yield self(a, b, c, d, e, f, g, h, i, j) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[K1 >: K: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I with J, K1] = - toServiceBuilder + }.toLayer } - implicit final class Function11ToServiceBuilderSyntax[ + implicit final class Function11ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -563,18 +393,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[L1 >: L: Tag: IsNotIntersection](implicit + def toLayer[L1 >: L: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I with J with K, L1] = { + ): URLayer[A with B with C with D with E with F with G with H with I with J with K, L1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -588,26 +418,10 @@ trait FunctionToServiceBuilderOps { j <- ZIO.service[J] k <- ZIO.service[K] } yield self(a, b, c, d, e, f, g, h, i, j, k) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[L1 >: L: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I with J with K, L1] = - toServiceBuilder + }.toLayer } - implicit final class Function12ToServiceBuilderSyntax[ + implicit final class Function12ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -626,18 +440,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[M1 >: M: Tag: IsNotIntersection](implicit + def toLayer[M1 >: M: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I with J with K with L, M1] = { + ): URLayer[A with B with C with D with E with F with G with H with I with J with K with L, M1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -652,25 +466,9 @@ trait FunctionToServiceBuilderOps { k <- ZIO.service[K] l <- ZIO.service[L] } yield self(a, b, c, d, e, f, g, h, i, j, k, l) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[M1 >: M: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I with J with K with L, M1] = - toServiceBuilder + }.toLayer } - implicit final class Function13ToServiceBuilderSyntax[ + implicit final class Function13ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -690,18 +488,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[N1 >: N: Tag: IsNotIntersection](implicit + def toLayer[N1 >: N: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I with J with K with L with M, N1] = { + ): URLayer[A with B with C with D with E with F with G with H with I with J with K with L with M, N1] = { for { a <- ZIO.service[A] b <- ZIO.service[B] @@ -717,26 +515,10 @@ trait FunctionToServiceBuilderOps { l <- ZIO.service[L] m <- ZIO.service[M] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[N1 >: N: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[A with B with C with D with E with F with G with H with I with J with K with L with M, N1] = - toServiceBuilder + }.toLayer } - implicit final class Function14ToServiceBuilderSyntax[ + implicit final class Function14ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -757,18 +539,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[O1 >: O: Tag: IsNotIntersection](implicit + def toLayer[O1 >: O: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[ + ): URLayer[ A with B with C with D with E with F with G with H with I with J with K with L with M with N, O1 ] = { @@ -788,29 +570,10 @@ trait FunctionToServiceBuilderOps { m <- ZIO.service[M] n <- ZIO.service[N] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m, n) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[O1 >: O: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[ - A with B with C with D with E with F with G with H with I with J with K with L with M with N, - O1 - ] = - toServiceBuilder + }.toLayer } - implicit final class Function15ToServiceBuilderSyntax[ + implicit final class Function15ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -832,18 +595,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[P1 >: P: Tag: IsNotIntersection](implicit + def toLayer[P1 >: P: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[ + ): URLayer[ A with B with C with D with E with F with G with H with I with J with K with L with M with N with O, P1 ] = { @@ -864,29 +627,10 @@ trait FunctionToServiceBuilderOps { n <- ZIO.service[N] o <- ZIO.service[O] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[P1 >: P: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[ - A with B with C with D with E with F with G with H with I with J with K with L with M with N with O, - P1 - ] = - toServiceBuilder + }.toLayer } - implicit final class Function16ToServiceBuilderSyntax[ + implicit final class Function16ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -909,18 +653,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[Q1 >: Q: Tag: IsNotIntersection](implicit + def toLayer[Q1 >: Q: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[ + ): URLayer[ A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P, Q1 ] = { @@ -942,29 +686,10 @@ trait FunctionToServiceBuilderOps { o <- ZIO.service[O] p <- ZIO.service[P] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[Q1 >: Q: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[ - A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P, - Q1 - ] = - toServiceBuilder + }.toLayer } - implicit final class Function17ToServiceBuilderSyntax[ + implicit final class Function17ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -988,18 +713,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[R1 >: R: Tag: IsNotIntersection](implicit + def toLayer[R1 >: R: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[ + ): URLayer[ A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q, R1 ] = { @@ -1022,29 +747,10 @@ trait FunctionToServiceBuilderOps { p <- ZIO.service[P] q <- ZIO.service[Q] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[R1 >: R: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[ - A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q, - R1 - ] = - toServiceBuilder + }.toLayer } - implicit final class Function18ToServiceBuilderSyntax[ + implicit final class Function18ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -1069,18 +775,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[S1 >: S: Tag: IsNotIntersection](implicit + def toLayer[S1 >: S: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[ + ): URLayer[ A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q with R, S1 ] = { @@ -1104,29 +810,10 @@ trait FunctionToServiceBuilderOps { q <- ZIO.service[Q] r <- ZIO.service[R] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[S1 >: S: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[ - A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q with R, - S1 - ] = - toServiceBuilder + }.toLayer } - implicit final class Function19ToServiceBuilderSyntax[ + implicit final class Function19ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -1152,18 +839,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[T1 >: T: Tag: IsNotIntersection](implicit + def toLayer[T1 >: T: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[ + ): URLayer[ A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q with R with S, T1 ] = { @@ -1188,29 +875,10 @@ trait FunctionToServiceBuilderOps { r <- ZIO.service[R] s <- ZIO.service[S] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[T1 >: T: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[ - A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q with R with S, - T1 - ] = - toServiceBuilder + }.toLayer } - implicit final class Function20ToServiceBuilderSyntax[ + implicit final class Function20ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -1237,18 +905,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[U1 >: U: Tag: IsNotIntersection](implicit + def toLayer[U1 >: U: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[ + ): URLayer[ A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q with R with S with T, U1 ] = { @@ -1274,29 +942,10 @@ trait FunctionToServiceBuilderOps { s <- ZIO.service[S] t <- ZIO.service[T] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[U1 >: U: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[ - A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q with R with S with T, - U1 - ] = - toServiceBuilder + }.toLayer } - implicit final class Function21ToServiceBuilderSyntax[ + implicit final class Function21ToLayerOps[ A: Tag: IsNotIntersection, B: Tag: IsNotIntersection, C: Tag: IsNotIntersection, @@ -1324,18 +973,18 @@ trait FunctionToServiceBuilderOps { ) { /** - * Converts this function to a ServiceBuilder that depends upon its inputs. + * Converts this function to a Layer that depends upon its inputs. * * {{{ * case class FooLive(config: Config, repo: Repo) extends Foo * - * val live: URServiceBuilder[Config with Repo, Foo] = - * FooLive.toServiceBuilder + * val live: URLayer[Config with Repo, Foo] = + * FooLive.toLayer * }}} */ - def toServiceBuilder[V1 >: V: Tag: IsNotIntersection](implicit + def toLayer[V1 >: V: Tag: IsNotIntersection](implicit trace: ZTraceElement - ): URServiceBuilder[ + ): URLayer[ A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q with R with S with T with U, V1 ] = { @@ -1362,26 +1011,7 @@ trait FunctionToServiceBuilderOps { t <- ZIO.service[T] u <- ZIO.service[U] } yield self(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) - }.toServiceBuilder - - /** - * Converts this function to a Layer that depends upon its inputs. - * - * {{{ - * case class FooLive(config: Config, repo: Repo) extends Foo - * - * val live: URLayer[Config with Repo, Foo] = - * FooLive.toLayer - * }}} - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[V1 >: V: Tag: IsNotIntersection](implicit - trace: ZTraceElement - ): URServiceBuilder[ - A with B with C with D with E with F with G with H with I with J with K with L with M with N with O with P with Q with R with S with T with U, - V1 - ] = - toServiceBuilder + }.toLayer } } diff --git a/core/shared/src/main/scala/zio/Random.scala b/core/shared/src/main/scala/zio/Random.scala index eb0cf2928bef..556d49844841 100644 --- a/core/shared/src/main/scala/zio/Random.scala +++ b/core/shared/src/main/scala/zio/Random.scala @@ -98,20 +98,20 @@ object Random extends Serializable { Random.shuffleWith(nextIntBounded(_), collection) } - val any: ZServiceBuilder[Random, Nothing, Random] = { - ZServiceBuilder.service[Random](Tag[Random], IsNotIntersection[Random], Tracer.newTrace) + val any: ZLayer[Random, Nothing, Random] = { + ZLayer.service[Random](Tag[Random], IsNotIntersection[Random], Tracer.newTrace) } - val live: ServiceBuilder[Nothing, Random] = { - ZServiceBuilder.succeed[Random](RandomLive)(Tag[Random], IsNotIntersection[Random], Tracer.newTrace) + val live: Layer[Nothing, Random] = { + ZLayer.succeed[Random](RandomLive)(Tag[Random], IsNotIntersection[Random], Tracer.newTrace) } /** * Constructs a `Random` service from a `scala.util.Random`. */ - val scalaRandom: ZServiceBuilder[scala.util.Random, Nothing, Random] = { + val scalaRandom: ZLayer[scala.util.Random, Nothing, Random] = { implicit val trace = Tracer.newTrace - ZServiceBuilder { + ZLayer { for { random <- ZIO.service[scala.util.Random] } yield RandomScala(random) diff --git a/core/shared/src/main/scala/zio/Runtime.scala b/core/shared/src/main/scala/zio/Runtime.scala index 5e6e06c37e2c..c72acac58e4e 100644 --- a/core/shared/src/main/scala/zio/Runtime.scala +++ b/core/shared/src/main/scala/zio/Runtime.scala @@ -408,22 +408,22 @@ object Runtime { lazy val global: Runtime[ZEnv] = Runtime(ZEnvironment.default, RuntimeConfig.global) /** - * Unsafely creates a `Runtime` from a `ZServiceBuilder` whose resources will - * be allocated immediately, and not released until the `Runtime` is shut down - * or the end of the application. + * Unsafely creates a `Runtime` from a `ZLayer` whose resources will be + * allocated immediately, and not released until the `Runtime` is shut down or + * the end of the application. * * This method is useful for small applications and integrating ZIO with * legacy code, but other applications should investigate using * [[ZIO.provide]] directly in their application entry points. */ - def unsafeFromServiceBuilder[R]( - serviceBuilder: ServiceBuilder[Any, R], + def unsafeFromLayer[R]( + layer: Layer[Any, R], runtimeConfig: RuntimeConfig = RuntimeConfig.default )(implicit trace: ZTraceElement): Runtime.Managed[R] = { val runtime = Runtime(ZEnvironment.empty, runtimeConfig) val (environment, shutdown) = runtime.unsafeRun { ZManaged.ReleaseMap.make.flatMap { releaseMap => - ZManaged.currentReleaseMap.locally(releaseMap)(serviceBuilder.build.zio).flatMap { case (_, acquire) => + ZManaged.currentReleaseMap.locally(releaseMap)(layer.build.zio).flatMap { case (_, acquire) => val finalizer = () => runtime.unsafeRun { releaseMap.releaseAll(Exit.unit, ExecutionStrategy.Sequential).uninterruptible.unit @@ -436,20 +436,4 @@ object Runtime { Runtime.Managed(environment, runtimeConfig, shutdown) } - - /** - * Unsafely creates a `Runtime` from a `ZServiceBuilder` whose resources will - * be allocated immediately, and not released until the `Runtime` is shut down - * or the end of the application. - * - * This method is useful for small applications and integrating ZIO with - * legacy code, but other applications should investigate using - * [[ZIO.provideLayer]] directly in their application entry points. - */ - @deprecated("Use unsafeFromServiceBuilder", "2.0.0") - def unsafeFromLayer[R]( - layer: Layer[Any, R], - runtimeConfig: RuntimeConfig = RuntimeConfig.default - )(implicit trace: ZTraceElement): Runtime.Managed[R] = - unsafeFromServiceBuilder(layer, runtimeConfig) } diff --git a/core/shared/src/main/scala/zio/System.scala b/core/shared/src/main/scala/zio/System.scala index c3f1724ac98d..5bb6e28f3f65 100644 --- a/core/shared/src/main/scala/zio/System.scala +++ b/core/shared/src/main/scala/zio/System.scala @@ -50,14 +50,14 @@ trait System extends Serializable { object System extends Serializable { - val any: ZServiceBuilder[System, Nothing, System] = { + val any: ZLayer[System, Nothing, System] = { implicit val trace = Tracer.newTrace - ZServiceBuilder.service[System] + ZLayer.service[System] } - val live: ServiceBuilder[Nothing, System] = { + val live: Layer[Nothing, System] = { implicit val trace = Tracer.newTrace - ZServiceBuilder.succeed[System](SystemLive) + ZLayer.succeed[System](SystemLive) } object SystemLive extends System { diff --git a/core/shared/src/main/scala/zio/ZEnv.scala b/core/shared/src/main/scala/zio/ZEnv.scala index d8ec3058c005..019ab83dadb2 100644 --- a/core/shared/src/main/scala/zio/ZEnv.scala +++ b/core/shared/src/main/scala/zio/ZEnv.scala @@ -31,9 +31,9 @@ object ZEnv { ) } - val any: ZServiceBuilder[ZEnv, Nothing, ZEnv] = - ZServiceBuilder.environment[ZEnv](Tracer.newTrace) + val any: ZLayer[ZEnv, Nothing, ZEnv] = + ZLayer.environment[ZEnv](Tracer.newTrace) - val live: ServiceBuilder[Nothing, ZEnv] = + val live: Layer[Nothing, ZEnv] = Clock.live ++ Console.live ++ System.live ++ Random.live } diff --git a/core/shared/src/main/scala/zio/ZIO.scala b/core/shared/src/main/scala/zio/ZIO.scala index a710a26485d6..6d4fc8bab495 100644 --- a/core/shared/src/main/scala/zio/ZIO.scala +++ b/core/shared/src/main/scala/zio/ZIO.scala @@ -311,7 +311,7 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, /** * Maps the success value of this effect to a service. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") final def asService[A1 >: A: Tag: IsNotIntersection](implicit trace: ZTraceElement): ZIO[R, E, ZEnvironment[A1]] = map(ZEnvironment[A1](_)) @@ -1460,13 +1460,12 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, ) /** - * Provides a service builder to the ZIO effect, which translates it to - * another level. + * Provides a layer to the ZIO effect, which translates it to another level. */ final def provide[E1 >: E, R0, R1]( - serviceBuilder: => ZServiceBuilder[R0, E1, R1] + layer: => ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): ZIO[R0, E1, A] = - ZIO.suspendSucceed(serviceBuilder.build.map(_.upcast(ev)).use(r => self.provideEnvironment(r))) + ZIO.suspendSucceed(layer.build.map(_.upcast(ev)).use(r => self.provideEnvironment(r))) /** * Provides the part of the environment that is not part of the `ZEnv`, @@ -1475,19 +1474,19 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, * {{{ * val zio: ZIO[ZEnv with Logging, Nothing, Unit] = ??? * - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * - * val zio2 = zio.provideCustom(loggingServiceBuilder) + * val zio2 = zio.provideCustom(loggingLayer) * }}} */ final def provideCustom[E1 >: E, R1]( - serviceBuilder: => ZServiceBuilder[ZEnv, E1, R1] + layer: => ZLayer[ZEnv, E1, R1] )(implicit ev: ZEnv with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement ): ZIO[ZEnv, E1, A] = - provideSome[ZEnv](serviceBuilder) + provideSome[ZEnv](layer) /** * Provides the part of the environment that is not part of the `ZEnv`, @@ -1496,14 +1495,14 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, * {{{ * val zio: ZIO[ZEnv with Logging, Nothing, Unit] = ??? * - * val loggingLayer: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val zio2 = zio.provideCustomLayer(loggingLayer) * }}} */ @deprecated("use provideCustom", "2.0.0") final def provideCustomLayer[E1 >: E, R1]( - layer: => ZServiceBuilder[ZEnv, E1, R1] + layer: => ZLayer[ZEnv, E1, R1] )(implicit ev: ZEnv with R1 <:< R, tagged: Tag[R1], @@ -1511,28 +1510,6 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, ): ZIO[ZEnv, E1, A] = provideCustom(layer) - /** - * Provides the part of the environment that is not part of the `ZEnv`, - * leaving an effect that only depends on the `ZEnv`. - * - * {{{ - * val zio: ZIO[ZEnv with Logging, Nothing, Unit] = ??? - * - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? - * - * val zio2 = zio.provideCustomServices(loggingServiceBuilder) - * }}} - */ - @deprecated("use provideCustom", "2.0.0") - final def provideCustomServices[E1 >: E, R1]( - serviceBuilder: => ZServiceBuilder[ZEnv, E1, R1] - )(implicit - ev: ZEnv with R1 <:< R, - tagged: Tag[R1], - trace: ZTraceElement - ): ZIO[ZEnv, E1, A] = - provideCustom(serviceBuilder) - /** * Provides the `ZIO` effect with its required environment, which eliminates * its dependency on `R`. @@ -1545,30 +1522,20 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, */ @deprecated("use provide", "2.0.0") final def provideLayer[E1 >: E, R0, R1]( - layer: => ZServiceBuilder[R0, E1, R1] + layer: => ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): ZIO[R0, E1, A] = provide(layer) - /** - * Provides a service builder to the ZIO effect, which translates it to - * another level. - */ - @deprecated("use provide", "2.0.0") - final def provideServices[E1 >: E, R0, R1]( - serviceBuilder: => ZServiceBuilder[R0, E1, R1] - )(implicit ev: R1 <:< R, trace: ZTraceElement): ZIO[R0, E1, A] = - provide(serviceBuilder) - /** * Splits the environment into two parts, providing one part using the - * specified service builder and leaving the remainder `R0`. + * specified layer and leaving the remainder `R0`. * * {{{ * val zio: ZIO[Clock with Random, Nothing, Unit] = ??? * - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * - * val zio2 = zio.provideSome[Random](clockServiceBuilder) + * val zio2 = zio.provideSome[Random](clockLayer) * }}} */ final def provideSome[R0]: ZIO.ProvideSome[R0, R, E, A] = @@ -1590,7 +1557,7 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, * {{{ * val zio: ZIO[Clock with Random, Nothing, Unit] = ??? * - * val clockLayer: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val zio2 = zio.provideSomeLayer[Random](clockLayer) * }}} @@ -1599,22 +1566,6 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, final def provideSomeLayer[R0]: ZIO.ProvideSome[R0, R, E, A] = provideSome - /** - * Splits the environment into two parts, providing one part using the - * specified service builder and leaving the remainder `R0`. - * - * {{{ - * val zio: ZIO[Clock with Random, Nothing, Unit] = ??? - * - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? - * - * val zio2 = zio.provideSomeServices[Random](clockServiceBuilder) - * }}} - */ - @deprecated("use provideSome", "2.0.0") - final def provideSomeServices[R0]: ZIO.ProvideSome[R0, R, E, A] = - provideSome - /** * Returns a new effect that will utilize the default scope (fiber scope) to * supervise any fibers forked within the original effect. @@ -2433,35 +2384,35 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, intoPromise(p) /** - * Constructs a service builder from this effect. + * Constructs a layer from this effect. */ - final def toServiceBuilder[A1 >: A](implicit + final def toLayer[A1 >: A](implicit ev1: Tag[A1], ev2: IsNotIntersection[A1], trace: ZTraceElement - ): ZServiceBuilder[R, E, A1] = - ZServiceBuilder.fromZIO[R, E, A1](self) + ): ZLayer[R, E, A1] = + ZLayer.fromZIO[R, E, A1](self) /** - * Constructs a service builder from this effect, which must return one or - * more services. + * Constructs a layer from this effect, which must return one or more + * services. */ - final def toServiceBuilderEnvironment[B](implicit + final def toLayerEnvironment[B](implicit ev: A <:< ZEnvironment[B], trace: ZTraceElement - ): ZServiceBuilder[R, E, B] = - ZServiceBuilder.fromZIOMany(self.map(ev)) + ): ZLayer[R, E, B] = + ZLayer.fromZIOEnvironment(self.map(ev)) /** - * Constructs a service builder from this effect, which must return one or - * more services. + * Constructs a layer from this effect, which must return one or more + * services. */ - @deprecated("use toServiceBuilderEnvironment", "2.0.0") - final def toServiceBuilderMany[B](implicit + @deprecated("use toLayerEnvironment", "2.0.0") + final def toLayerMany[B](implicit ev: A <:< ZEnvironment[B], trace: ZTraceElement - ): ZServiceBuilder[R, E, B] = - toServiceBuilderEnvironment + ): ZLayer[R, E, B] = + toLayerEnvironment /** * Converts the effect into a [[scala.concurrent.Future]]. @@ -2475,25 +2426,6 @@ sealed trait ZIO[-R, +E, +A] extends Serializable with ZIOPlatformSpecific[R, E, final def toFutureWith(f: E => Throwable)(implicit trace: ZTraceElement): URIO[R, CancelableFuture[A]] = self.fork.flatMap(_.toFutureWith(f)) - /** - * Constructs a layer from this effect. - */ - @deprecated("use toServiceBuilder", "2.0.0") - final def toLayer[A1 >: A](implicit - ev1: Tag[A1], - ev2: IsNotIntersection[A1], - trace: ZTraceElement - ): ZServiceBuilder[R, E, A1] = - toServiceBuilder[A1] - - /** - * Constructs a layer from this effect, which must return one or more - * services. - */ - @deprecated("use toServiceBuilderMany", "2.0.0") - final def toLayerMany[B](implicit ev: A <:< ZEnvironment[B], trace: ZTraceElement): ZServiceBuilder[R, E, B] = - toServiceBuilderMany - /** * Converts this ZIO to [[zio.ZManaged]] with no release action. It will be * performed interruptibly. @@ -5019,10 +4951,10 @@ object ZIO extends ZIOCompanionPlatformSpecific { def provideEnvironment[R, E, A](r: => ZEnvironment[R])(implicit trace: ZTraceElement): ZIO[R, E, A] => IO[E, A] = _.provideEnvironment(r) - def provide[RIn, E, ROut, RIn2, ROut2](builder: ZServiceBuilder[RIn, E, ROut])( + def provide[RIn, E, ROut, RIn2, ROut2](builder: ZLayer[RIn, E, ROut])( zio: ZIO[ROut with RIn2, E, ROut2] )(implicit ev: Tag[RIn2], tag: Tag[ROut], trace: ZTraceElement): ZIO[RIn with RIn2, E, ROut2] = - zio.provideSomeServices[RIn with RIn2](ZServiceBuilder.environment[RIn2] ++ builder) + zio.provideSomeLayer[RIn with RIn2](ZLayer.environment[RIn2] ++ builder) /** * Races an `IO[E, A]` against zero or more other effects. Yields either the @@ -5731,9 +5663,9 @@ object ZIO extends ZIOCompanionPlatformSpecific { final class ProvideSome[R0, -R, +E, +A](private val self: ZIO[R, E, A]) extends AnyVal { def apply[E1 >: E, R1]( - serviceBuilder: => ZServiceBuilder[R0, E1, R1] + layer: => ZLayer[R0, E1, R1] )(implicit ev: R0 with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement): ZIO[R0, E1, A] = - self.provide[E1, R0, R0 with R1](ZServiceBuilder.environment[R0] ++ serviceBuilder) + self.provide[E1, R0, R0 with R1](ZLayer.environment[R0] ++ layer) } final class UpdateService[-R, +E, +A, M](private val self: ZIO[R, E, A]) extends AnyVal { diff --git a/core/shared/src/main/scala/zio/ZIOApp.scala b/core/shared/src/main/scala/zio/ZIOApp.scala index ecd079680db4..c0d61e30c7ef 100644 --- a/core/shared/src/main/scala/zio/ZIOApp.scala +++ b/core/shared/src/main/scala/zio/ZIOApp.scala @@ -21,9 +21,9 @@ import zio.stacktracer.TracingImplicits.disableAutoTrace import java.util.concurrent.atomic.AtomicBoolean /** - * An entry point for a ZIO application that allows sharing service builders - * between applications. For a simpler version that uses the default ZIO - * environment see `ZIOAppDefault`. + * An entry point for a ZIO application that allows sharing layers between + * applications. For a simpler version that uses the default ZIO environment see + * `ZIOAppDefault`. */ trait ZIOApp extends ZIOAppPlatformSpecific { self => private[zio] val shuttingDown = new AtomicBoolean(false) @@ -33,10 +33,10 @@ trait ZIOApp extends ZIOAppPlatformSpecific { self => type Environment /** - * A service builder that manages the acquisition and release of services - * necessary for the application to run. + * A layer that manages the acquisition and release of services necessary for + * the application to run. */ - def serviceBuilder: ZServiceBuilder[ZIOAppArgs, Any, Environment] + def layer: ZLayer[ZIOAppArgs, Any, Environment] /** * The main function of the application, which can access the command-line @@ -52,7 +52,7 @@ trait ZIOApp extends ZIOAppPlatformSpecific { self => * that executes the logic of both applications. */ final def <>(that: ZIOApp)(implicit trace: ZTraceElement): ZIOApp = - ZIOApp(self.run.zipPar(that.run), self.serviceBuilder +!+ that.serviceBuilder, self.hook >>> that.hook) + ZIOApp(self.run.zipPar(that.run), self.layer +!+ that.layer, self.hook >>> that.hook) /** * A helper function to obtain access to the command-line arguments of the @@ -87,11 +87,11 @@ trait ZIOApp extends ZIOAppPlatformSpecific { self => ZIO.runtime[ZEnv].flatMap { runtime => val newRuntime = runtime.mapRuntimeConfig(hook) - val newServiceBuilder = - ZServiceBuilder.environment[ZEnv] +!+ ZServiceBuilder.succeed(ZIOAppArgs(args)) >>> - serviceBuilder +!+ ZServiceBuilder.environment[ZEnv with ZIOAppArgs] + val newLayer = + ZLayer.environment[ZEnv] +!+ ZLayer.succeed(ZIOAppArgs(args)) >>> + layer +!+ ZLayer.environment[ZEnv with ZIOAppArgs] - newRuntime.run(run.provide(newServiceBuilder)) + newRuntime.run(run.provide(newLayer)) } def runtime: Runtime[ZEnv] = Runtime.default @@ -106,8 +106,8 @@ object ZIOApp { type Environment = app.Environment override final def hook: RuntimeConfigAspect = app.hook - final def serviceBuilder: ZServiceBuilder[ZIOAppArgs, Any, Environment] = - app.serviceBuilder + final def layer: ZLayer[ZIOAppArgs, Any, Environment] = + app.layer override final def run: ZIO[Environment with ZEnv with ZIOAppArgs, Any, Any] = app.run implicit final def tag: Tag[Environment] = @@ -120,14 +120,14 @@ object ZIOApp { */ def apply[R]( run0: ZIO[R with ZEnv with ZIOAppArgs, Any, Any], - serviceBuilder0: ZServiceBuilder[ZIOAppArgs, Any, R], + layer0: ZLayer[ZIOAppArgs, Any, R], hook0: RuntimeConfigAspect )(implicit tagged: Tag[R]): ZIOApp = new ZIOApp { type Environment = R def tag: Tag[Environment] = tagged override def hook = hook0 - def serviceBuilder = serviceBuilder0 + def layer = layer0 def run = run0 } @@ -136,5 +136,5 @@ object ZIOApp { * configuration. */ def fromZIO(run0: ZIO[ZEnv with ZIOAppArgs, Any, Any])(implicit trace: ZTraceElement): ZIOApp = - ZIOApp(run0, ZServiceBuilder.environment, RuntimeConfigAspect.identity) + ZIOApp(run0, ZLayer.environment, RuntimeConfigAspect.identity) } diff --git a/core/shared/src/main/scala/zio/ZIOAppDefault.scala b/core/shared/src/main/scala/zio/ZIOAppDefault.scala index 90e64b3bcf4d..f3d1db71a2e0 100644 --- a/core/shared/src/main/scala/zio/ZIOAppDefault.scala +++ b/core/shared/src/main/scala/zio/ZIOAppDefault.scala @@ -40,7 +40,7 @@ trait ZIOAppDefault extends ZIOApp { type Environment = ZEnv - val serviceBuilder: ZServiceBuilder[ZIOAppArgs, Any, ZEnv] = ZEnv.live + val layer: ZLayer[ZIOAppArgs, Any, ZEnv] = ZEnv.live val tag: Tag[ZEnv] = Tag[ZEnv] } diff --git a/core/shared/src/main/scala/zio/ZServiceBuilder.scala b/core/shared/src/main/scala/zio/ZLayer.scala similarity index 67% rename from core/shared/src/main/scala/zio/ZServiceBuilder.scala rename to core/shared/src/main/scala/zio/ZLayer.scala index 5fbc3fded49e..f51ae247c941 100644 --- a/core/shared/src/main/scala/zio/ZServiceBuilder.scala +++ b/core/shared/src/main/scala/zio/ZLayer.scala @@ -23,24 +23,23 @@ import zio.ZManaged.ReleaseMap import scala.collection.mutable.Builder /** - * A `ZServiceBuilder[E, A, B]` describes how to build one or more services in - * your application. Services can be injected into effects via ZIO#inject. - * Effects can require services via ZIO.service." + * A `ZLayer[E, A, B]` describes how to build one or more services in your + * application. Services can be injected into effects via ZIO#inject. Effects + * can require services via ZIO.service." * - * ServiceBuilder can be thought of as recipes for producing bundles of - * services, given their dependencies (other services). + * Layer can be thought of as recipes for producing bundles of services, given + * their dependencies (other services). * * Construction of services can be effectful and utilize resources that must be * acquired and safely released when the services are done being utilized. * - * By default service builders are shared, meaning that if the same - * servicebuilder is used twice the service builder will only be allocated a - * single time. + * By default layers are shared, meaning that if the same layer is used twice + * the layer will only be allocated a single time. * - * Because of their excellent composition properties, service builders are the - * idiomatic way in ZIO to create services that depend on other services. + * Because of their excellent composition properties, layers are the idiomatic + * way in ZIO to create services that depend on other services. */ -sealed abstract class ZServiceBuilder[-RIn, +E, +ROut] { self => +sealed abstract class ZLayer[-RIn, +E, +ROut] { self => /** * A symbolic alias for `orDie`. @@ -49,56 +48,56 @@ sealed abstract class ZServiceBuilder[-RIn, +E, +ROut] { self => ev1: E <:< Throwable, ev2: CanFail[E], trace: ZTraceElement - ): ZServiceBuilder[RIn, Nothing, ROut] = + ): ZLayer[RIn, Nothing, ROut] = self.orDie final def +!+[E1 >: E, RIn2, ROut1 >: ROut, ROut2]( - that: ZServiceBuilder[RIn2, E1, ROut2] - ): ZServiceBuilder[RIn with RIn2, E1, ROut1 with ROut2] = + that: ZLayer[RIn2, E1, ROut2] + ): ZLayer[RIn with RIn2, E1, ROut1 with ROut2] = self.zipWithPar(that)(_.unionAll[ROut2](_)) /** - * Combines this service builder with the specified service builder, producing - * a new service builder that has the inputs and outputs of = both. + * Combines this layer with the specified layer, producing a new layer that + * has the inputs and outputs of = both. */ final def ++[E1 >: E, RIn2, ROut1 >: ROut, ROut2]( - that: ZServiceBuilder[RIn2, E1, ROut2] - )(implicit tag: Tag[ROut2]): ZServiceBuilder[RIn with RIn2, E1, ROut1 with ROut2] = + that: ZLayer[RIn2, E1, ROut2] + )(implicit tag: Tag[ROut2]): ZLayer[RIn with RIn2, E1, ROut1 with ROut2] = self.zipWithPar(that)(_.union[ROut2](_)) /** * A symbolic alias for `orElse`. */ def <>[RIn1 <: RIn, E1, ROut1 >: ROut]( - that: ZServiceBuilder[RIn1, E1, ROut1] - )(implicit ev: CanFail[E], trace: ZTraceElement): ZServiceBuilder[RIn1, E1, ROut1] = + that: ZLayer[RIn1, E1, ROut1] + )(implicit ev: CanFail[E], trace: ZTraceElement): ZLayer[RIn1, E1, ROut1] = self.orElse(that) /** * A named alias for `++`. */ final def and[E1 >: E, RIn2, ROut1 >: ROut, ROut2]( - that: ZServiceBuilder[RIn2, E1, ROut2] - )(implicit tag: Tag[ROut2]): ZServiceBuilder[RIn with RIn2, E1, ROut1 with ROut2] = + that: ZLayer[RIn2, E1, ROut2] + )(implicit tag: Tag[ROut2]): ZLayer[RIn with RIn2, E1, ROut1 with ROut2] = self.++[E1, RIn2, ROut1, ROut2](that) /** * A named alias for `>+>`. */ final def andTo[E1 >: E, RIn2 >: ROut, ROut1 >: ROut, ROut2]( - that: ZServiceBuilder[RIn2, E1, ROut2] + that: ZLayer[RIn2, E1, ROut2] )(implicit tagged: Tag[ROut2], trace: ZTraceElement - ): ZServiceBuilder[RIn, E1, ROut1 with ROut2] = + ): ZLayer[RIn, E1, ROut1 with ROut2] = self.>+>[E1, RIn2, ROut1, ROut2](that) /** - * Builds a service builder into a managed value. + * Builds a layer into a managed value. */ final def build(implicit trace: ZTraceElement): ZManaged[RIn, E, ZEnvironment[ROut]] = for { - memoMap <- ZServiceBuilder.MemoMap.make.toManaged + memoMap <- ZLayer.MemoMap.make.toManaged run <- self.scope value <- run(memoMap) } yield value @@ -107,127 +106,120 @@ sealed abstract class ZServiceBuilder[-RIn, +E, +ROut] { self => * Recovers from all errors. */ final def catchAll[RIn1 <: RIn, E1, ROut1 >: ROut]( - handler: E => ZServiceBuilder[RIn1, E1, ROut1] - )(implicit trace: ZTraceElement): ZServiceBuilder[RIn1, E1, ROut1] = + handler: E => ZLayer[RIn1, E1, ROut1] + )(implicit trace: ZTraceElement): ZLayer[RIn1, E1, ROut1] = foldServices(handler, ZLayer.succeedMany(_)) /** - * Constructs a service builder dynamically based on the output of this - * service builder. + * Constructs a layer dynamically based on the output of this layer. */ final def flatMap[RIn1 <: RIn, E1 >: E, ROut2]( - f: ZEnvironment[ROut] => ZServiceBuilder[RIn1, E1, ROut2] - )(implicit trace: ZTraceElement): ZServiceBuilder[RIn1, E1, ROut2] = + f: ZEnvironment[ROut] => ZLayer[RIn1, E1, ROut2] + )(implicit trace: ZTraceElement): ZLayer[RIn1, E1, ROut2] = foldServices(ZLayer.fail, f) final def flatten[RIn1 <: RIn, E1 >: E, ROut1 >: ROut, ROut2](implicit tag: Tag[ROut1], - ev1: ROut1 <:< ZServiceBuilder[RIn1, E1, ROut2], + ev1: ROut1 <:< ZLayer[RIn1, E1, ROut2], ev2: IsNotIntersection[ROut1], trace: ZTraceElement - ): ZServiceBuilder[RIn1, E1, ROut2] = + ): ZLayer[RIn1, E1, ROut2] = flatMap(environment => ev1(environment.get[ROut1])) /** - * Feeds the error or output services of this service builder into the input - * of either the specified `failure` or `success` service builders, resulting - * in a new service builder with the inputs of this service builder, and the - * error or outputs of the specified service builder. + * Feeds the error or output services of this layer into the input of either + * the specified `failure` or `success` layers, resulting in a new layer with + * the inputs of this layer, and the error or outputs of the specified layer. */ final def foldServices[E1, RIn1 <: RIn, ROut2]( - failure: E => ZServiceBuilder[RIn1, E1, ROut2], - success: ZEnvironment[ROut] => ZServiceBuilder[RIn1, E1, ROut2] - )(implicit ev: CanFail[E], trace: ZTraceElement): ZServiceBuilder[RIn1, E1, ROut2] = + failure: E => ZLayer[RIn1, E1, ROut2], + success: ZEnvironment[ROut] => ZLayer[RIn1, E1, ROut2] + )(implicit ev: CanFail[E], trace: ZTraceElement): ZLayer[RIn1, E1, ROut2] = foldCauseServices(_.failureOrCause.fold(failure, ZLayer.failCause), success) /** - * Feeds the error or output services of this service builder into the input - * of either the specified `failure` or `success` service builders, resulting - * in a new service builder with the inputs of this service builder, and the - * error or outputs of the specified service builder. + * Feeds the error or output services of this layer into the input of either + * the specified `failure` or `success` layers, resulting in a new layer with + * the inputs of this layer, and the error or outputs of the specified layer. */ final def foldCauseServices[E1, RIn1 <: RIn, ROut2]( - failure: Cause[E] => ZServiceBuilder[RIn1, E1, ROut2], - success: ZEnvironment[ROut] => ZServiceBuilder[RIn1, E1, ROut2] - )(implicit ev: CanFail[E]): ZServiceBuilder[RIn1, E1, ROut2] = + failure: Cause[E] => ZLayer[RIn1, E1, ROut2], + success: ZEnvironment[ROut] => ZLayer[RIn1, E1, ROut2] + )(implicit ev: CanFail[E]): ZLayer[RIn1, E1, ROut2] = ZLayer.Fold(self, failure, success) /** - * Creates a fresh version of this service builder that will not be shared. + * Creates a fresh version of this layer that will not be shared. */ - final def fresh: ZServiceBuilder[RIn, E, ROut] = - ZServiceBuilder.Fresh(self) + final def fresh: ZLayer[RIn, E, ROut] = + ZLayer.Fresh(self) /** - * Returns the hash code of this service builder. + * Returns the hash code of this layer. */ override final lazy val hashCode: Int = super.hashCode /** - * Builds this service builder and uses it until it is interrupted. This is - * useful when your entire application is a service builder, such as an HTTP - * server. + * Builds this layer and uses it until it is interrupted. This is useful when + * your entire application is a layer, such as an HTTP server. */ final def launch(implicit trace: ZTraceElement): ZIO[RIn, E, Nothing] = build.useForever /** - * Returns a new service builder whose output is mapped by the specified - * function. + * Returns a new layer whose output is mapped by the specified function. */ final def map[ROut1](f: ZEnvironment[ROut] => ZEnvironment[ROut1])(implicit trace: ZTraceElement - ): ZServiceBuilder[RIn, E, ROut1] = - flatMap(environment => ZServiceBuilder.succeedMany(f(environment))) + ): ZLayer[RIn, E, ROut1] = + flatMap(environment => ZLayer.succeedMany(f(environment))) /** - * Returns a service builder with its error channel mapped using the specified - * function. + * Returns a layer with its error channel mapped using the specified function. */ - final def mapError[E1](f: E => E1)(implicit ev: CanFail[E], trace: ZTraceElement): ZServiceBuilder[RIn, E1, ROut] = + final def mapError[E1](f: E => E1)(implicit ev: CanFail[E], trace: ZTraceElement): ZLayer[RIn, E1, ROut] = catchAll(e => ZLayer.fail(f(e))) /** * Returns a managed effect that, if evaluated, will return the lazily - * computed result of this service builder. + * computed result of this layer. */ - final def memoize(implicit trace: ZTraceElement): ZManaged[Any, Nothing, ZServiceBuilder[RIn, E, ROut]] = - build.memoize.map(ZServiceBuilder.fromManagedEnvironment) + final def memoize(implicit trace: ZTraceElement): ZManaged[Any, Nothing, ZLayer[RIn, E, ROut]] = + build.memoize.map(ZLayer.fromManagedEnvironment) /** * Translates effect failure into death of the fiber, making all failures - * unchecked and not a part of the type of the service builder. + * unchecked and not a part of the type of the layer. */ final def orDie(implicit ev1: E IsSubtypeOfError Throwable, ev2: CanFail[E], trace: ZTraceElement - ): ZServiceBuilder[RIn, Nothing, ROut] = - catchAll(e => ZServiceBuilder.die(ev1(e))) + ): ZLayer[RIn, Nothing, ROut] = + catchAll(e => ZLayer.die(ev1(e))) /** - * Executes this service builder and returns its output, if it succeeds, but - * otherwise executes the specified service builder. + * Executes this layer and returns its output, if it succeeds, but otherwise + * executes the specified layer. */ final def orElse[RIn1 <: RIn, E1, ROut1 >: ROut]( - that: ZServiceBuilder[RIn1, E1, ROut1] - )(implicit ev: CanFail[E], trace: ZTraceElement): ZServiceBuilder[RIn1, E1, ROut1] = + that: ZLayer[RIn1, E1, ROut1] + )(implicit ev: CanFail[E], trace: ZTraceElement): ZLayer[RIn1, E1, ROut1] = catchAll(_ => that) /** - * Retries constructing this service builder according to the specified - * schedule. + * Retries constructing this layer according to the specified schedule. */ final def retry[RIn1 <: RIn with Clock]( schedule: Schedule[RIn1, E, Any] - )(implicit trace: ZTraceElement): ZServiceBuilder[RIn1, E, ROut] = { + )(implicit trace: ZTraceElement): ZLayer[RIn1, E, ROut] = { import Schedule.Decision._ case class State(state: schedule.State) - def update(e: E, s: schedule.State): ZServiceBuilder[RIn1, E, State] = - ZServiceBuilder.fromZIO { + def update(e: E, s: schedule.State): ZLayer[RIn1, E, State] = + ZLayer.fromZIO { Clock.currentDateTime.flatMap { now => schedule.step(now, e, s).flatMap { case (_, _, Done) => ZIO.fail(e) @@ -237,39 +229,39 @@ sealed abstract class ZServiceBuilder[-RIn, +E, +ROut] { self => } } - def loop(s: schedule.State): ZServiceBuilder[RIn1, E, ROut] = + def loop(s: schedule.State): ZLayer[RIn1, E, ROut] = self.catchAll(update(_, s).flatMap(environment => loop(environment.get.state).fresh)) - ZServiceBuilder.succeed(State(schedule.initial)).flatMap(environment => loop(environment.get.state)) + ZLayer.succeed(State(schedule.initial)).flatMap(environment => loop(environment.get.state)) } /** - * Performs the specified effect if this service builder succeeds. + * Performs the specified effect if this layer succeeds. */ final def tap[RIn1 <: RIn, E1 >: E](f: ZEnvironment[ROut] => ZIO[RIn1, E1, Any])(implicit trace: ZTraceElement - ): ZServiceBuilder[RIn1, E1, ROut] = - flatMap(environment => ZServiceBuilder.fromZIOEnvironment(f(environment).as(environment))) + ): ZLayer[RIn1, E1, ROut] = + flatMap(environment => ZLayer.fromZIOEnvironment(f(environment).as(environment))) /** - * Performs the specified effect if this service builder fails. + * Performs the specified effect if this layer fails. */ final def tapError[RIn1 <: RIn, E1 >: E](f: E => ZIO[RIn1, E1, Any])(implicit trace: ZTraceElement - ): ZServiceBuilder[RIn1, E1, ROut] = + ): ZLayer[RIn1, E1, ROut] = catchAll(e => ZLayer.fromZIO[RIn1, E1, Nothing](f(e) *> ZIO.fail(e))) /** * A named alias for `>>>`. */ - final def to[E1 >: E, ROut2](that: ZServiceBuilder[ROut, E1, ROut2])(implicit + final def to[E1 >: E, ROut2](that: ZLayer[ROut, E1, ROut2])(implicit trace: ZTraceElement - ): ZServiceBuilder[RIn, E1, ROut2] = + ): ZLayer[RIn, E1, ROut2] = self >>> that /** - * Converts a service builder that requires no services into a managed - * runtime, which can be used to execute effects. + * Converts a layer that requires no services into a managed runtime, which + * can be used to execute effects. */ final def toRuntime( runtimeConfig: RuntimeConfig @@ -277,38 +269,37 @@ sealed abstract class ZServiceBuilder[-RIn, +E, +ROut] { self => build.provideEnvironment(ZEnvironment.empty.upcast).map(Runtime(_, runtimeConfig)) /** - * Updates one of the services output by this service builder. + * Updates one of the services output by this layer. */ final def update[A >: ROut: Tag: IsNotIntersection]( f: A => A - )(implicit trace: ZTraceElement): ZServiceBuilder[RIn, E, ROut] = + )(implicit trace: ZTraceElement): ZLayer[RIn, E, ROut] = map(_.update[A](f)) /** - * Combines this service builder the specified service builder, producing a - * new service builder that has the inputs of both, and the outputs of both - * combined using the specified function. + * Combines this layer the specified layer, producing a new layer that has the + * inputs of both, and the outputs of both combined using the specified + * function. */ final def zipWithPar[E1 >: E, RIn2, ROut1 >: ROut, ROut2, ROut3]( - that: ZServiceBuilder[RIn2, E1, ROut2] - )(f: (ZEnvironment[ROut], ZEnvironment[ROut2]) => ZEnvironment[ROut3]): ZServiceBuilder[RIn with RIn2, E1, ROut3] = - ZServiceBuilder.ZipWithPar(self, that, f) + that: ZLayer[RIn2, E1, ROut2] + )(f: (ZEnvironment[ROut], ZEnvironment[ROut2]) => ZEnvironment[ROut3]): ZLayer[RIn with RIn2, E1, ROut3] = + ZLayer.ZipWithPar(self, that, f) /** - * Returns whether this service builder is a fresh version that will not be - * shared. + * Returns whether this layer is a fresh version that will not be shared. */ private final def isFresh: Boolean = self match { - case ZServiceBuilder.Fresh(_) => true - case _ => false + case ZLayer.Fresh(_) => true + case _ => false } private final def scope(implicit trace: ZTraceElement - ): Managed[Nothing, ZServiceBuilder.MemoMap => ZManaged[RIn, E, ZEnvironment[ROut]]] = + ): Managed[Nothing, ZLayer.MemoMap => ZManaged[RIn, E, ZEnvironment[ROut]]] = self match { - case ZServiceBuilder.Fold(self, failure, success) => + case ZLayer.Fold(self, failure, success) => ZManaged.succeed { memoMap => memoMap .getOrElseMemoize(self) @@ -317,68 +308,66 @@ sealed abstract class ZServiceBuilder[-RIn, +E, +ROut] { self => r => memoMap.getOrElseMemoize(success(r)) ) } - case ZServiceBuilder.Fresh(self) => + case ZLayer.Fresh(self) => Managed.succeed(_ => self.build) - case ZServiceBuilder.Managed(self) => + case ZLayer.Managed(self) => Managed.succeed(_ => self) - case ZServiceBuilder.Suspend(self) => + case ZLayer.Suspend(self) => ZManaged.succeed(memoMap => memoMap.getOrElseMemoize(self())) - case ZServiceBuilder.To(self, that) => + case ZLayer.To(self, that) => ZManaged.succeed(memoMap => memoMap .getOrElseMemoize(self) .flatMap(r => memoMap.getOrElseMemoize(that).provideEnvironment(r)(NeedsEnv.needsEnv, trace)) ) - case ZServiceBuilder.ZipWith(self, that, f) => + case ZLayer.ZipWith(self, that, f) => ZManaged.succeed(memoMap => memoMap.getOrElseMemoize(self).zipWith(memoMap.getOrElseMemoize(that))(f)) - case ZServiceBuilder.ZipWithPar(self, that, f) => + case ZLayer.ZipWithPar(self, that, f) => ZManaged.succeed(memoMap => memoMap.getOrElseMemoize(self).zipWithPar(memoMap.getOrElseMemoize(that))(f)) } } -object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { +object ZLayer extends ZLayerCompanionVersionSpecific { private final case class Fold[RIn, E, E2, ROut, ROut2]( - self: ZServiceBuilder[RIn, E, ROut], - failure: Cause[E] => ZServiceBuilder[RIn, E2, ROut2], - success: ZEnvironment[ROut] => ZServiceBuilder[RIn, E2, ROut2] - ) extends ZServiceBuilder[RIn, E2, ROut2] - private final case class Fresh[RIn, E, ROut](self: ZServiceBuilder[RIn, E, ROut]) - extends ZServiceBuilder[RIn, E, ROut] + self: ZLayer[RIn, E, ROut], + failure: Cause[E] => ZLayer[RIn, E2, ROut2], + success: ZEnvironment[ROut] => ZLayer[RIn, E2, ROut2] + ) extends ZLayer[RIn, E2, ROut2] + private final case class Fresh[RIn, E, ROut](self: ZLayer[RIn, E, ROut]) extends ZLayer[RIn, E, ROut] private final case class Managed[-RIn, +E, +ROut](self: ZManaged[RIn, E, ZEnvironment[ROut]]) - extends ZServiceBuilder[RIn, E, ROut] - private final case class Suspend[-RIn, +E, +ROut](self: () => ZServiceBuilder[RIn, E, ROut]) - extends ZServiceBuilder[RIn, E, ROut] + extends ZLayer[RIn, E, ROut] + private final case class Suspend[-RIn, +E, +ROut](self: () => ZLayer[RIn, E, ROut]) extends ZLayer[RIn, E, ROut] private final case class To[RIn, E, ROut, ROut1]( - self: ZServiceBuilder[RIn, E, ROut], - that: ZServiceBuilder[ROut, E, ROut1] - ) extends ZServiceBuilder[RIn, E, ROut1] + self: ZLayer[RIn, E, ROut], + that: ZLayer[ROut, E, ROut1] + ) extends ZLayer[RIn, E, ROut1] private final case class ZipWith[-RIn, +E, ROut, ROut2, ROut3]( - self: ZServiceBuilder[RIn, E, ROut], - that: ZServiceBuilder[RIn, E, ROut2], + self: ZLayer[RIn, E, ROut], + that: ZLayer[RIn, E, ROut2], f: (ZEnvironment[ROut], ZEnvironment[ROut2]) => ZEnvironment[ROut3] - ) extends ZServiceBuilder[RIn, E, ROut3] + ) extends ZLayer[RIn, E, ROut3] private final case class ZipWithPar[-RIn, +E, ROut, ROut2, ROut3]( - self: ZServiceBuilder[RIn, E, ROut], - that: ZServiceBuilder[RIn, E, ROut2], + self: ZLayer[RIn, E, ROut], + that: ZLayer[RIn, E, ROut2], f: (ZEnvironment[ROut], ZEnvironment[ROut2]) => ZEnvironment[ROut3] - ) extends ZServiceBuilder[RIn, E, ROut3] + ) extends ZLayer[RIn, E, ROut3] /** - * Constructs a service builderfrom a managed resource. + * Constructs a layerfrom a managed resource. */ def apply[RIn, E, ROut: Tag: IsNotIntersection](managed: ZManaged[RIn, E, ROut])(implicit trace: ZTraceElement - ): ZServiceBuilder[RIn, E, ROut] = - ZServiceBuilder.fromManaged(managed) + ): ZLayer[RIn, E, ROut] = + ZLayer.fromManaged(managed) /** - * Constructs a service builder from an effectual resource. + * Constructs a layer from an effectual resource. */ def apply[RIn, E, ROut: Tag: IsNotIntersection](zio: ZIO[RIn, E, ROut])(implicit trace: ZTraceElement - ): ZServiceBuilder[RIn, E, ROut] = - ZServiceBuilder.fromZIO(zio) + ): ZLayer[RIn, E, ROut] = + ZLayer.fromZIO(zio) sealed trait Debug @@ -389,23 +378,22 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { private[zio] case object Mermaid extends Debug /** - * Including this service builder in a call to a compile-time - * ZServiceBuilder constructor, such as [[ZIO.inject]] or - * [[ZServiceBuilder.wire]], will display a tree visualization of the - * constructed service builder graph. + * Including this layer in a call to a compile-time ZLayer constructor, such + * as [[ZIO.inject]] or [[ZLayer.wire]], will display a tree visualization + * of the constructed layer graph. * * {{{ - * val serviceBuilder = - * ZServiceBuilder.wire[OldLady]( + * val layer = + * ZLayer.wire[OldLady]( * OldLady.live, * Spider.live, * Fly.live, * Bear.live, * Console.live, - * ZServiceBuilder.Debug.tree + * ZLayer.Debug.tree * ) * - * // Including `ZServiceBuilder.Debug.tree` will generate the following compilation error: + * // Including `ZLayer.Debug.tree` will generate the following compilation error: * // * // ◉ OldLady.live * // ├─◑ Spider.live @@ -417,27 +405,26 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { * * }}} */ - val tree: UServiceBuilder[Debug] = - ZServiceBuilder.succeed[Debug](Debug.Tree)(Tag[Debug], IsNotIntersection[Debug], Tracer.newTrace) + val tree: ULayer[Debug] = + ZLayer.succeed[Debug](Debug.Tree)(Tag[Debug], IsNotIntersection[Debug], Tracer.newTrace) /** - * Including this service builder in a call to a compile-time - * ZServiceBuilder constructor, such as [[ZIO.inject]] or - * [[ZServiceBuilder.wire]], will display a tree visualization of the - * constructed service builder graph as well as a link to Mermaid chart. + * Including this layer in a call to a compile-time ZLayer constructor, such + * as [[ZIO.inject]] or [[ZLayer.wire]], will display a tree visualization + * of the constructed layer graph as well as a link to Mermaid chart. * * {{{ - * val serviceBuilder = - * ZServiceBuilder.wire[OldLady]( + * val layer = + * ZLayer.wire[OldLady]( * OldLady.live, * Spider.live, * Fly.live, * Bear.live, * Console.live, - * ZServiceBuilder.Debug.mermaid + * ZLayer.Debug.mermaid * ) * - * // Including `ZServiceBuilder.Debug.mermaid` will generate the following compilation error: + * // Including `ZLayer.Debug.mermaid` will generate the following compilation error: * // * // ◉ OldLady.live * // ├─◑ Spider.live @@ -452,42 +439,41 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { * * }}} */ - val mermaid: UServiceBuilder[Debug] = - ZServiceBuilder.succeed[Debug](Debug.Mermaid)(Tag[Debug], IsNotIntersection[Debug], Tracer.newTrace) + val mermaid: ULayer[Debug] = + ZLayer.succeed[Debug](Debug.Mermaid)(Tag[Debug], IsNotIntersection[Debug], Tracer.newTrace) } /** - * Gathers up the ZServiceBuilder inside of the given collection, and combines - * them into a single ZServiceBuilder containing an equivalent collection of - * results. + * Gathers up the ZLayer inside of the given collection, and combines them + * into a single ZLayer containing an equivalent collection of results. */ def collectAll[R, E, A: Tag: IsNotIntersection, Collection[+Element] <: Iterable[Element]]( - in: Collection[ZServiceBuilder[R, E, A]] + in: Collection[ZLayer[R, E, A]] )(implicit ev: IsNotIntersection[Collection[A]], tag: Tag[Collection[A]], - bf: BuildFrom[Collection[ZServiceBuilder[R, E, A]], A, Collection[A]], + bf: BuildFrom[Collection[ZLayer[R, E, A]], A, Collection[A]], trace: ZTraceElement - ): ZServiceBuilder[R, E, Collection[A]] = + ): ZLayer[R, E, Collection[A]] = foreach(in)(i => i) /** - * Constructs a service builder that dies with the specified throwable. + * Constructs a layer that dies with the specified throwable. */ - final def die(t: Throwable)(implicit trace: ZTraceElement): ZServiceBuilder[Any, Nothing, Nothing] = - ZServiceBuilder.failCause(Cause.die(t)) + final def die(t: Throwable)(implicit trace: ZTraceElement): ZLayer[Any, Nothing, Nothing] = + ZLayer.failCause(Cause.die(t)) /** - * Constructs a service builder that fails with the specified error. + * Constructs a layer that fails with the specified error. */ - def fail[E](e: E)(implicit trace: ZTraceElement): ServiceBuilder[E, Nothing] = + def fail[E](e: E)(implicit trace: ZTraceElement): Layer[E, Nothing] = failCause(Cause.fail(e)) /** - * Constructs a service builder that fails with the specified cause. + * Constructs a layer that fails with the specified cause. */ - def failCause[E](cause: Cause[E])(implicit trace: ZTraceElement): ServiceBuilder[E, Nothing] = - ZServiceBuilder(ZManaged.failCause(cause)) + def failCause[E](cause: Cause[E])(implicit trace: ZTraceElement): Layer[E, Nothing] = + ZLayer(ZManaged.failCause(cause)) /** * Applies the function `f` to each element of the `Collection[A]` and returns @@ -495,196 +481,195 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { */ def foreach[R, E, A, B: Tag: IsNotIntersection, Collection[+Element] <: Iterable[Element]]( in: Collection[A] - )(f: A => ZServiceBuilder[R, E, B])(implicit + )(f: A => ZLayer[R, E, B])(implicit ev: IsNotIntersection[Collection[B]], tag: Tag[Collection[B]], bf: BuildFrom[Collection[A], B, Collection[B]], trace: ZTraceElement - ): ZServiceBuilder[R, E, Collection[B]] = - in.foldLeft[ZServiceBuilder[R, E, Builder[B, Collection[B]]]](ZServiceBuilder.succeed(bf.newBuilder(in)))((io, a) => + ): ZLayer[R, E, Collection[B]] = + in.foldLeft[ZLayer[R, E, Builder[B, Collection[B]]]](ZLayer.succeed(bf.newBuilder(in)))((io, a) => io.zipWithPar(f(a))((left, right) => ZEnvironment(left.get += right.get)) ).map(environment => ZEnvironment(environment.get.result())) /** - * Constructs a service builder from acquire and release actions. The acquire - * and release actions will be performed uninterruptibly. + * Constructs a layer from acquire and release actions. The acquire and + * release actions will be performed uninterruptibly. */ def fromAcquireRelease[R, E, A: Tag: IsNotIntersection](acquire: ZIO[R, E, A])(release: A => URIO[R, Any])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = + ): ZLayer[R, E, A] = fromManaged(ZManaged.acquireReleaseWith(acquire)(release)) /** - * Constructs a service builder from acquire and release actions, which must - * return one or more services. The acquire and release actions will be - * performed uninterruptibly. + * Constructs a layer from acquire and release actions, which must return one + * or more services. The acquire and release actions will be performed + * uninterruptibly. */ def fromAcquireReleaseEnvironment[R, E, A]( acquire: ZIO[R, E, ZEnvironment[A]] )(release: ZEnvironment[A] => URIO[R, Any])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = + ): ZLayer[R, E, A] = fromManagedMany(ZManaged.acquireReleaseWith(acquire)(release)) /** - * Constructs a service builder from acquire and release actions, which must - * return one or more services. The acquire and release actions will be - * performed uninterruptibly. + * Constructs a layer from acquire and release actions, which must return one + * or more services. The acquire and release actions will be performed + * uninterruptibly. */ @deprecated("use fromAcquireReleaseEnvironment", "2.0.0") def fromAcquireReleaseMany[R, E, A](acquire: ZIO[R, E, ZEnvironment[A]])(release: ZEnvironment[A] => URIO[R, Any])( implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = + ): ZLayer[R, E, A] = fromAcquireReleaseEnvironment(acquire)(release) /** - * Constructs a service builder from the specified effect. + * Constructs a layer from the specified effect. */ @deprecated("use fromZIO", "2.0.0") def fromEffect[R, E, A: Tag: IsNotIntersection](zio: ZIO[R, E, A])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = + ): ZLayer[R, E, A] = fromZIO(zio) /** - * Constructs a service builder from the specified effect, which must return - * one or more services. + * Constructs a layer from the specified effect, which must return one or more + * services. */ @deprecated("use fromZIOMany", "2.0.0") def fromEffectMany[R, E, A](zio: ZIO[R, E, ZEnvironment[A]])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = + ): ZLayer[R, E, A] = fromZIOMany(zio) /** - * Constructs a service builder from the environment using the specified - * function. + * Constructs a layer from the environment using the specified function. */ def fromFunction[A, B: Tag: IsNotIntersection](f: ZEnvironment[A] => B)(implicit trace: ZTraceElement - ): ZServiceBuilder[A, Nothing, B] = + ): ZLayer[A, Nothing, B] = fromFunctionZIO(a => ZIO.succeedNow(f(a))) /** - * Constructs a service builder from the environment using the specified - * function, which must return one or more services. + * Constructs a layer from the environment using the specified function, which + * must return one or more services. */ def fromFunctionEnvironment[A, B](f: ZEnvironment[A] => ZEnvironment[B])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, Nothing, B] = + ): ZLayer[A, Nothing, B] = fromFunctionEnvironmentZIO(a => ZIO.succeedNow(f(a))) /** - * Constructs a service builder from the environment using the specified - * effectful resourceful function, which must return one or more services. + * Constructs a layer from the environment using the specified effectful + * resourceful function, which must return one or more services. */ def fromFunctionEnvironmentManaged[A, E, B](f: ZEnvironment[A] => ZManaged[Any, E, ZEnvironment[B]])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, E, B] = - ZServiceBuilder.fromManagedEnvironment(ZManaged.environmentWithManaged(f)) + ): ZLayer[A, E, B] = + ZLayer.fromManagedEnvironment(ZManaged.environmentWithManaged(f)) /** - * Constructs a service builder from the environment using the specified - * effectful function, which must return one or more services. + * Constructs a layer from the environment using the specified effectful + * function, which must return one or more services. */ def fromFunctionEnvironmentZIO[A, E, B](f: ZEnvironment[A] => IO[E, ZEnvironment[B]])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, E, B] = + ): ZLayer[A, E, B] = fromFunctionEnvironmentManaged(a => f(a).toManaged) /** - * Constructs a service builder from the environment using the specified - * effectful function. + * Constructs a layer from the environment using the specified effectful + * function. */ @deprecated("use fromFunctionZIO", "2.0.0") def fromFunctionM[A, E, B: Tag: IsNotIntersection](f: ZEnvironment[A] => IO[E, B])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, E, B] = + ): ZLayer[A, E, B] = fromFunctionZIO(f) /** - * Constructs a service builder from the environment using the specified - * effectful resourceful function. + * Constructs a layer from the environment using the specified effectful + * resourceful function. */ def fromFunctionManaged[A, E, B: Tag: IsNotIntersection](f: ZEnvironment[A] => ZManaged[Any, E, B])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, E, B] = + ): ZLayer[A, E, B] = fromManaged(ZManaged.accessManaged(f)) /** - * Constructs a service builder from the environment using the specified - * function, which must return one or more services. + * Constructs a layer from the environment using the specified function, which + * must return one or more services. */ @deprecated("use fromFunctionEnvironment", "2.0.0") def fromFunctionMany[A, B](f: ZEnvironment[A] => ZEnvironment[B])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, Nothing, B] = + ): ZLayer[A, Nothing, B] = fromFunctionEnvironment(f) /** - * Constructs a service builder from the environment using the specified - * effectful function, which must return one or more services. + * Constructs a layer from the environment using the specified effectful + * function, which must return one or more services. */ @deprecated("use fromFunctionManyZIO", "2.0.0") def fromFunctionManyM[A, E, B](f: ZEnvironment[A] => IO[E, ZEnvironment[B]])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, E, B] = + ): ZLayer[A, E, B] = fromFunctionManyZIO(f) /** - * Constructs a service builder from the environment using the specified - * effectful resourceful function, which must return one or more services. + * Constructs a layer from the environment using the specified effectful + * resourceful function, which must return one or more services. */ @deprecated("use fromFunctionEnvironmentManaged", "2.0.0") def fromFunctionManyManaged[A, E, B](f: ZEnvironment[A] => ZManaged[Any, E, ZEnvironment[B]])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, E, B] = + ): ZLayer[A, E, B] = fromFunctionEnvironmentManaged(f) /** - * Constructs a service builder from the environment using the specified - * effectful function, which must return one or more services. + * Constructs a layer from the environment using the specified effectful + * function, which must return one or more services. */ @deprecated("use fromFunctionEnvironmentZIO", "2.0.0") def fromFunctionManyZIO[A, E, B](f: ZEnvironment[A] => IO[E, ZEnvironment[B]])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, E, B] = + ): ZLayer[A, E, B] = fromFunctionEnvironmentZIO(f) /** - * Constructs a service builder from the environment using the specified - * effectful function. + * Constructs a layer from the environment using the specified effectful + * function. */ def fromFunctionZIO[A, E, B: Tag: IsNotIntersection](f: ZEnvironment[A] => IO[E, B])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, E, B] = + ): ZLayer[A, E, B] = fromFunctionManaged(a => f(a).toManaged) /** - * Constructs a service builder that purely depends on the specified service. + * Constructs a layer that purely depends on the specified service. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromService[A: Tag: IsNotIntersection, B: Tag: IsNotIntersection](f: A => B)(implicit trace: ZTraceElement - ): ZServiceBuilder[A, Nothing, B] = + ): ZLayer[A, Nothing, B] = fromServiceM[A, Any, Nothing, B](a => ZIO.succeedNow(f(a))) /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, B: Tag: IsNotIntersection]( f: (A0, A1) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[A0 with A1, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[A0 with A1, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -692,15 +677,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[A0 with A1 with A2, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[A0 with A1 with A2, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -709,15 +694,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[A0 with A1 with A2 with A3, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[A0 with A1 with A2 with A3, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -729,15 +714,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4) => B )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -750,15 +735,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5) => B )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4 with A5, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -770,15 +755,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5 with A6, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[A0 with A1 with A2 with A3 with A4 with A5 with A6, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -793,15 +778,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7) => B )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -817,15 +802,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8) => B )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -842,15 +827,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9) => B )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, Nothing, B] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, Nothing, B] = { + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -866,19 +851,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -895,19 +880,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -925,19 +910,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -956,19 +941,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -988,19 +973,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1021,19 +1006,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1055,19 +1040,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1090,19 +1075,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1126,19 +1111,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1163,19 +1148,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1201,19 +1186,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that purely depends on the specified services. + * Constructs a layer that purely depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServices[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1240,42 +1225,39 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21) => B - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20 with A21, Nothing, B ] = { - val serviceBuilder = fromServicesM(andThen(f)(ZIO.succeedNow(_))) - serviceBuilder + val layer = fromServicesM(andThen(f)(ZIO.succeedNow(_))) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * service. + * Constructs a layer that effectfully depends on the specified service. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServiceM[A: Tag: IsNotIntersection, R, E, B: Tag: IsNotIntersection](f: A => ZIO[R, E, B])(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A, E, B] = + ): ZLayer[R with A, E, B] = fromServiceManaged[A, R, E, B](a => f(a).toManaged) /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, R, E, B: Tag: IsNotIntersection]( f: (A0, A1) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1285,16 +1267,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1307,16 +1288,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3) => ZIO[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1330,16 +1310,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4) => ZIO[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1354,16 +1333,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5) => ZIO[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1377,16 +1355,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1403,16 +1380,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7) => ZIO[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1430,16 +1406,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8) => ZIO[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1458,16 +1433,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9) => ZIO[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, E, B] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, E, B] = { + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1485,20 +1459,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1517,20 +1490,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1550,20 +1522,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1584,20 +1555,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1619,20 +1589,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1655,20 +1624,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1692,20 +1660,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1730,20 +1697,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1769,20 +1735,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1809,20 +1774,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1850,20 +1814,19 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services. + * Constructs a layer that effectfully depends on the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1915,42 +1878,42 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A20, A21 ) => ZIO[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20 with A21, E, B ] = { - val serviceBuilder = fromServicesManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManaged(andThen(f)(_.toManaged)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified service. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServiceManaged[A: Tag: IsNotIntersection, R, E, B: Tag: IsNotIntersection](f: A => ZManaged[R, E, B])(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A, E, B] = + ): ZLayer[R with A, E, B] = fromServiceManyManaged[A, R, E, B](a => f(a).asService) /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, R, E, B: Tag: IsNotIntersection]( f: (A0, A1) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1960,16 +1923,16 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -1982,16 +1945,16 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3) => ZManaged[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2005,16 +1968,16 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4) => ZManaged[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2029,16 +1992,16 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5) => ZManaged[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2052,16 +2015,16 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2078,16 +2041,16 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7) => ZManaged[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2105,16 +2068,16 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8) => ZManaged[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2133,16 +2096,16 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9) => ZManaged[R, E, B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2160,20 +2123,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2192,20 +2155,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2225,20 +2188,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2259,20 +2222,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2294,20 +2257,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2330,20 +2293,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2367,20 +2330,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2405,20 +2368,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified services. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2444,20 +2407,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified service. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2484,20 +2447,20 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B: Tag: IsNotIntersection ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** * Constructs a set of services that resourcefully and effectfully depends on * the specified service. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2547,7 +2510,7 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A19, A20 ) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20, E, B @@ -2585,7 +2548,7 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { * Constructs a set of services that resourcefully and effectfully depends on * the specified service. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2637,58 +2600,58 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A20, A21 ) => ZManaged[R, E, B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20 with A21, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.asService)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.asService)) + layer } /** - * Constructs a service builder that purely depends on the specified service, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified service, which must + * return one or more services. For the more common variant that returns a + * single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServiceMany[A: Tag: IsNotIntersection, B](f: A => ZEnvironment[B])(implicit trace: ZTraceElement - ): ZServiceBuilder[A, Nothing, B] = + ): ZLayer[A, Nothing, B] = fromServiceManyM[A, Any, Nothing, B](a => ZIO.succeedNow(f(a))) /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, B]( f: (A0, A1) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[A0 with A1, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[A0 with A1, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, A2: Tag: IsNotIntersection, B]( f: (A0, A1, A2) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[A0 with A1 with A2, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[A0 with A1 with A2, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2697,17 +2660,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[A0 with A1 with A2 with A3, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[A0 with A1 with A2 with A3, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2719,17 +2682,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4) => ZEnvironment[B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2742,17 +2705,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5) => ZEnvironment[B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4 with A5, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2764,17 +2727,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5 with A6, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[A0 with A1 with A2 with A3 with A4 with A5 with A6, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2789,17 +2752,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7) => ZEnvironment[B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2815,17 +2778,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8) => ZEnvironment[B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2842,17 +2805,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9) => ZEnvironment[B] )(implicit trace: ZTraceElement - ): ZServiceBuilder[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, Nothing, B] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + ): ZLayer[A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, Nothing, B] = { + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2868,21 +2831,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2899,21 +2862,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2931,21 +2894,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2964,21 +2927,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -2998,21 +2961,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3033,21 +2996,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3069,21 +3032,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3106,21 +3069,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3144,21 +3107,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3183,21 +3146,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3225,21 +3188,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20) => ZEnvironment[ B ] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that purely depends on the specified services, - * which must return one or more services. For the more common variant that - * returns a single service see `fromService`. + * Constructs a layer that purely depends on the specified services, which + * must return one or more services. For the more common variant that returns + * a single service see `fromService`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesMany[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3289,58 +3252,58 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A20, A21 ) => ZEnvironment[B] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20 with A21, Nothing, B ] = { - val serviceBuilder = fromServicesManyM(andThen(f)(ZIO.succeedNow)) - serviceBuilder + val layer = fromServicesManyM(andThen(f)(ZIO.succeedNow)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * service, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified service, which + * must return one or more services. For the more common variant that returns + * a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServiceManyM[A: Tag: IsNotIntersection, R, E, B](f: A => ZIO[R, E, ZEnvironment[B]])(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A, E, B] = + ): ZLayer[R with A, E, B] = fromServiceManyManaged[A, R, E, B](a => f(a).toManaged) /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, R, E, B]( f: (A0, A1) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, A2: Tag: IsNotIntersection, R, E, B]( f: (A0, A1, A2) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3351,17 +3314,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2 with A3, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2 with A3, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3375,17 +3338,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4) => ZIO[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3400,17 +3363,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5) => ZIO[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3424,17 +3387,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3451,17 +3414,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7) => ZIO[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3479,17 +3442,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8) => ZIO[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3508,17 +3471,17 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9) => ZIO[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, E, B] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, E, B] = { + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3536,21 +3499,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3569,21 +3532,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3603,21 +3566,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3638,21 +3601,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3674,21 +3637,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3711,21 +3674,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3749,21 +3712,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3788,21 +3751,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3848,21 +3811,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A17, A18 ) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3910,21 +3873,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A18, A19 ) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -3974,21 +3937,21 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A19, A20 ) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that effectfully depends on the specified - * services, which must return one or more services. For the more common - * variant that returns a single service see `fromServiceM`. + * Constructs a layer that effectfully depends on the specified services, + * which must return one or more services. For the more common variant that + * returns a single service see `fromServiceM`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyM[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4040,36 +4003,36 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A20, A21 ) => ZIO[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20 with A21, E, B ] = { - val serviceBuilder = fromServicesManyManaged(andThen(f)(_.toManaged)) - serviceBuilder + val layer = fromServicesManyManaged(andThen(f)(_.toManaged)) + layer } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified service, which must return one or more services. For the more + * Constructs a layer that resourcefully and effectfully depends on the + * specified service, which must return one or more services. For the more * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServiceManyManaged[A: Tag: IsNotIntersection, R, E, B](f: A => ZManaged[R, E, ZEnvironment[B]])(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A, E, B] = - ZServiceBuilder.fromManagedMany(ZManaged.serviceWithManaged[A](f)) + ): ZLayer[R with A, E, B] = + ZLayer.fromManagedMany(ZManaged.serviceWithManaged[A](f)) /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, R, E, B]( f: (A0, A1) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1, E, B] = - ZServiceBuilder.fromManagedMany { + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4078,11 +4041,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4092,8 +4055,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2, E, B] = - ZServiceBuilder.fromManagedMany { + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4103,11 +4066,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4118,8 +4081,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2 with A3, E, B] = - ZServiceBuilder.fromManagedMany { + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2 with A3, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4130,11 +4093,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4148,8 +4111,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4) => ZManaged[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4, E, B] = - ZServiceBuilder.fromManagedMany { + ): ZLayer[R with A0 with A1 with A2 with A3 with A4, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4161,11 +4124,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4180,8 +4143,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5) => ZManaged[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5, E, B] = - ZServiceBuilder.fromManagedMany { + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4194,11 +4157,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4212,8 +4175,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6, E, B] = - ZServiceBuilder.fromManagedMany { + )(implicit trace: ZTraceElement): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4227,11 +4190,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4248,8 +4211,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7) => ZManaged[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, E, B] = - ZServiceBuilder.fromManagedMany { + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4264,11 +4227,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4286,8 +4249,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8) => ZManaged[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, E, B] = - ZServiceBuilder.fromManagedMany { + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4303,11 +4266,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4326,8 +4289,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9) => ZManaged[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, E, B] = - ZServiceBuilder.fromManagedMany { + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4344,11 +4307,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4368,8 +4331,8 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) => ZManaged[R, E, ZEnvironment[B]] )(implicit trace: ZTraceElement - ): ZServiceBuilder[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10, E, B] = - ZServiceBuilder.fromManagedMany { + ): ZLayer[R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10, E, B] = + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4387,11 +4350,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4410,12 +4373,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4434,11 +4397,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4458,12 +4421,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4483,11 +4446,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4508,12 +4471,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4534,11 +4497,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4560,12 +4523,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4587,11 +4550,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4614,12 +4577,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4642,11 +4605,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4670,12 +4633,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { B ]( f: (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4699,11 +4662,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4747,12 +4710,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A16, A17 ) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4777,11 +4740,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4827,12 +4790,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A17, A18 ) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4858,11 +4821,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4910,12 +4873,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A18, A19 ) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -4942,11 +4905,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -4996,12 +4959,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A19, A20 ) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -5029,11 +4992,11 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder that resourcefully and effectfully depends on - * the specified services, which must return one or more services. For the - * more common variant that returns a single service see `fromServiceManaged`. + * Constructs a layer that resourcefully and effectfully depends on the + * specified services, which must return one or more services. For the more + * common variant that returns a single service see `fromServiceManaged`. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def fromServicesManyManaged[ A0: Tag: IsNotIntersection, A1: Tag: IsNotIntersection, @@ -5085,12 +5048,12 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { A20, A21 ) => ZManaged[R, E, ZEnvironment[B]] - )(implicit trace: ZTraceElement): ZServiceBuilder[ + )(implicit trace: ZTraceElement): ZLayer[ R with A0 with A1 with A2 with A3 with A4 with A5 with A6 with A7 with A8 with A9 with A10 with A11 with A12 with A13 with A14 with A15 with A16 with A17 with A18 with A19 with A20 with A21, E, B ] = - ZServiceBuilder.fromManagedMany { + ZLayer.fromManagedMany { for { a0 <- ZManaged.service[A0] a1 <- ZManaged.service[A1] @@ -5119,157 +5082,155 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { } /** - * Constructs a service builder from a managed resource. + * Constructs a layer from a managed resource. */ def fromManaged[R, E, A: Tag: IsNotIntersection](m: ZManaged[R, E, A])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = - ZServiceBuilder.fromManagedMany(m.map(ZEnvironment(_))) + ): ZLayer[R, E, A] = + ZLayer.fromManagedEnvironment(m.map(ZEnvironment(_))) /** - * Constructs a service builder from a managed resource, which must return one - * or more services. + * Constructs a layer from a managed resource, which must return one or more + * services. */ def fromManagedEnvironment[R, E, A](m: ZManaged[R, E, ZEnvironment[A]])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = + ): ZLayer[R, E, A] = Managed(m) /** - * Constructs a service builder from a managed resource, which must return one - * or more services. + * Constructs a layer from a managed resource, which must return one or more + * services. */ @deprecated("use fromManagedEnvironment", "2.0.0") def fromManagedMany[R, E, A](m: ZManaged[R, E, ZEnvironment[A]])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = + ): ZLayer[R, E, A] = fromManagedEnvironment(m) /** - * Constructs a service builder from the specified effect. + * Constructs a layer from the specified effect. */ def fromZIO[R, E, A: Tag: IsNotIntersection](zio: ZIO[R, E, A])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = - fromZIOMany(zio.map(ZEnvironment(_))) + ): ZLayer[R, E, A] = + fromZIOEnvironment(zio.map(ZEnvironment(_))) /** - * Constructs a service builder from the specified effect, which must return - * one or more services. + * Constructs a layer from the specified effect, which must return one or more + * services. */ def fromZIOEnvironment[R, E, A](zio: ZIO[R, E, ZEnvironment[A]])(implicit trace: ZTraceElement - ): ZServiceBuilder[R, E, A] = - ZServiceBuilder.fromManagedMany(ZManaged.fromZIO(zio)) + ): ZLayer[R, E, A] = + ZLayer.fromManagedEnvironment(ZManaged.fromZIO(zio)) /** - * Constructs a service builder from the specified effect, which must return - * one or more services. + * Constructs a layer from the specified effect, which must return one or more + * services. */ @deprecated("use fromZIOEnvironment", "2.0.0") - def fromZIOMany[R, E, A](zio: ZIO[R, E, ZEnvironment[A]])(implicit trace: ZTraceElement): ZServiceBuilder[R, E, A] = + def fromZIOMany[R, E, A](zio: ZIO[R, E, ZEnvironment[A]])(implicit trace: ZTraceElement): ZLayer[R, E, A] = fromZIOEnvironment(zio) /** - * An identity service builder that passes along its inputs. Note that this - * represents an identity with respect to the `>>>` operator. It represents an - * identity with respect to the `++` operator when the environment type is - * `Any`. + * An identity layer that passes along its inputs. Note that this represents + * an identity with respect to the `>>>` operator. It represents an identity + * with respect to the `++` operator when the environment type is `Any`. */ @deprecated("use environment", "2.0.0") - def identity[A: Tag](implicit trace: ZTraceElement): ZServiceBuilder[A, Nothing, A] = - ZServiceBuilder.environment[A] + def identity[A: Tag](implicit trace: ZTraceElement): ZLayer[A, Nothing, A] = + ZLayer.environment[A] /** - * Constructs a service builder that passes along the specified environment as - * an output. + * Constructs a layer that passes along the specified environment as an + * output. */ @deprecated("use environment", "2.0.0") - def requires[A: Tag](implicit trace: ZTraceElement): ZServiceBuilder[A, Nothing, A] = - ZServiceBuilder.environment[A] + def requires[A: Tag](implicit trace: ZTraceElement): ZLayer[A, Nothing, A] = + ZLayer.environment[A] /** - * Constructs a service builder that passes along the specified environment as - * an output. + * Constructs a layer that passes along the specified environment as an + * output. */ - def environment[A](implicit trace: ZTraceElement): ZServiceBuilder[A, Nothing, A] = - ZServiceBuilder.fromManagedMany(ZManaged.environment[A]) + def environment[A](implicit trace: ZTraceElement): ZLayer[A, Nothing, A] = + ZLayer.fromManagedEnvironment(ZManaged.environment[A]) /** - * Constructs a service builder that accesses and returns the specified - * service from the environment. + * Constructs a layer that accesses and returns the specified service from the + * environment. */ - def service[A: Tag: IsNotIntersection](implicit trace: ZTraceElement): ZServiceBuilder[A, Nothing, A] = - ZServiceBuilder.fromManaged(ZManaged.service[A]) + def service[A: Tag: IsNotIntersection](implicit trace: ZTraceElement): ZLayer[A, Nothing, A] = + ZLayer.fromManaged(ZManaged.service[A]) /** - * Constructs a service builder from the specified value. + * Constructs a layer from the specified value. */ - def succeed[A: Tag: IsNotIntersection](a: A)(implicit trace: ZTraceElement): UServiceBuilder[A] = - ZServiceBuilder.fromManagedMany(ZManaged.succeedNow(ZEnvironment(a))) + def succeed[A: Tag: IsNotIntersection](a: A)(implicit trace: ZTraceElement): ULayer[A] = + ZLayer.fromManagedEnvironment(ZManaged.succeedNow(ZEnvironment(a))) /** - * Constructs a service builder from the specified value, which must return - * one or more services. + * Constructs a layer from the specified value, which must return one or more + * services. */ - def succeedEnvironment[A](a: ZEnvironment[A])(implicit trace: ZTraceElement): UServiceBuilder[A] = - ZServiceBuilder.fromManagedMany(ZManaged.succeedNow(a)) + def succeedEnvironment[A](a: ZEnvironment[A])(implicit trace: ZTraceElement): ULayer[A] = + ZLayer.fromManagedEnvironment(ZManaged.succeedNow(a)) /** - * Constructs a service builder from the specified value, which must return - * one or more services. + * Constructs a layer from the specified value, which must return one or more + * services. */ @deprecated("use succeedEnvironment", "2.0.0") - def succeedMany[A](a: ZEnvironment[A])(implicit trace: ZTraceElement): UServiceBuilder[A] = + def succeedMany[A](a: ZEnvironment[A])(implicit trace: ZTraceElement): ULayer[A] = succeedEnvironment(a) /** - * Lazily constructs a service builder. This is useful to avoid infinite - * recursion when creating service builders that refer to themselves. + * Lazily constructs a layer. This is useful to avoid infinite recursion when + * creating layers that refer to themselves. */ - def suspend[RIn, E, ROut](serviceBuilder: => ZServiceBuilder[RIn, E, ROut]): ZServiceBuilder[RIn, E, ROut] = { - lazy val self = serviceBuilder + def suspend[RIn, E, ROut](layer: => ZLayer[RIn, E, ROut]): ZLayer[RIn, E, ROut] = { + lazy val self = layer Suspend(() => self) } - implicit final class ZServiceBuilderPassthroughOps[RIn, E, ROut](private val self: ZServiceBuilder[RIn, E, ROut]) - extends AnyVal { + implicit final class ZLayerPassthroughOps[RIn, E, ROut](private val self: ZLayer[RIn, E, ROut]) extends AnyVal { /** - * Returns a new service builder that produces the outputs of this service - * builder but also passes through the inputs. + * Returns a new layer that produces the outputs of this layer but also + * passes through the inputs. */ def passthrough(implicit in: Tag[RIn], out: Tag[ROut], trace: ZTraceElement - ): ZServiceBuilder[RIn, E, RIn with ROut] = - ZServiceBuilder.environment[RIn] ++ self + ): ZLayer[RIn, E, RIn with ROut] = + ZLayer.environment[RIn] ++ self } - implicit final class ZServiceBuilderProjectOps[R, E, A](private val self: ZServiceBuilder[R, E, A]) extends AnyVal { + implicit final class ZLayerProjectOps[R, E, A](private val self: ZLayer[R, E, A]) extends AnyVal { /** - * Projects out part of one of the services output by this service builder - * using the specified function. + * Projects out part of one of the services output by this layer using the + * specified function. */ def project[B: Tag: IsNotIntersection]( f: A => B - )(implicit ev: IsNotIntersection[A], tag: Tag[A], trace: ZTraceElement): ZServiceBuilder[R, E, B] = + )(implicit ev: IsNotIntersection[A], tag: Tag[A], trace: ZTraceElement): ZLayer[R, E, B] = self.map(environment => ZEnvironment(f(environment.get))) } /** - * A `MemoMap` memoizes service builders. + * A `MemoMap` memoizes layers. */ private abstract class MemoMap { self => /** - * Checks the memo map to see if a service builder exists. If it is, - * immediately returns it. Otherwise, obtains the service builder, stores it - * in the memo map, and adds a finalizer to the outer `Managed`. + * Checks the memo map to see if a layer exists. If it is, immediately + * returns it. Otherwise, obtains the layer, stores it in the memo map, and + * adds a finalizer to the outer `Managed`. */ - def getOrElseMemoize[E, A, B](serviceBuilder: ZServiceBuilder[A, E, B]): ZManaged[A, E, ZEnvironment[B]] + def getOrElseMemoize[E, A, B](layer: ZLayer[A, E, B]): ZManaged[A, E, ZEnvironment[B]] } private object MemoMap { @@ -5279,15 +5240,15 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { */ def make(implicit trace: ZTraceElement): UIO[MemoMap] = Ref.Synchronized - .make[Map[ZServiceBuilder[Nothing, Any, Any], (IO[Any, Any], ZManaged.Finalizer)]](Map.empty) + .make[Map[ZLayer[Nothing, Any, Any], (IO[Any, Any], ZManaged.Finalizer)]](Map.empty) .map { ref => new MemoMap { self => final def getOrElseMemoize[E, A, B]( - serviceBuilder: ZServiceBuilder[A, E, B] + layer: ZLayer[A, E, B] ): ZManaged[A, E, ZEnvironment[B]] = ZManaged { ref.modifyZIO { map => - map.get(serviceBuilder) match { + map.get(layer) match { case Some((acquire, release)) => val cached = ZManaged.currentReleaseMap.get.flatMap { releaseMap => @@ -5316,7 +5277,7 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { tp <- restore( ZManaged.currentReleaseMap.locally(innerReleaseMap)( - serviceBuilder.scope.flatMap(_.apply(self)).zio + layer.scope.flatMap(_.apply(self)).zio ) ).exit.flatMap { case e @ Exit.Failure(cause) => @@ -5349,7 +5310,7 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { }, (exit: Exit[Any, Any]) => finalizerRef.get.flatMap(_(exit)) ) - } yield (resource, if (serviceBuilder.isFresh) map else map + (serviceBuilder -> memoized)) + } yield (resource, if (layer.isFresh) map else map + (layer -> memoized)) } }.flatten @@ -5514,8 +5475,7 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21) => g(f(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21)) - implicit final class ZServiceBuilderProvideSomeOps[RIn, E, ROut](private val self: ZServiceBuilder[RIn, E, ROut]) - extends AnyVal { + implicit final class ZLayerProvideSomeOps[RIn, E, ROut](private val self: ZLayer[RIn, E, ROut]) extends AnyVal { /** * Feeds the output services of this builder into the input of the specified @@ -5523,45 +5483,45 @@ object ZServiceBuilder extends ZServiceBuilderCompanionVersionSpecific { * well as any leftover inputs, and the outputs of the specified builder. */ def >>>[RIn2, E1 >: E, ROut2]( - that: ZServiceBuilder[ROut with RIn2, E1, ROut2] - )(implicit tag: Tag[ROut], trace: ZTraceElement): ZServiceBuilder[RIn with RIn2, E1, ROut2] = - ZServiceBuilder.To(ZServiceBuilder.environment[RIn2] ++ self, that) + that: ZLayer[ROut with RIn2, E1, ROut2] + )(implicit tag: Tag[ROut], trace: ZTraceElement): ZLayer[RIn with RIn2, E1, ROut2] = + ZLayer.To(ZLayer.environment[RIn2] ++ self, that) /** * Feeds the output services of this builder into the input of the specified * builder, resulting in a new builder with the inputs of this builder as * well as any leftover inputs, and the outputs of the specified builder. */ - def >>>[E1 >: E, ROut2](that: ZServiceBuilder[ROut, E1, ROut2])(implicit + def >>>[E1 >: E, ROut2](that: ZLayer[ROut, E1, ROut2])(implicit trace: ZTraceElement - ): ZServiceBuilder[RIn, E1, ROut2] = - ZServiceBuilder.To(self, that) + ): ZLayer[RIn, E1, ROut2] = + ZLayer.To(self, that) /** - * Feeds the output services of this service builder into the input of the - * specified service builder, resulting in a new service builder with the - * inputs of this service builder, and the outputs of both service builders. + * Feeds the output services of this layer into the input of the specified + * layer, resulting in a new layer with the inputs of this layer, and the + * outputs of both layers. */ def >+>[RIn2, E1 >: E, ROut2]( - that: ZServiceBuilder[ROut with RIn2, E1, ROut2] + that: ZLayer[ROut with RIn2, E1, ROut2] )(implicit tagged: Tag[ROut], tagged2: Tag[ROut2], trace: ZTraceElement - ): ZServiceBuilder[RIn with RIn2, E1, ROut with ROut2] = + ): ZLayer[RIn with RIn2, E1, ROut with ROut2] = self ++ self.>>>[RIn2, E1, ROut2](that) /** - * Feeds the output services of this service builder into the input of the - * specified service builder, resulting in a new service builder with the - * inputs of this service builder, and the outputs of both service builders. + * Feeds the output services of this layer into the input of the specified + * layer, resulting in a new layer with the inputs of this layer, and the + * outputs of both layers. */ def >+>[E1 >: E, RIn2 >: ROut, ROut1 >: ROut, ROut2]( - that: ZServiceBuilder[RIn2, E1, ROut2] + that: ZLayer[RIn2, E1, ROut2] )(implicit tagged: Tag[ROut2], trace: ZTraceElement - ): ZServiceBuilder[RIn, E1, ROut1 with ROut2] = + ): ZLayer[RIn, E1, ROut1 with ROut2] = self.zipWithPar(self >>> that)(_.union[ROut2](_)) } diff --git a/core/shared/src/main/scala/zio/ZManaged.scala b/core/shared/src/main/scala/zio/ZManaged.scala index 980b95b0673c..b1f5a636814f 100644 --- a/core/shared/src/main/scala/zio/ZManaged.scala +++ b/core/shared/src/main/scala/zio/ZManaged.scala @@ -172,7 +172,7 @@ sealed abstract class ZManaged[-R, +E, +A] extends ZManagedVersionSpecific[R, E, /** * Maps the success value of this effect to a service. */ - @deprecated("use toServiceBuilder", "2.0.0") + @deprecated("use toLayer", "2.0.0") def asService[A1 >: A: Tag: IsNotIntersection](implicit trace: ZTraceElement): ZManaged[R, E, ZEnvironment[A1]] = map(ZEnvironment[A1](_)) @@ -809,41 +809,40 @@ sealed abstract class ZManaged[-R, +E, +A] extends ZManagedVersionSpecific[R, E, } /** - * Provides a service builder to the `ZManaged`, which translates it to - * another level. + * Provides a layer to the `ZManaged`, which translates it to another level. */ final def provide[E1 >: E, R0, R1]( - serviceBuilder: => ZServiceBuilder[R0, E1, R1] + layer: => ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): ZManaged[R0, E1, A] = - ZManaged.suspend(serviceBuilder.build.map(_.upcast(ev)).flatMap(r => self.provideEnvironment(r))) + ZManaged.suspend(layer.build.map(_.upcast(ev)).flatMap(r => self.provideEnvironment(r))) /** * Provides the part of the environment that is not part of the `ZEnv`, * leaving a managed effect that only depends on the `ZEnv`. * * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val managed: ZManaged[ZEnv with Logging, Nothing, Unit] = ??? * - * val managed2 = managed.provideCustom(loggingServiceBuilder) + * val managed2 = managed.provideCustom(loggingLayer) * }}} */ final def provideCustom[E1 >: E, R1]( - serviceBuilder: => ZServiceBuilder[ZEnv, E1, R1] + layer: => ZLayer[ZEnv, E1, R1] )(implicit ev: ZEnv with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement ): ZManaged[ZEnv, E1, A] = - provideSome[ZEnv](serviceBuilder) + provideSome[ZEnv](layer) /** * Provides the part of the environment that is not part of the `ZEnv`, * leaving a managed effect that only depends on the `ZEnv`. * * {{{ - * val loggingLayer: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val managed: ZManaged[ZEnv with Logging, Nothing, Unit] = ??? * @@ -852,7 +851,7 @@ sealed abstract class ZManaged[-R, +E, +A] extends ZManagedVersionSpecific[R, E, */ @deprecated("use provideCustom", "2.0.0") final def provideCustomLayer[E1 >: E, R1]( - layer: => ZServiceBuilder[ZEnv, E1, R1] + layer: => ZLayer[ZEnv, E1, R1] )(implicit ev: ZEnv with R1 <:< R, tagged: Tag[R1], @@ -860,27 +859,6 @@ sealed abstract class ZManaged[-R, +E, +A] extends ZManagedVersionSpecific[R, E, ): ZManaged[ZEnv, E1, A] = provideCustom(layer) - /** - * Provides the part of the environment that is not part of the `ZEnv`, - * leaving a managed effect that only depends on the `ZEnv`. - * - * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? - * - * val managed: ZManaged[ZEnv with Logging, Nothing, Unit] = ??? - * - * val managed2 = managed.provideCustomServices(loggingServiceBuilder) - * }}} - */ - final def provideCustomServices[E1 >: E, R1]( - serviceBuilder: => ZServiceBuilder[ZEnv, E1, R1] - )(implicit - ev: ZEnv with R1 <:< R, - tagged: Tag[R1], - trace: ZTraceElement - ): ZManaged[ZEnv, E1, A] = - provideCustom(serviceBuilder) - /** * Provides the `ZManaged` effect with its required environment, which * eliminates its dependency on `R`. @@ -893,29 +871,20 @@ sealed abstract class ZManaged[-R, +E, +A] extends ZManagedVersionSpecific[R, E, */ @deprecated("use provide", "2.0.0") final def provideLayer[E1 >: E, R0, R1]( - layer: => ZServiceBuilder[R0, E1, R1] + layer: => ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): ZManaged[R0, E1, A] = provide(layer) - /** - * Provides a service builder to the `ZManaged`, which translates it to - * another level. - */ - final def provideServices[E1 >: E, R0, R1]( - serviceBuilder: => ZServiceBuilder[R0, E1, R1] - )(implicit ev: R1 <:< R, trace: ZTraceElement): ZManaged[R0, E1, A] = - provide(serviceBuilder) - /** * Splits the environment into two parts, providing one part using the - * specified service builder and leaving the remainder `R0`. + * specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val managed: ZManaged[Clock with Random, Nothing, Unit] = ??? * - * val managed2 = managed.provideSome[Random](clockServiceBuilder) + * val managed2 = managed.provideSome[Random](clockLayer) * }}} */ final def provideSome[R0]: ZManaged.ProvideSome[R0, R, E, A] = @@ -935,7 +904,7 @@ sealed abstract class ZManaged[-R, +E, +A] extends ZManagedVersionSpecific[R, E, * specified layer and leaving the remainder `R0`. * * {{{ - * val clockLayer: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val managed: ZManaged[Clock with Random, Nothing, Unit] = ??? * @@ -946,21 +915,6 @@ sealed abstract class ZManaged[-R, +E, +A] extends ZManagedVersionSpecific[R, E, final def provideSomeLayer[R0]: ZManaged.ProvideSome[R0, R, E, A] = provideSome - /** - * Splits the environment into two parts, providing one part using the - * specified service builder and leaving the remainder `R0`. - * - * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? - * - * val managed: ZManaged[Clock with Random, Nothing, Unit] = ??? - * - * val managed2 = managed.provideSomeServices[Random](clockServiceBuilder) - * }}} - */ - final def provideSomeServices[R0]: ZManaged.ProvideSome[R0, R, E, A] = - provideSome - /** * Keeps some of the errors, and terminates the fiber with the rest. */ @@ -1249,46 +1203,31 @@ sealed abstract class ZManaged[-R, +E, +A] extends ZManagedVersionSpecific[R, E, } /** - * Constructs a service builder from this managed resource. + * Constructs a layer from this managed resource. */ - def toServiceBuilder[A1 >: A: Tag: IsNotIntersection](implicit trace: ZTraceElement): ZServiceBuilder[R, E, A1] = - ZServiceBuilder.fromManaged[R, E, A1](self) + def toLayer[A1 >: A: Tag: IsNotIntersection](implicit trace: ZTraceElement): ZLayer[R, E, A1] = + ZLayer.fromManaged[R, E, A1](self) /** - * Constructs a service builder from this managed resource, which must return - * one or more services. + * Constructs a layer from this managed resource, which must return one or + * more services. */ - final def toServiceBuilderEnvironment[B](implicit + final def toLayerEnvironment[B](implicit ev: A <:< ZEnvironment[B], trace: ZTraceElement - ): ZServiceBuilder[R, E, B] = - ZServiceBuilder.fromManagedMany(self.map(ev)) + ): ZLayer[R, E, B] = + ZLayer.fromManagedMany(self.map(ev)) /** - * Constructs a service builder from this managed resource, which must return - * one or more setoServiceBuilderEnvironment + * Constructs a layer from this managed resource, which must return one or + * more setoLayerEnvironment */ - @deprecated("use toServiceBuilderEnvironment", "2.0.0") - final def toServiceBuilderMany[B](implicit + @deprecated("use toLayerEnvironment", "2.0.0") + final def toLayerMany[B](implicit ev: A <:< ZEnvironment[B], trace: ZTraceElement - ): ZServiceBuilder[R, E, B] = - toServiceBuilderEnvironment - - /** - * Constructs a layer from this managed resource. - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer[A1 >: A: Tag: IsNotIntersection](implicit trace: ZTraceElement): ZServiceBuilder[R, E, A1] = - toServiceBuilder[A1] - - /** - * Constructs a layer from this managed resource, which must return one or - * more services. - */ - @deprecated("use toServiceBuilderMany", "2.0.0") - final def toLayerMany[B](implicit ev: A <:< ZEnvironment[B], trace: ZTraceElement): ZServiceBuilder[R, E, B] = - toServiceBuilderMany + ): ZLayer[R, E, B] = + toLayerEnvironment /** * Return unit while running the effect @@ -1630,13 +1569,13 @@ object ZManaged extends ZManagedPlatformSpecific { final class ProvideSome[R0, -R, +E, +A](private val self: ZManaged[R, E, A]) extends AnyVal { def apply[E1 >: E, R1]( - serviceBuilder: => ZServiceBuilder[R0, E1, R1] + layer: => ZLayer[R0, E1, R1] )(implicit ev: R0 with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement ): ZManaged[R0, E1, A] = - self.provide[E1, R0, R0 with R1](ZServiceBuilder.environment[R0] ++ serviceBuilder) + self.provide[E1, R0, R0 with R1](ZLayer.environment[R0] ++ layer) } final class UnlessManaged[R, E](private val b: () => ZManaged[R, E, Boolean]) extends AnyVal { @@ -3181,10 +3120,10 @@ object ZManaged extends ZManagedPlatformSpecific { } } - def provide[RIn, E, ROut, RIn2, ROut2](builder: ZServiceBuilder[RIn, E, ROut])( + def provide[RIn, E, ROut, RIn2, ROut2](builder: ZLayer[RIn, E, ROut])( managed: ZManaged[ROut with RIn2, E, ROut2] )(implicit ev: Tag[RIn2], tag: Tag[ROut], trace: ZTraceElement): ZManaged[RIn with RIn2, E, ROut2] = - managed.provideSomeServices[RIn with RIn2](ZServiceBuilder.environment[RIn2] ++ builder) + managed.provideSomeLayer[RIn with RIn2](ZLayer.environment[RIn2] ++ builder) /** * Reduces an `Iterable[IO]` to a single `IO`, working sequentially. diff --git a/core/shared/src/main/scala/zio/ZState.scala b/core/shared/src/main/scala/zio/ZState.scala index 728fffa54d21..b4f2158ccf59 100644 --- a/core/shared/src/main/scala/zio/ZState.scala +++ b/core/shared/src/main/scala/zio/ZState.scala @@ -37,9 +37,8 @@ import zio.stacktracer.TracingImplicits.disableAutoTrace * than using a type such as `Int` to avoid the risk of ambiguity. * * To run an effect that depends on some state, create the initial state with - * the `make` constructor and then use `toServiceBuilder` to convert it into a - * service builder that you can provide along with your application's other - * services. + * the `make` constructor and then use `toLayer` to convert it into a service + * builder that you can provide along with your application's other services. */ sealed trait ZState[S] { @@ -77,9 +76,8 @@ object ZState { } /** - * Creates a service builder that outputs an initial state with the specified - * value. + * Creates a layer that outputs an initial state with the specified value. */ - def makeServiceBuilder[S: Tag](s: S)(implicit trace: ZTraceElement): ZServiceBuilder[Any, Nothing, ZState[S]] = - make(s).toServiceBuilder + def makeLayer[S: Tag](s: S)(implicit trace: ZTraceElement): ZLayer[Any, Nothing, ZState[S]] = + make(s).toLayer } diff --git a/core/shared/src/main/scala/zio/internal/macros/Graph.scala b/core/shared/src/main/scala/zio/internal/macros/Graph.scala index 9d542eafc8c2..2a91102f423d 100644 --- a/core/shared/src/main/scala/zio/internal/macros/Graph.scala +++ b/core/shared/src/main/scala/zio/internal/macros/Graph.scala @@ -1,9 +1,9 @@ package zio.internal.macros -import zio.internal.macros.ServiceBuilderCompose._ +import zio.internal.macros.LayerCompose._ final case class Graph[Key, A](nodes: List[Node[Key, A]], keyEquals: (Key, Key) => Boolean) { - def buildComplete(outputs: List[Key]): Either[::[GraphError[Key, A]], ServiceBuilderCompose[A]] = + def buildComplete(outputs: List[Key]): Either[::[GraphError[Key, A]], LayerCompose[A]] = forEach(outputs) { output => getNodeWithOutput[GraphError[Key, A]](output, error = GraphError.MissingTopLevelDependency(output)) .flatMap(node => buildNode(node, Set(node))) @@ -25,12 +25,12 @@ final case class Graph[Key, A](nodes: List[Node[Key, A]], keyEquals: (Key, Key) private def buildNode( node: Node[Key, A], seen: Set[Node[Key, A]] - ): Either[::[GraphError[Key, A]], ServiceBuilderCompose[A]] = + ): Either[::[GraphError[Key, A]], LayerCompose[A]] = getDependencies(node).flatMap { forEach(_) { out => assertNonCircularDependency(node, seen, out).flatMap(_ => buildNode(out, seen + out)) }.map { - _.distinct.combineHorizontally >>> ServiceBuilderCompose.succeed(node.value) + _.distinct.combineHorizontally >>> LayerCompose.succeed(node.value) } } diff --git a/core/shared/src/main/scala/zio/internal/macros/LayerCompose.scala b/core/shared/src/main/scala/zio/internal/macros/LayerCompose.scala new file mode 100644 index 000000000000..dec6fbb55446 --- /dev/null +++ b/core/shared/src/main/scala/zio/internal/macros/LayerCompose.scala @@ -0,0 +1,36 @@ +package zio.internal.macros + +import zio.internal.macros.LayerCompose.{ComposeH, ComposeV, Empty, Value} + +sealed abstract class LayerCompose[+A] extends Product with Serializable { self => + def >>>[A1 >: A](that: LayerCompose[A1]): LayerCompose[A1] = + if (self eq Empty) that else if (that eq Empty) self else ComposeV(self, that) + + def ++[A1 >: A](that: LayerCompose[A1]): LayerCompose[A1] = + if (self eq Empty) that else if (that eq Empty) self else ComposeH(self, that) + + def fold[B](z: B, value: A => B, composeH: (B, B) => B, composeV: (B, B) => B): B = self match { + case Empty => z + case Value(value0) => value(value0) + case ComposeH(left, right) => + composeH(left.fold(z, value, composeH, composeV), right.fold(z, value, composeH, composeV)) + case ComposeV(left, right) => + composeV(left.fold(z, value, composeH, composeV), right.fold(z, value, composeH, composeV)) + } + + def toSet[A1 >: A]: Set[A1] = fold[Set[A1]](Set.empty[A1], Set(_), _ ++ _, _ ++ _) +} + +object LayerCompose { + def succeed[A](value: A): LayerCompose[A] = Value(value) + def empty: LayerCompose[Nothing] = Empty + + case object Empty extends LayerCompose[Nothing] + final case class Value[+A](value: A) extends LayerCompose[A] + final case class ComposeH[+A](left: LayerCompose[A], right: LayerCompose[A]) extends LayerCompose[A] + final case class ComposeV[+A](left: LayerCompose[A], right: LayerCompose[A]) extends LayerCompose[A] + + implicit final class LayerComposeIterableOps[A](private val self: Iterable[LayerCompose[A]]) extends AnyVal { + def combineHorizontally: LayerCompose[A] = self.foldLeft[LayerCompose[A]](Empty)(_ ++ _) + } +} diff --git a/core/shared/src/main/scala/zio/internal/macros/ServiceBuilderExprBuilder.scala b/core/shared/src/main/scala/zio/internal/macros/LayerExprBuilder.scala similarity index 85% rename from core/shared/src/main/scala/zio/internal/macros/ServiceBuilderExprBuilder.scala rename to core/shared/src/main/scala/zio/internal/macros/LayerExprBuilder.scala index 0eed202b04de..eca24a0340d6 100644 --- a/core/shared/src/main/scala/zio/internal/macros/ServiceBuilderExprBuilder.scala +++ b/core/shared/src/main/scala/zio/internal/macros/LayerExprBuilder.scala @@ -3,7 +3,7 @@ package zio.internal.macros import zio._ import zio.internal.ansi.AnsiStringOps -final case class ZServiceBuilderExprBuilder[Key, A]( +final case class ZLayerExprBuilder[Key, A]( graph: Graph[Key, A], showKey: Key => String, showExpr: A => String, @@ -12,7 +12,7 @@ final case class ZServiceBuilderExprBuilder[Key, A]( composeH: (A, A) => A, composeV: (A, A) => A ) { - def buildServiceBuilderFor(output: List[Key]): A = + def buildLayerFor(output: List[Key]): A = output match { case Nil => emptyExpr case output => @@ -27,8 +27,8 @@ final case class ZServiceBuilderExprBuilder[Key, A]( } } - private def assertNoLeftovers(serviceBuilderCompose: ServiceBuilderCompose[A]): Unit = { - val used = serviceBuilderCompose.toSet + private def assertNoLeftovers(layerCompose: LayerCompose[A]): Unit = { + val used = layerCompose.toSet val leftovers = graph.nodes.filterNot(node => used.contains(node.value)) if (leftovers.nonEmpty) { @@ -52,7 +52,7 @@ final case class ZServiceBuilderExprBuilder[Key, A]( if (outputMap.nonEmpty) { val message = outputMap.map { case (output, nodes) => - s"${output.toString.cyan} is provided by multiple service builders:\n" + + s"${output.toString.cyan} is provided by multiple layers:\n" + nodes.map(node => "— " + showExpr(node.value).bold.cyan).mkString("\n") } .mkString("\n") @@ -72,7 +72,7 @@ final case class ZServiceBuilderExprBuilder[Key, A]( abort(s""" -${s" ZServiceBuilder Wiring Error ".red.inverted.bold} +${s" ZLayer Wiring Error ".red.inverted.bold} $body @@ -109,8 +109,8 @@ $body } val groupedTransitiveErrors = transitiveDepErrors.groupBy(_.node).map { case (node, errors) => - val serviceBuilder = errors.flatMap(_.dependency) - GraphError.MissingTransitiveDependencies(node, serviceBuilder) + val layer = errors.flatMap(_.dependency) + GraphError.MissingTransitiveDependencies(node, layer) } initialCircularErrors ++ groupedTransitiveErrors ++ remainingErrors @@ -125,9 +125,9 @@ $body s"""$prefix $styled""" } .mkString("\n") - val styledServiceBuilder = showExpr(node.value).blue + val styledLayer = showExpr(node.value).blue s"""$styledDependencies - ${"for".underlined} $styledServiceBuilder""" + ${"for".underlined} $styledLayer""" case GraphError.MissingTopLevelDependency(dependency) => val styledDependency = showKey(dependency).blue.bold @@ -142,4 +142,4 @@ $styledNode both requires ${"and".bold} is transitively required by $styledDepen } } -object ZServiceBuilderExprBuilder extends ExprGraphCompileVariants {} +object ZLayerExprBuilder extends ExprGraphCompileVariants {} diff --git a/core/shared/src/main/scala/zio/internal/macros/ServiceBuilderCompose.scala b/core/shared/src/main/scala/zio/internal/macros/ServiceBuilderCompose.scala deleted file mode 100644 index c253dd1c12d9..000000000000 --- a/core/shared/src/main/scala/zio/internal/macros/ServiceBuilderCompose.scala +++ /dev/null @@ -1,39 +0,0 @@ -package zio.internal.macros - -import zio.internal.macros.ServiceBuilderCompose.{ComposeH, ComposeV, Empty, Value} - -sealed abstract class ServiceBuilderCompose[+A] extends Product with Serializable { self => - def >>>[A1 >: A](that: ServiceBuilderCompose[A1]): ServiceBuilderCompose[A1] = - if (self eq Empty) that else if (that eq Empty) self else ComposeV(self, that) - - def ++[A1 >: A](that: ServiceBuilderCompose[A1]): ServiceBuilderCompose[A1] = - if (self eq Empty) that else if (that eq Empty) self else ComposeH(self, that) - - def fold[B](z: B, value: A => B, composeH: (B, B) => B, composeV: (B, B) => B): B = self match { - case Empty => z - case Value(value0) => value(value0) - case ComposeH(left, right) => - composeH(left.fold(z, value, composeH, composeV), right.fold(z, value, composeH, composeV)) - case ComposeV(left, right) => - composeV(left.fold(z, value, composeH, composeV), right.fold(z, value, composeH, composeV)) - } - - def toSet[A1 >: A]: Set[A1] = fold[Set[A1]](Set.empty[A1], Set(_), _ ++ _, _ ++ _) -} - -object ServiceBuilderCompose { - def succeed[A](value: A): ServiceBuilderCompose[A] = Value(value) - def empty: ServiceBuilderCompose[Nothing] = Empty - - case object Empty extends ServiceBuilderCompose[Nothing] - final case class Value[+A](value: A) extends ServiceBuilderCompose[A] - final case class ComposeH[+A](left: ServiceBuilderCompose[A], right: ServiceBuilderCompose[A]) - extends ServiceBuilderCompose[A] - final case class ComposeV[+A](left: ServiceBuilderCompose[A], right: ServiceBuilderCompose[A]) - extends ServiceBuilderCompose[A] - - implicit final class ServiceBuilderComposeIterableOps[A](private val self: Iterable[ServiceBuilderCompose[A]]) - extends AnyVal { - def combineHorizontally: ServiceBuilderCompose[A] = self.foldLeft[ServiceBuilderCompose[A]](Empty)(_ ++ _) - } -} diff --git a/core/shared/src/main/scala/zio/package.scala b/core/shared/src/main/scala/zio/package.scala index c355642a7abd..1260bb1c0dcc 100644 --- a/core/shared/src/main/scala/zio/package.scala +++ b/core/shared/src/main/scala/zio/package.scala @@ -20,7 +20,7 @@ import zio.stacktracer.TracingImplicits.disableAutoTrace package object zio extends BuildFromCompat with EitherCompat - with FunctionToServiceBuilderOps + with FunctionToLayerSyntax with IntersectionTypeCompat with VersionSpecific with DurationModule { @@ -45,27 +45,11 @@ package object zio val Managed: ZManaged.type = ZManaged - type RServiceBuilder[-RIn, +ROut] = ZServiceBuilder[RIn, Throwable, ROut] - type URServiceBuilder[-RIn, +ROut] = ZServiceBuilder[RIn, Nothing, ROut] - type ServiceBuilder[+E, +ROut] = ZServiceBuilder[Any, E, ROut] - type UServiceBuilder[+ROut] = ZServiceBuilder[Any, Nothing, ROut] - type TaskServiceBuilder[+ROut] = ZServiceBuilder[Any, Throwable, ROut] - - @deprecated("use ZServiceBuilder", "2.0.0") - type ZLayer[-RIn, +E, +ROut] = ZServiceBuilder[RIn, E, ROut] - @deprecated("use ZServiceBuilder", "2.0.0") - val ZLayer: ZServiceBuilder.type = ZServiceBuilder - - @deprecated("use RServiceBuilder", "2.0.0") - type RLayer[-RIn, +ROut] = ZServiceBuilder[RIn, Throwable, ROut] - @deprecated("use URServiceBuilder", "2.0.0") - type URLayer[-RIn, +ROut] = ZServiceBuilder[RIn, Nothing, ROut] - @deprecated("use ServiceBuilder", "2.0.0") - type Layer[+E, +ROut] = ZServiceBuilder[Any, E, ROut] - @deprecated("use UServiceBuilder", "2.0.0") - type ULayer[+ROut] = ZServiceBuilder[Any, Nothing, ROut] - @deprecated("use TaskServiceBuilder", "2.0.0") - type TaskLayer[+ROut] = ZServiceBuilder[Any, Throwable, ROut] + type RLayer[-RIn, +ROut] = ZLayer[RIn, Throwable, ROut] + type URLayer[-RIn, +ROut] = ZLayer[RIn, Nothing, ROut] + type Layer[+E, +ROut] = ZLayer[Any, E, ROut] + type ULayer[+ROut] = ZLayer[Any, Nothing, ROut] + type TaskLayer[+ROut] = ZLayer[Any, Throwable, ROut] type Queue[A] = ZQueue[Any, Any, Nothing, Nothing, A, A] val Queue: ZQueue.type = ZQueue diff --git a/core/shared/src/main/scala/zio/stm/TRandom.scala b/core/shared/src/main/scala/zio/stm/TRandom.scala index 2be7f7aefba2..954627c74573 100644 --- a/core/shared/src/main/scala/zio/stm/TRandom.scala +++ b/core/shared/src/main/scala/zio/stm/TRandom.scala @@ -44,12 +44,12 @@ trait TRandom { object TRandom extends Serializable { - val any: ZServiceBuilder[TRandom, Nothing, TRandom] = { + val any: ZLayer[TRandom, Nothing, TRandom] = { implicit val trace = Tracer.newTrace - ZServiceBuilder.service[TRandom] + ZLayer.service[TRandom] } - val live: ZServiceBuilder[Random, Nothing, TRandom] = { + val live: ZLayer[Random, Nothing, TRandom] = { implicit val trace = Tracer.newTrace Random.nextLong.flatMap { init => TRef @@ -58,7 +58,7 @@ object TRandom extends Serializable { TRandomLive(seed) } .commit - }.toServiceBuilder + }.toLayer } /** diff --git a/docs/datatypes/contextual/index.md b/docs/datatypes/contextual/index.md index 16816f8f0ec3..e71f37c0e90e 100644 --- a/docs/datatypes/contextual/index.md +++ b/docs/datatypes/contextual/index.md @@ -55,7 +55,7 @@ val effect: ZIO[Console with Random, Nothing, Unit] = for { val mainApp: ZIO[Any, Nothing, Unit] = effect.provide(Console.live ++ Random.live) ``` -We don't need to provide live service builders for built-in services (don't worry, we will discuss service builders later in this page). ZIO has a `ZEnv` type alias for the composition of all ZIO built-in services (Clock, Console, System, Random, and Blocking). So we can run the above `effect` as follows: +We don't need to provide live layers for built-in services (don't worry, we will discuss layers later in this page). ZIO has a `ZEnv` type alias for the composition of all ZIO built-in services (Clock, Console, System, Random, and Blocking). So we can run the above `effect` as follows: ```scala mdoc:compile-only import zio._ @@ -83,17 +83,17 @@ ZIO environment facility enables us to: Defining service in ZIO is not very different from object-oriented style, it has the same principle; coding to an interface, not an implementation. But the way ZIO encourages us to implement this principle by using _Module Pattern_ which doesn't very differ from the object-oriented style. ZIO have one data type that plays a key role in writing ZIO services using _Module Pattern_: -1. ZServiceBuilder +1. ZLayer So, before diving into the _Module Pattern_, We need to learn more about ZIO Contextual Data Types. Let's review each of them: -### ZServiceBuilder +### ZLayer -`ZServiceBuilder[-RIn, +E, +ROut]` is a recipe to build an environment of type `ROut`, starting from a value `RIn`, and possibly producing an error `E` during creation. +`ZLayer[-RIn, +E, +ROut]` is a recipe to build an environment of type `ROut`, starting from a value `RIn`, and possibly producing an error `E` during creation. -We can compose `serviceBuilderA` and `serviceBuilderB` _horizontally_ to build a service builder that has the requirements of both, to provide the capabilities of both, through `serviceBuilderA ++ serviceBuilderB` +We can compose `layerA` and `layerB` _horizontally_ to build a layer that has the requirements of both, to provide the capabilities of both, through `layerA ++ layerB` -We can also compose service builders _vertically_, meaning the output of one service builder is used as input for the subsequent service builder, resulting in one service builder with the requirement of the first, and the output of the second: `serviceBuilderA >>> serviceBuilderB`. When doing this, the first service builder must output all the services required by the second service builder, but we can defer creating some of these services and require them as part of the input of the final service builder using `ZServiceBuilder.identity`. +We can also compose layers _vertically_, meaning the output of one layer is used as input for the subsequent layer, resulting in one layer with the requirement of the first, and the output of the second: `layerA >>> layerB`. When doing this, the first layer must output all the services required by the second layer, but we can defer creating some of these services and require them as part of the input of the final layer using `ZLayer.identity`. ## Defining Services in OOP @@ -159,7 +159,7 @@ In the functional Scala as well as in object-oriented programming the best pract It is not mandatory but ZIO encourages us to follow this principle by bundling related functionality as an interface by using _Module Pattern_. -The core idea is that a service builder depends upon the interfaces exposed by the service builders immediately below itself, but is completely unaware of its dependencies' internal implementations. +The core idea is that a layer depends upon the interfaces exposed by the layers immediately below itself, but is completely unaware of its dependencies' internal implementations. In object-oriented programming: @@ -167,7 +167,7 @@ In object-oriented programming: - **Service Implementation** is done by implementing interfaces using _classes_ or creating _new object_ of the interface. - **Defining Dependencies** is done by using _constructors_. They allow us to build classes, give their dependencies. This is called constructor-based dependency injection. -We have a similar analogy in Module Pattern, except instead of using _constructors_ we use **`ZServiceBuilder`** to define dependencies. So in ZIO fashion, we can think of `ZServiceBuilder` as a service constructor. +We have a similar analogy in Module Pattern, except instead of using _constructors_ we use **`ZLayer`** to define dependencies. So in ZIO fashion, we can think of `ZLayer` as a service constructor. ZIO has two patterns to write services. The first version of _Module Pattern_ has some boilerplate, but the second version is very concise and straightforward. ZIO doesn't mandate any of them, you can use whichever you like. @@ -179,9 +179,9 @@ Let's start learning this pattern by writing a `Logging` service: 2. **Service Definition** — Then we create the `Logging` companion object. Inside the companion object, we define the service definition with a trait named `Service`. Traits are how we define services. A service could be all the stuff that is related to one concept with singular responsibility. -3. **Service Implementation** — After that, we implement our service by creating a new Service and then lifting that entire implementation into the `ZServiceBuilder` data type by using the `ZServiceBuilder.succeed` constructor. +3. **Service Implementation** — After that, we implement our service by creating a new Service and then lifting that entire implementation into the `ZLayer` data type by using the `ZLayer.succeed` constructor. -4. **Defining Dependencies** — If our service has a dependency on other services, we should use constructors like `ZServiceBuilder.fromService` and `ZServiceBuilder.fromServices`. +4. **Defining Dependencies** — If our service has a dependency on other services, we should use constructors like `ZLayer.fromService` and `ZLayer.fromServices`. 5. **Accessor Methods** — Finally, to create the API more ergonomic, it's better to write accessor methods for all of our service methods. @@ -193,7 +193,7 @@ import zio.Console._ ``` ```scala mdoc:invisible -import zio.{UIO, ServiceBuilder, ZServiceBuilder, ZIO, URIO} +import zio.{UIO, Layer, ZLayer, ZIO, URIO} ``` ```scala mdoc:silent:nest @@ -206,7 +206,7 @@ object logging { def log(line: String): UIO[Unit] } - val live: UServiceBuilder[Logging] = ZServiceBuilder.succeed { + val live: ULayer[Logging] = ZLayer.succeed { new Service { override def log(line: String): UIO[Unit] = ZIO.succeed(println(line)) @@ -220,7 +220,7 @@ object logging { } ``` -We might need `Console` and `Clock` services to implement the `Logging` service. In this case, we use `ZServiceBuilder.fromServices` constructor: +We might need `Console` and `Clock` services to implement the `Logging` service. In this case, we use `ZLayer.fromServices` constructor: ```scala mdoc:silent:nest:warn object logging { @@ -232,8 +232,8 @@ object logging { def log(line: String): UIO[Unit] } - val live: URServiceBuilder[Clock with Console, Logging] = - ZServiceBuilder.fromServices[Clock, Console, Logging.Service] { + val live: URLayer[Clock with Console, Logging] = + ZLayer.fromServices[Clock, Console, Logging.Service] { (clock: Clock, console: Console) => new Logging.Service { override def log(line: String): UIO[Unit] = @@ -271,7 +271,7 @@ During writing an application we don't care which implementation version of the Writing services with _Module Pattern 2.0_ is much easier than the previous one. It removes some level of indirection from the previous version, and much more similar to the object-oriented approach in writing services. -_Module Pattern 2.0_ has more similarity with object-oriented way of defining services. We use classes to implement services, and we use constructors to define service dependencies; At the end of the day, we lift class constructor into the `ZServiceBuilder`. +_Module Pattern 2.0_ has more similarity with object-oriented way of defining services. We use classes to implement services, and we use constructors to define service dependencies; At the end of the day, we lift class constructor into the `ZLayer`. 1. **Service Definition** — Defining service in this version has changed slightly compared to the previous version. We would take the service definition and pull it out into the top-level: @@ -314,12 +314,12 @@ case class LoggingLive(console: Console, clock: Clock) extends Logging { } ``` -4. **Defining ZServiceBuilder** — Now, we create a companion object for `LoggingLive` data type and lift the service implementation into the `ZServiceBuilder`: +4. **Defining ZLayer** — Now, we create a companion object for `LoggingLive` data type and lift the service implementation into the `ZLayer`: ```scala mdoc:silent object LoggingLive { - val serviceBuilder: URServiceBuilder[Console with Clock, Logging] = - (LoggingLive(_, _)).toServiceBuilder[Logging] + val layer: URLayer[Console with Clock, Logging] = + (LoggingLive(_, _)).toLayer[Logging] } ``` @@ -333,32 +333,32 @@ object Logging { That's it! Very simple! ZIO encourages us to follow some of the best practices in object-oriented programming. So it doesn't require us to throw away all our object-oriented knowledge. -Finally, we provide required service builders to our `app` effect: +Finally, we provide required layers to our `app` effect: ```scala mdoc:silent:nest import zio._ val app = Logging.log("Application Started") zio.Runtime.default.unsafeRun( - app.provide(LoggingLive.serviceBuilder) + app.provide(LoggingLive.layer) ) ``` ## Dependency Injection in ZIO -ZServiceBuilder combined with the ZIO environment, allow us to use ZIO for dependency injection. There are two parts for dependency injection: +ZLayer combined with the ZIO environment, allow us to use ZIO for dependency injection. There are two parts for dependency injection: 1. **Building Dependency Graph** 2. **Dependency Propagation** -ZIO has a full solution to the dependency injection problem. It solves the first problem by using compositional properties of `ZServiceBuilder`, and solves the second by using ZIO Environment facilities like `ZIO#provide`. +ZIO has a full solution to the dependency injection problem. It solves the first problem by using compositional properties of `ZLayer`, and solves the second by using ZIO Environment facilities like `ZIO#provide`. The way ZIO manages dependencies between application components gives us extreme power in terms of compositionality and offering the capability to easily change different implementations. This is particularly useful during _testing_ and _mocking_. -By using ZServiceBuilder and ZIO Environment we can solve the propagation and wire-up problems in dependency injection. But it doesn't necessary to use it, we can still use things like [Guice](https://github.com/google/guice) with ZIO, or we might like to use [izumi distage](https://izumi.7mind.io/distage/index.html) solution for dependency injection. +By using ZLayer and ZIO Environment we can solve the propagation and wire-up problems in dependency injection. But it doesn't necessary to use it, we can still use things like [Guice](https://github.com/google/guice) with ZIO, or we might like to use [izumi distage](https://izumi.7mind.io/distage/index.html) solution for dependency injection. ### Building Dependency Graph -Assume we have several services with their dependencies, and we need a way to compose and wiring up these dependencies and create the dependency graph of our application. `ZServiceBuilder` is a ZIO solution for this problem, it allows us to build up the whole application dependency graph by composing service builders horizontally and vertically. More information about how to compose service builders is on the [ZServiceBuilder](zservicebuilder.md) page. +Assume we have several services with their dependencies, and we need a way to compose and wiring up these dependencies and create the dependency graph of our application. `ZLayer` is a ZIO solution for this problem, it allows us to build up the whole application dependency graph by composing layers horizontally and vertically. More information about how to compose layers is on the [ZLayer](zlayer.md) page. ### Dependency Propagation @@ -415,11 +415,11 @@ val loggingImpl = new Logging { val effect = app.provideEnvironment(ZEnvironment(loggingImpl)) ``` -Most of the time, we don't use `Has` directly to implement our services, instead; we use `ZServiceBuilder` to construct the dependency graph of our application, then we use methods like `ZIO#provide` to propagate dependencies into the environment of our ZIO effect. +Most of the time, we don't use `Has` directly to implement our services, instead; we use `ZLayer` to construct the dependency graph of our application, then we use methods like `ZIO#provide` to propagate dependencies into the environment of our ZIO effect. #### Using `provide` Method -Unlike the `ZIO#provideEnvironment` which takes a `ZEnvironment[R]`, the `ZIO#provide` takes a `ZServiceBuilder` to the ZIO effect and translates it to another level. +Unlike the `ZIO#provideEnvironment` which takes a `ZEnvironment[R]`, the `ZIO#provide` takes a `ZLayer` to the ZIO effect and translates it to another level. Assume we have written this piece of program that requires Clock and Console services: @@ -447,7 +447,7 @@ As we see, the type of our effect converted from `ZIO[Random with Console with C #### Using `provideSome` Method -Sometimes we have written a program, and we don't want to provide all its requirements. In these cases, we can use `ZIO#provideSome` to partially apply some service builders to the `ZIO` effect. +Sometimes we have written a program, and we don't want to provide all its requirements. In these cases, we can use `ZIO#provideSome` to partially apply some layers to the `ZIO` effect. In the previous example, if we just want to provide the `Console`, we should use `ZIO#provideSome`: @@ -466,7 +466,7 @@ val mainEffect: ZIO[Random with Clock, Nothing, Unit] = Sometimes we have written a program that contains ZIO built-in services and some other services that are not part of `ZEnv`. - As `ZEnv` provides us the implementation of built-in services, we just need to provide service builders for those services that are not part of the `ZEnv`. + As `ZEnv` provides us the implementation of built-in services, we just need to provide layers for those services that are not part of the `ZEnv`. `ZIO#provideCustom` helps us to do so and returns an effect that only depends on `ZEnv`. @@ -488,7 +488,7 @@ object Logging { } object LoggingLive { - val serviceBuilder: UServiceBuilder[Logging] = ZServiceBuilder.succeed { + val layer: ULayer[Logging] = ZLayer.succeed { new Logging { override def log(str: String): UIO[Unit] = ??? } @@ -504,8 +504,8 @@ val myApp: ZIO[Logging with Console with Clock, Nothing, Unit] = for { This program uses two ZIO built-in services, `Console` and `Clock`. We don't need to provide `Console` and `Clock` manually, to reduce some boilerplate, we use `ZEnv` to satisfy some common base requirements. -By using `ZIO#provideCustom` we only provide the `Logging` service builder, and it returns a `ZIO` effect which only requires `ZEnv`: +By using `ZIO#provideCustom` we only provide the `Logging` layer, and it returns a `ZIO` effect which only requires `ZEnv`: ```scala mdoc:silent -val mainEffect: ZIO[ZEnv, Nothing, Unit] = myApp.provideCustom(LoggingLive.serviceBuilder) +val mainEffect: ZIO[ZEnv, Nothing, Unit] = myApp.provideCustom(LoggingLive.layer) ``` diff --git a/docs/datatypes/contextual/layer.md b/docs/datatypes/contextual/layer.md new file mode 100644 index 000000000000..a92b8b2ca510 --- /dev/null +++ b/docs/datatypes/contextual/layer.md @@ -0,0 +1,10 @@ +--- +id: layer +title: "Layer" +--- + +`Layer[+E, +ROut]` is a type alias for `ZLayer[Any, E, ROut]`, which represents a layer that doesn't require any services, it may fail with an error type of `E`, and returns `ROut` as its output. + +```scala +type Layer[+E, +ROut] = ZLayer[Any, E, ROut] +``` diff --git a/docs/datatypes/contextual/rlayer.md b/docs/datatypes/contextual/rlayer.md new file mode 100644 index 000000000000..a97431975c53 --- /dev/null +++ b/docs/datatypes/contextual/rlayer.md @@ -0,0 +1,10 @@ +--- +id: rlayer +title: "RLayer" +--- + +`RLayer[-RIn, +ROut]` is a type alias for `ZLayer[RIn, Throwable, ROut]`, which represents a layer that requires `RIn` as its input, it may fail with `Throwable` value, or returns `ROut` as its output. + +```scala +type RLayer[-RIn, +ROut] = ZLayer[RIn, Throwable, ROut] +``` \ No newline at end of file diff --git a/docs/datatypes/contextual/rservicebuilder.md b/docs/datatypes/contextual/rservicebuilder.md deleted file mode 100644 index 36d42945bd04..000000000000 --- a/docs/datatypes/contextual/rservicebuilder.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -id: rservicebuilder -title: "RServiceBuilder" ---- - -`RServiceBuilder[-RIn, +ROut]` is a type alias for `ZServiceBuilder[RIn, Throwable, ROut]`, which represents a service builder that requires `RIn` as its input, it may fail with `Throwable` value, or returns `ROut` as its output. - -```scala -type RServiceBuilder[-RIn, +ROut] = ZServiceBuilder[RIn, Throwable, ROut] -``` \ No newline at end of file diff --git a/docs/datatypes/contextual/servicebuilder.md b/docs/datatypes/contextual/servicebuilder.md deleted file mode 100644 index 6434de0fc422..000000000000 --- a/docs/datatypes/contextual/servicebuilder.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -id: servicebuilder -title: "ServiceBuilder" ---- - -`ServiceBuilder[+E, +ROut]` is a type alias for `ZServiceBuilder[Any, E, ROut]`, which represents a service builder that doesn't require any services, it may fail with an error type of `E`, and returns `ROut` as its output. - -```scala -type ServiceBuilder[+E, +ROut] = ZServiceBuilder[Any, E, ROut] -``` diff --git a/docs/datatypes/contextual/task-layer.md b/docs/datatypes/contextual/task-layer.md new file mode 100644 index 000000000000..a8655e4762a2 --- /dev/null +++ b/docs/datatypes/contextual/task-layer.md @@ -0,0 +1,10 @@ +--- +id: tasklayer +title: "TaskLayer" +--- + +`TaskLayer[+ROut]` is a type alias for `ZLayer[Any, Throwable, ROut]`, which represents a layer that doesn't require any services as its input, it may fail with `Throwable` value, and returns `ROut` as its output. + +```scala +type TaskLayer[+ROut] = ZLayer[Any, Throwable, ROut] +``` diff --git a/docs/datatypes/contextual/task-servicebuilder.md b/docs/datatypes/contextual/task-servicebuilder.md deleted file mode 100644 index 7dcb6e5c72ba..000000000000 --- a/docs/datatypes/contextual/task-servicebuilder.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -id: taskservicebuilder -title: "TaskServiceBuilder" ---- - -`TaskServiceBuilder[+ROut]` is a type alias for `ZServiceBuilder[Any, Throwable, ROut]`, which represents a service builder that doesn't require any services as its input, it may fail with `Throwable` value, and returns `ROut` as its output. - -```scala -type TaskServiceBuilder[+ROut] = ZServiceBuilder[Any, Throwable, ROut] -``` diff --git a/docs/datatypes/contextual/ulayer.md b/docs/datatypes/contextual/ulayer.md new file mode 100644 index 000000000000..ad0e6e79a1ca --- /dev/null +++ b/docs/datatypes/contextual/ulayer.md @@ -0,0 +1,10 @@ +--- +id: ulayer +title: "ULayer" +--- + +`ULayer[+ROut]` is a type alias for `ZLayer[Any, Nothing, ROut]`, which represents a layer that doesn't require any services as its input, it can't fail, and returns `ROut` as its output. + +```scala +type ULayer[+ROut] = ZLayer[Any, Nothing, ROut] +``` diff --git a/docs/datatypes/contextual/urlayer.md b/docs/datatypes/contextual/urlayer.md new file mode 100644 index 000000000000..9705223beacf --- /dev/null +++ b/docs/datatypes/contextual/urlayer.md @@ -0,0 +1,10 @@ +--- +id: urlayer +title: "URLayer" +--- + +`URLayer[-RIn, +ROut]` is a type alias for `ZLayer[RIn, Nothing, ROut]`, which represents a layer that requires `RIn` as its input, it can't fail, and returns `ROut` as its output. + +```scala +type URLayer[-RIn, +ROut] = ZLayer[RIn, Nothing, ROut] +``` diff --git a/docs/datatypes/contextual/urservicebuilder.md b/docs/datatypes/contextual/urservicebuilder.md deleted file mode 100644 index 2e804587f00a..000000000000 --- a/docs/datatypes/contextual/urservicebuilder.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -id: urservicebuilder -title: "URServiceBuilder" ---- - -`URServiceBuilder[-RIn, +ROut]` is a type alias for `ZServiceBuilder[RIn, Nothing, ROut]`, which represents a service builder that requires `RIn` as its input, it can't fail, and returns `ROut` as its output. - -```scala -type URServiceBuilder[-RIn, +ROut] = ZServiceBuilder[RIn, Nothing, ROut] -``` diff --git a/docs/datatypes/contextual/uservicebuilder.md b/docs/datatypes/contextual/uservicebuilder.md deleted file mode 100644 index 1398ee0878ae..000000000000 --- a/docs/datatypes/contextual/uservicebuilder.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -id: uservicebuilder -title: "UServiceBuilder" ---- - -`UServiceBuilder[+ROut]` is a type alias for `ZServiceBuilder[Any, Nothing, ROut]`, which represents a service builder that doesn't require any services as its input, it can't fail, and returns `ROut` as its output. - -```scala -type UServiceBuilder[+ROut] = ZServiceBuilder[Any, Nothing, ROut] -``` diff --git a/docs/datatypes/contextual/zlayer.md b/docs/datatypes/contextual/zlayer.md new file mode 100644 index 000000000000..58da273e47bc --- /dev/null +++ b/docs/datatypes/contextual/zlayer.md @@ -0,0 +1,713 @@ +--- +id: zlayer +title: "ZLayer" +--- + +A `ZLayer[-RIn, +E, +ROut]` describes a layer of an application: every layer in an application requires some services as input `RIn` and produces some services as the output `ROut`. + +Layers are: + +1. **Recipes for Creating Services** — They describe how a given dependencies produces another services. For example, the `ZLayer[Logging with Database, Throwable, UserRepo]` is a recipe for building a service that requires `Logging` and `Database` service, and it produces a `UserRepo` service. + +2. **An Alternative to Constructors** — We can think of `ZLayer` as a more powerful version of a constructor, it is an alternative way to represent a constructor. Like a constructor, it allows us to build the `ROut` service in terms of its dependencies (`RIn`). + +3. **Composable** — Because of their excellent **composition properties**, layers are the idiomatic way in ZIO to create services that depend on other services. We can define layers that are relying on each other. + +4. **Effectful and Resourceful** — The construction of ZIO layers can be effectful and resourceful, they can be acquired and safely released when the services are done being utilized. + +5. **Asynchronous** — Unlike class constructors which are blocking, ZLayer is fully asynchronous and non-blocking. + +For example, a `ZLayer[Blocking with Logging, Throwable, Database]` can be thought of as a function that map `Blocking` and `Logging` services into `Database` service: + +```scala +(Blocking, Logging) => Database +``` + +So we can say that the `Database` service has two dependencies: `Blocking` and `Logging` services. + +Let's see how we can create a layer: + +## Creation + +`ZLayer` is an **alternative to a class constructor**, a recipe to create a service. This recipe may contain the following information: + +1. **Dependencies** — To create a service, we need to indicate what other service we are depending on. For example, a `Database` service might need `Socket` and `Blocking` services to perform its operations. + +2. **Acquisition/Release Action** — It may contain how to initialize a service. For example, if we are creating a recipe for a `Database` service, we should provide how the `Database` will be initialized, via acquisition action. Also, it may contain how to release a service. For example, how the `Database` releases its connection pools. + +In some cases, a `ZLayer` may not have any dependencies or requirements from the environment. In this case, we can specify `Any` for the `RIn` type parameter. The `Layer` type alias provided by ZIO is a convenient way to define a layer without requirements. + +There are many ways to create a ZLayer. Here's an incomplete list: + - `ZLayer.succeed` to create a layer from an existing service + - `ZLayer.succeedMany` to create a layer from a value that's one or more services + - `ZLayer.fromFunction` to create a layer from a function from the requirement to the service + - `ZLayer.fromEffect` to lift a `ZIO` effect to a layer requiring the effect environment + - `ZLayer.fromAcquireRelease` for a layer based on resource acquisition/release. The idea is the same as `ZManaged`. + - `ZLayer.fromService` to build a layer from a service + - `ZLayer.fromServices` to build a layer from a number of required services + - `ZLayer.identity` to express the requirement for a dependency + - `ZIO#toLayer` or `ZManaged#toLayer` to construct a layer from an effect + +Where it makes sense, these methods have also variants to build a service effectfully (suffixed by `ZIO`), resourcefully (suffixed by `Managed`), or to create a combination of services (suffixed by `Many`). + +Let's review some of the `ZLayer`'s most useful constructors: + +### From Simple Values + +With `ZLayer.succeed` we can construct a `ZLayer` from a value. It returns a `ULayer[A]` value, which represents a layer of an application that _has_ a service of type `A`: + +```scala +def succeed[A: Tag](a: A): ULayer[A] +``` + +In the following example, we are going to create a `nameLayer` that provides us the name of `Adam`. + +```scala mdoc:invisible +import zio._ +``` + +```scala mdoc:silent +val nameLayer: ULayer[String] = ZLayer.succeed("Adam") +``` + +In most cases, we use `ZLayer.succeed` to create a layer of type `A`. + +For example, assume we have written the following service: + +```scala mdoc:silent +object terminal { + type Terminal = Terminal.Service + + object Terminal { + trait Service { + def printLine(line: String): UIO[Unit] + } + + object Service { + val live: Service = new Service { + override def printLine(line: String): UIO[Unit] = + ZIO.succeed(println(line)) + } + } + } +} +``` + +Now we can create a `ZLayer` from the `live` version of this service: + +```scala mdoc:silent +import terminal._ +val live: ZLayer[Any, Nothing, Terminal] = ZLayer.succeed(Terminal.Service.live) +``` + +### From Managed Resources + +Some components of our applications need to be managed, meaning they undergo a resource acquisition phase before usage, and a resource release phase after usage (e.g. when the application shuts down). + +Fortunately, the construction of ZIO layers can be effectful and resourceful, this means they can be acquired and safely released when the services are done being utilized. + +`ZLayer` relies on the powerful `ZManaged` data type and this makes this process extremely simple. + +We can lift any `ZManaged` to `ZLayer` by providing a managed resource to the `ZIO.fromManaged` constructor: + +```scala mdoc:invisible +import scala.io.BufferedSource +``` + +```scala mdoc:silent:nest +val managedFile = ZManaged.fromAutoCloseable( + ZIO.attempt(scala.io.Source.fromFile("file.txt")) +) +val fileLayer: ZLayer[Any, Throwable, BufferedSource] = + ZLayer.fromManaged(managedFile) +``` + +Also, every `ZManaged` can be converted to `ZLayer` by calling `ZLayer#toLayer`: + +```scala mdoc:silent:nest +val fileLayer: ZLayer[Any, Throwable, BufferedSource] = managedFile.toLayer +``` + +Let's see another real-world example of creating a layer from managed resources. Assume we have written a managed `UserRepository`: + +```scala mdoc:invisible:reset +import zio._ +import zio.Console._ +import scala.io.Source._ +import java.io.{FileInputStream, FileOutputStream, Closeable} + +trait DBConfig +trait Transactor + +def dbConfig: Task[DBConfig] = Task.attempt(???) +def initializeDb(config: DBConfig): Task[Unit] = Task.attempt(???) +def makeTransactor(config: DBConfig): ZManaged[Any, Throwable, Transactor] = ??? + +case class UserRepository(xa: Transactor) +object UserRepository { + def apply(xa: Transactor): UserRepository = new UserRepository(xa) +} +``` + +```scala mdoc:silent:nest +def userRepository: ZManaged[Console, Throwable, UserRepository] = for { + cfg <- dbConfig.toManaged + _ <- initializeDb(cfg).toManaged + xa <- makeTransactor(cfg) +} yield new UserRepository(xa) +``` + +We can convert that to `ZLayer` with `ZLayer.fromManaged` or `ZManaged#toLayer`: + +```scala mdoc:nest +val usersLayer = userRepository.toLayer +val usersLayer_ = ZLayer.fromManaged(userRepository) +``` + +Also, we can create a `ZLayer` directly from `acquire` and `release` actions of a managed resource: + +```scala mdoc:nest +def acquire = ZIO.attempt(new FileInputStream("file.txt")) +def release(resource: Closeable) = ZIO.succeed(resource.close()) + +val inputStreamLayer = ZLayer.fromAcquireRelease(acquire)(release) +``` + +### From ZIO Effects + +We can create `ZLayer` from any `ZIO` effect by using `ZLayer.fromEffect` constructor, or calling `ZIO#toLayer` method: + +```scala mdoc +val layer = ZLayer.fromZIO(ZIO.succeed("Hello, World!")) +val layer_ = ZIO.succeed("Hello, World!").toLayer +``` + +Assume we have a `ZIO` effect that read the application config from a file, we can create a layer from that: + +```scala mdoc:invisible +trait AppConfig +``` + +```scala mdoc:nest +def loadConfig: Task[AppConfig] = Task.attempt(???) +val configLayer = ZLayer.fromZIO(loadConfig) +``` + +### From another Service + +Every `ZLayer` describes an application that requires some services as input and produces some services as output. Sometimes when we are creating a layer, we may need to access and depend on one or several services. + +The `ZLayer.fromService` construct a layer that purely depends on the specified service: + +```scala +def fromService[A: Tag, B: Tag](f: A => B): ZLayer[A, Nothing, B] +``` + +Assume we want to write a `live` version of the following logging service: + +```scala mdoc:silent:nest +object logging { + type Logging = Logging.Service + + object Logging { + trait Service { + def log(msg: String): UIO[Unit] + } + } +} +``` + +We can create that by using `ZLayer.fromService` constructor, which depends on `Console` service: + +```scala mdoc:invisible +import logging.Logging +import logging.Logging._ +``` + +```scala mdoc:silent:nest:warn +val live: ZLayer[Console, Nothing, Logging] = ZLayer.fromService(console => + new Service { + override def log(msg: String): UIO[Unit] = console.printLine(msg).orDie + } +) +``` + +## Vertical and Horizontal Composition + +We said that we can think of the `ZLayer` as a more powerful _constructor_. Constructors are not composable, because they are not values. While a constructor is not composable, `ZLayer` has a nice facility to compose with other `ZLayer`s. So we can say that a `ZLayer` turns a constructor into values. + +`ZLayer`s can be composed together horizontally or vertically: + +1. **Horizontal Composition** — They can be composed together horizontally with the `++` operator. When we compose layers horizontally, the new layer requires all the services that both of them require and produces all services that both of them produce. Horizontal composition is a way of composing two layers side-by-side. It is useful when we combine two layers that they don't have any relationship with each other. + +2. **Vertical Composition** — If we have a layer that requires `A` and produces `B`, we can compose this with another layer that requires `B` and produces `C`; this composition produces a layer that requires `A` and produces `C`. The feed operator, `>>>`, stack them on top of each other by using vertical composition. This sort of composition is like _function composition_, feeding an output of one layer to an input of another. + +Let's get into an example, assume we have these services with their implementations: + +```scala mdoc:invisible:reset +import zio._ +``` + +```scala mdoc:silent:nest +trait Logging { } +trait Database { } +trait BlobStorage { } +trait UserRepo { } +trait DocRepo { } + +case class LoggerImpl(console: Console) extends Logging { } +case object DatabaseImp extends Database { } +case class UserRepoImpl(logging: Logging, database: Database) extends UserRepo { } +case class BlobStorageImpl(logging: Logging) extends BlobStorage { } +case class DocRepoImpl(logging: Logging, database: Database, blobStorage: BlobStorage) extends DocRepo { } +``` + +We can't compose these services together, because their constructors are not value. `ZLayer` can convert these services into values, then we can compose them together. + +Let's assume we have lifted these services into `ZLayer`s: + +```scala mdoc:silent +val logging: URLayer[Console, Logging] = + (LoggerImpl.apply _).toLayer +val database: URLayer[Any, Database] = + ZLayer.succeed(DatabaseImp) +val userRepo: URLayer[Logging with Database, UserRepo] = + (UserRepoImpl(_, _)).toLayer +val blobStorage: URLayer[Logging, BlobStorage] = + (BlobStorageImpl(_)).toLayer +val docRepo: URLayer[Logging with Database with BlobStorage, DocRepo] = + (DocRepoImpl(_, _, _)).toLayer +``` + +Now, we can compose logging and database horizontally: + +```scala mdoc:silent +val newLayer: ZLayer[Console, Throwable, Logging with Database] = logging ++ database +``` + +And then we can compose the `newLayer` with `userRepo` vertically: + +```scala mdoc:silent +val myLayer: ZLayer[Console, Throwable, UserRepo] = newLayer >>> userRepo +``` + +## Service Builder Memoization + +One important feature of `ZIO` layers is that **they are shared by default**, meaning that if the same layer is used twice, the layer will only be allocated a single time. + +For every layer in our dependency graph, there is only one instance of it that is shared between all the layers that depend on it. + +If we don't want to share a module, we should create a fresh, non-shared version of it through `ZLayer#fresh`. + +## Updating Local Dependencies + +```scala mdoc:invisible:reset +import zio._ + +trait DBError +trait Product +trait ProductId +trait DBConnection +case class User(id: UserId, name: String) +case class UserId(value: Long) + + +type UserRepo = UserRepo.Service + +object UserRepo { + trait Service { + def getUser(userId: UserId): IO[DBError, Option[User]] + def createUser(user: User): IO[DBError, Unit] + } + + // This simple in-memory version has no dependencies. + // This could be useful for tests where you don't want the additional + // complexity of having to manage DB Connections. + val inMemory: Layer[Nothing, UserRepo] = ZLayer.succeed( + new Service { + def getUser(userId: UserId): IO[DBError, Option[User]] = UIO(???) + def createUser(user: User): IO[DBError, Unit] = UIO(???) + } + ) + + //accessor methods + def getUser(userId: UserId): ZIO[UserRepo, DBError, Option[User]] = + ZIO.serviceWithZIO(_.getUser(userId)) + + def createUser(user: User): ZIO[UserRepo, DBError, Unit] = + ZIO.serviceWithZIO(_.createUser(user)) +} + + +type Logging = Logging.Service + +object Logging { + trait Service { + def info(s: String): UIO[Unit] + def error(s: String): UIO[Unit] + } + + val consoleLogger: ZLayer[Console, Nothing, Logging] = ZLayer.fromFunction( environment => + new Service { + def info(s: String): UIO[Unit] = environment.get.printLine(s"info - $s").orDie + def error(s: String): UIO[Unit] = environment.get.printLine(s"error - $s").orDie + } + ) + + //accessor methods + def info(s: String): URIO[Logging, Unit] = + ZIO.serviceWithZIO(_.info(s)) + + def error(s: String): URIO[Logging, Unit] = + ZIO.serviceWithZIO(_.error(s)) +} + + + +import java.sql.Connection +def makeConnection: UIO[Connection] = UIO(???) +val connectionLayer: Layer[Nothing, Connection] = + ZLayer.fromAcquireRelease(makeConnection)(c => UIO(c.close())) +val postgresLayer: ZLayer[Connection, Nothing, UserRepo] = + ZLayer.fromFunction { environment: ZEnvironment[Connection] => + new UserRepo.Service { + override def getUser(userId: UserId): IO[DBError, Option[User]] = UIO(???) + override def createUser(user: User): IO[DBError, Unit] = UIO(???) + } + } + +val fullRepo: Layer[Nothing, UserRepo] = connectionLayer >>> postgresLayer + + + +val user2: User = User(UserId(123), "Tommy") +val makeUser: ZIO[Logging with UserRepo, DBError, Unit] = for { + _ <- Logging.info(s"inserting user") // URIO[Logging, Unit] + _ <- UserRepo.createUser(user2) // ZIO[UserRepo, DBError, Unit] + _ <- Logging.info(s"user inserted") // URIO[Logging, Unit] +} yield () + + +// compose horizontally +val horizontal: ZLayer[Console, Nothing, Logging with UserRepo] = Logging.consoleLogger ++ UserRepo.inMemory + +// fulfill missing services, composing vertically +val fullLayer: Layer[Nothing, Logging with UserRepo] = Console.live >>> horizontal + +// provide the services to the program +makeUser.provideSome(fullLayer) +``` + +Given a layer, it is possible to update one or more components it provides. We update a dependency in two ways: + +1. **Using the `update` Method** — This method allows us to replace one requirement with a different implementation: + +```scala mdoc:silent:nest +val withPostgresService = horizontal.update[UserRepo.Service]{ oldRepo => new UserRepo.Service { + override def getUser(userId: UserId): IO[DBError, Option[User]] = UIO(???) + override def createUser(user: User): IO[DBError, Unit] = UIO(???) + } + } +``` + +2. **Using Horizontal Composition** — Another way to update a requirement is to horizontally compose in a layer that provides the updated service. The resulting composition will replace the old layer with the new one: + +```scala mdoc:silent:nest +val dbLayer: Layer[Nothing, UserRepo] = ZLayer.succeed(new UserRepo.Service { + override def getUser(userId: UserId): IO[DBError, Option[User]] = ??? + override def createUser(user: User): IO[DBError, Unit] = ??? + }) + +val updatedHorizontal2 = horizontal ++ dbLayer +``` + +## Hidden Versus Passed Through Dependencies + +One design decision regarding building dependency graphs is whether to hide or pass through the upstream dependencies of a service. `ZLayer` defaults to hidden dependencies but makes it easy to pass through dependencies as well. + +To illustrate this, consider the Postgres-based repository discussed above: + +```scala mdoc:silent:nest +val connection: ZLayer[Any, Nothing, Connection] = connectionLayer +val userRepo: ZLayer[Connection, Nothing, UserRepo] = postgresLayer +val layer: ZLayer[Any, Nothing, UserRepo] = connection >>> userRepo +``` + +Notice that in `layer`, the dependency `UserRepo` has on `Connection` has been "hidden", and is no longer expressed in the type signature. From the perspective of a caller, `layer` just outputs a `UserRepo` and requires no inputs. The caller does not need to be concerned with the internal implementation details of how the `UserRepo` is constructed. + +To provide only some inputs, we need to explicitly define what inputs still need to be provided: + +```scala mdoc:silent:nest +trait Configuration + +val userRepoWithConfig: ZLayer[Configuration with Connection, Nothing, UserRepo] = + ZLayer.succeed(new Configuration{}) ++ postgresLayer +val partialLayer: ZLayer[Configuration, Nothing, UserRepo] = + (ZLayer.environment[Configuration] ++ connection) >>> userRepoWithConfig +``` + +In this example the requirement for a `Connection` has been satisfied, but `Configuration` is still required by `partialLayer`. + +This achieves an encapsulation of services and can make it easier to refactor code. For example, say we want to refactor our application to use an in-memory database: + +```scala mdoc:silent:nest +val updatedLayer: ZLayer[Any, Nothing, UserRepo] = dbLayer +``` + +No other code will need to be changed, because the previous implementation's dependency upon a `Connection` was hidden from users, and so they were not able to rely on it. + +However, if an upstream dependency is used by many other services, it can be convenient to "pass through" that dependency, and include it in the output of a layer. This can be done with the `>+>` operator, which provides the output of one layer to another layer, returning a new layer that outputs the services of _both_. + + +```scala mdoc:silent:nest +val layer: ZLayer[Any, Nothing, Connection with UserRepo] = connection >+> userRepo +``` + +Here, the `Connection` dependency has been passed through, and is available to all downstream services. This allows a style of composition where the `>+>` operator is used to build a progressively larger set of services, with each new service able to depend on all the services before it. + +```scala mdoc:invisible +type Baker = Baker.Service +type Ingredients = Ingredients.Service +type Oven = Oven.Service +type Dough = Dough.Service +type Cake = Cake.Service + +object Baker { + trait Service +} + +object Ingredients { + trait Service +} + +object Oven { + trait Service +} + +object Dough { + trait Service +} + +object Cake { + trait Service +} +``` + +```scala mdoc +lazy val baker: ZLayer[Any, Nothing, Baker] = ??? +lazy val ingredients: ZLayer[Any, Nothing, Ingredients] = ??? +lazy val oven: ZLayer[Any, Nothing, Oven] = ??? +lazy val dough: ZLayer[Baker with Ingredients, Nothing, Dough] = ??? +lazy val cake: ZLayer[Baker with Oven with Dough, Nothing, Cake] = ??? + +lazy val all: ZLayer[Any, Nothing, Baker with Ingredients with Oven with Dough with Cake] = + baker >+> // Baker + ingredients >+> // Baker with Ingredients + oven >+> // Baker with Ingredients with Oven + dough >+> // Baker with Ingredients with Oven with Dough + cake // Baker with Ingredients with Oven with Dough with Cake +``` + +`ZLayer` makes it easy to mix and match these styles. If you pass through dependencies and later want to hide them you can do so through a simple type ascription: + +```scala mdoc:silent +lazy val hidden: ZLayer[Any, Nothing, Cake] = all +``` + +And if you do build your dependency graph more explicitly, you can be confident that dependencies used in multiple parts of the dependency graph will only be created once due to memoization and sharing. + +## Cyclic Dependencies + +The `ZLayer` mechanism makes it impossible to build cyclic dependencies, making the initialization process very linear, by construction. + +## Asynchronous Service Construction + +Another important note about `ZLayer` is that, unlike constructors which are synchronous, `ZLayer` is _asynchronous_. Constructors in classes are always synchronous. This is a drawback for non-blocking applications. Because sometimes we might want to use something that is blocking the inside constructor. + +For example, when we are constructing some sort of Kafka streaming service, we might want to connect to the Kafka cluster in the constructor of our service, which takes some time. So that wouldn't be a good idea to blocking inside a constructor. There are some workarounds for fixing this issue, but they are not perfect as the ZIO solution. + +Well, with ZIO ZLayer, our constructor could be asynchronous, and they also can block definitely. And that is because `ZLayer` has the full power of ZIO. And as a result, we have strictly more power on our constructors with ZLayer. + +We can acquire resources asynchronously or in a blocking fashion, and spend some time doing that, and we don't need to worry about it. That is not an anti-pattern. This is the best practice with ZIO. + +## Examples + +### The simplest ZLayer application + +This application demonstrates a ZIO program with a single dependency on a simple string value: + +```scala mdoc:compile-only +import zio._ + +object Example extends ZIOAppDefault { + + // Define our simple ZIO program + val zio: ZIO[String, Nothing, Unit] = for { + name <- ZIO.service[String] + _ <- UIO(println(s"Hello, $name!")) + } yield () + + // Create a ZLayer that produces a string and can be used to satisfy a string + // dependency that the program has + val nameLayer: ULayer[String] = ZLayer.succeed("Adam") + + // Run the program, providing the `nameLayer` + def run = zio.provideSome(nameLayer) +} + +``` + +### ZLayer application with dependencies + +In the following example, our ZIO application has several dependencies: + - `zio.Clock` + - `zio.Console` + - `ModuleB` + +`ModuleB` in turn depends upon `ModuleA`: + +```scala +import zio._ +import zio.Clock._ +import zio.Console._ +import java.io.IOException + +object moduleA { + type ModuleA = ModuleA.Service + + object ModuleA { + trait Service { + def letsGoA(v: Int): UIO[String] + } + + val any: ZLayer[ModuleA, Nothing, ModuleA] = + ZLayer.requires[ModuleA] + + val live: Layer[Nothing, Service] = ZLayer.succeed { + new Service { + def letsGoA(v: Int): UIO[String] = UIO(s"done: v = $v ") + } + } + } + + def letsGoA(v: Int): URIO[ModuleA, String] = + ZIO.serviceWithZIO(_.letsGoA(v)) +} + +import moduleA._ + +object moduleB { + type ModuleB = ModuleB.Service + + object ModuleB { + trait Service { + def letsGoB(v: Int): UIO[String] + } + + val any: ZLayer[ModuleB, Nothing, ModuleB] = + ZLayer.requires[ModuleB] + + val live: ZLayer[ModuleA, Nothing, ModuleB] = ZLayer.fromService { (moduleA: ModuleA.Service) => + new Service { + def letsGoB(v: Int): UIO[String] = + moduleA.letsGoA(v) + } + } + } + + def letsGoB(v: Int): URIO[ModuleB, String] = + ZIO.serviceWithZIO(_.letsGoB(v)) +} + +object ZLayerApp0 extends zio.App { + + import moduleB._ + + val env = Console.live ++ Clock.live ++ (ModuleA.live >>> ModuleB.live) + val program: ZIO[Console with Clock with moduleB.ModuleB, IOException, Unit] = + for { + _ <- printLine(s"Welcome to ZIO!") + _ <- sleep(1.second) + r <- letsGoB(10) + _ <- printLine(r) + } yield () + + def run(args: List[String]) = + program.provideSome(env).exitCode + +} + +// output: +// [info] running ZLayerApp +// Welcome to ZIO! +// done: v = 10 +``` + +### ZLayer example with complex dependencies + +In this example, we can see that `ModuleC` depends upon `ModuleA`, `ModuleB`, and `Clock`. The layer provided to the runnable application shows how dependency layers can be combined using `++` into a single combined layer. The combined layer will then be able to produce both of the outputs of the original sets as a single layer: + +```scala mdoc:compile-only +import zio._ +import zio.Clock._ + +object ZLayerApp1 extends scala.App { + val rt = Runtime.default + + type ModuleA = ModuleA.Service + + object ModuleA { + + trait Service {} + + val any: ZLayer[ModuleA, Nothing, ModuleA] = + ZLayer.environment[ModuleA] + + val live: ZLayer[Any, Nothing, ModuleA] = + ZLayer.succeed(new Service {}) + } + + type ModuleB = ModuleB.Service + + object ModuleB { + + trait Service {} + + val any: ZLayer[ModuleB, Nothing, ModuleB] = + ZLayer.environment[ModuleB] + + val live: ZLayer[Any, Nothing, ModuleB] = + ZLayer.succeed(new Service {}) + } + + type ModuleC = ModuleC.Service + + object ModuleC { + + trait Service { + def foo: UIO[Int] + } + + val any: ZLayer[ModuleC, Nothing, ModuleC] = + ZLayer.environment[ModuleC] + + val live: ZLayer[ModuleA with ModuleB with Clock, Nothing, ModuleC] = + ZLayer.succeed { + new Service { + val foo: UIO[Int] = UIO.succeed(42) + } + } + + val foo: URIO[ModuleC, Int] = + ZIO.serviceWithZIO(_.foo) + } + + val env = (ModuleA.live ++ ModuleB.live ++ ZLayer.environment[Clock]) >>> ModuleC.live + + val res = ModuleC.foo.provideCustom(env) + + val out = rt.unsafeRun(res) + println(out) + // 42 +} +``` diff --git a/docs/datatypes/contextual/zservicebuilder.md b/docs/datatypes/contextual/zservicebuilder.md deleted file mode 100644 index e6581e57ffbc..000000000000 --- a/docs/datatypes/contextual/zservicebuilder.md +++ /dev/null @@ -1,713 +0,0 @@ ---- -id: zservicebuilder -title: "ZServiceBuilder" ---- - -A `ZServiceBuilder[-RIn, +E, +ROut]` describes a service builder of an application: every service builder in an application requires some services as input `RIn` and produces some services as the output `ROut`. - -Service builders are: - -1. **Recipes for Creating Services** — They describe how a given dependencies produces another services. For example, the `ZServiceBuilder[Logging with Database, Throwable, UserRepo]` is a recipe for building a service that requires `Logging` and `Database` service, and it produces a `UserRepo` service. - -2. **An Alternative to Constructors** — We can think of `ZServiceBuilder` as a more powerful version of a constructor, it is an alternative way to represent a constructor. Like a constructor, it allows us to build the `ROut` service in terms of its dependencies (`RIn`). - -3. **Composable** — Because of their excellent **composition properties**, service builders are the idiomatic way in ZIO to create services that depend on other services. We can define service builders that are relying on each other. - -4. **Effectful and Resourceful** — The construction of ZIO service builders can be effectful and resourceful, they can be acquired and safely released when the services are done being utilized. - -5. **Asynchronous** — Unlike class constructors which are blocking, ZServiceBuilder is fully asynchronous and non-blocking. - -For example, a `ZServiceBuilder[Blocking with Logging, Throwable, Database]` can be thought of as a function that map `Blocking` and `Logging` services into `Database` service: - -```scala -(Blocking, Logging) => Database -``` - -So we can say that the `Database` service has two dependencies: `Blocking` and `Logging` services. - -Let's see how we can create a service builder: - -## Creation - -`ZServiceBuilder` is an **alternative to a class constructor**, a recipe to create a service. This recipe may contain the following information: - -1. **Dependencies** — To create a service, we need to indicate what other service we are depending on. For example, a `Database` service might need `Socket` and `Blocking` services to perform its operations. - -2. **Acquisition/Release Action** — It may contain how to initialize a service. For example, if we are creating a recipe for a `Database` service, we should provide how the `Database` will be initialized, via acquisition action. Also, it may contain how to release a service. For example, how the `Database` releases its connection pools. - -In some cases, a `ZServiceBuilder` may not have any dependencies or requirements from the environment. In this case, we can specify `Any` for the `RIn` type parameter. The `ServiceBuilder` type alias provided by ZIO is a convenient way to define a service builder without requirements. - -There are many ways to create a ZServiceBuilder. Here's an incomplete list: - - `ZServiceBuilder.succeed` to create a service builder from an existing service - - `ZServiceBuilder.succeedMany` to create a service builder from a value that's one or more services - - `ZServiceBuilder.fromFunction` to create a service builder from a function from the requirement to the service - - `ZServiceBuilder.fromEffect` to lift a `ZIO` effect to a service builder requiring the effect environment - - `ZServiceBuilder.fromAcquireRelease` for a service builder based on resource acquisition/release. The idea is the same as `ZManaged`. - - `ZServiceBuilder.fromService` to build a service builer from a service - - `ZServiceBuilder.fromServices` to build a service builder from a number of required services - - `ZServiceBuilder.identity` to express the requirement for a dependency - - `ZIO#toServiceBuilder` or `ZManaged#toServiceBuilder` to construct a service builder from an effect - -Where it makes sense, these methods have also variants to build a service effectfully (suffixed by `ZIO`), resourcefully (suffixed by `Managed`), or to create a combination of services (suffixed by `Many`). - -Let's review some of the `ZServiceBuilder`'s most useful constructors: - -### From Simple Values - -With `ZServiceBuilder.succeed` we can construct a `ZServiceBuilder` from a value. It returns a `UServiceBuilder[A]` value, which represents a service builder of an application that _has_ a service of type `A`: - -```scala -def succeed[A: Tag](a: A): UServiceBuilder[A] -``` - -In the following example, we are going to create a `nameServiceBuilder` that provides us the name of `Adam`. - -```scala mdoc:invisible -import zio._ -``` - -```scala mdoc:silent -val nameServiceBuilder: UServiceBuilder[String] = ZServiceBuilder.succeed("Adam") -``` - -In most cases, we use `ZServiceBuilder.succeed` to create a service builder of type `A`. - -For example, assume we have written the following service: - -```scala mdoc:silent -object terminal { - type Terminal = Terminal.Service - - object Terminal { - trait Service { - def printLine(line: String): UIO[Unit] - } - - object Service { - val live: Service = new Service { - override def printLine(line: String): UIO[Unit] = - ZIO.succeed(println(line)) - } - } - } -} -``` - -Now we can create a `ZServiceBuilder` from the `live` version of this service: - -```scala mdoc:silent -import terminal._ -val live: ZServiceBuilder[Any, Nothing, Terminal] = ZServiceBuilder.succeed(Terminal.Service.live) -``` - -### From Managed Resources - -Some components of our applications need to be managed, meaning they undergo a resource acquisition phase before usage, and a resource release phase after usage (e.g. when the application shuts down). - -Fortunately, the construction of ZIO service builders can be effectful and resourceful, this means they can be acquired and safely released when the services are done being utilized. - -`ZServiceBuilder` relies on the powerful `ZManaged` data type and this makes this process extremely simple. - -We can lift any `ZManaged` to `ZServiceBuilder` by providing a managed resource to the `ZIO.fromManaged` constructor: - -```scala mdoc:invisible -import scala.io.BufferedSource -``` - -```scala mdoc:silent:nest -val managedFile = ZManaged.fromAutoCloseable( - ZIO.attempt(scala.io.Source.fromFile("file.txt")) -) -val fileServiceBuilder: ZServiceBuilder[Any, Throwable, BufferedSource] = - ZServiceBuilder.fromManaged(managedFile) -``` - -Also, every `ZManaged` can be converted to `ZServiceBuilder` by calling `ZServiceBuilder#toServiceBuilder`: - -```scala mdoc:silent:nest -val fileServiceBuilder: ZServiceBuilder[Any, Throwable, BufferedSource] = managedFile.toServiceBuilder -``` - -Let's see another real-world example of creating a service builder from managed resources. Assume we have written a managed `UserRepository`: - -```scala mdoc:invisible:reset -import zio._ -import zio.Console._ -import scala.io.Source._ -import java.io.{FileInputStream, FileOutputStream, Closeable} - -trait DBConfig -trait Transactor - -def dbConfig: Task[DBConfig] = Task.attempt(???) -def initializeDb(config: DBConfig): Task[Unit] = Task.attempt(???) -def makeTransactor(config: DBConfig): ZManaged[Any, Throwable, Transactor] = ??? - -case class UserRepository(xa: Transactor) -object UserRepository { - def apply(xa: Transactor): UserRepository = new UserRepository(xa) -} -``` - -```scala mdoc:silent:nest -def userRepository: ZManaged[Console, Throwable, UserRepository] = for { - cfg <- dbConfig.toManaged - _ <- initializeDb(cfg).toManaged - xa <- makeTransactor(cfg) -} yield new UserRepository(xa) -``` - -We can convert that to `ZServiceBuilder` with `ZServiceBuilder.fromManaged` or `ZManaged#toServiceBuilder`: - -```scala mdoc:nest -val usersServiceBuilder = userRepository.toServiceBuilder -val usersServiceBuilder_ = ZServiceBuilder.fromManaged(userRepository) -``` - -Also, we can create a `ZServiceBuilder` directly from `acquire` and `release` actions of a managed resource: - -```scala mdoc:nest -def acquire = ZIO.attempt(new FileInputStream("file.txt")) -def release(resource: Closeable) = ZIO.succeed(resource.close()) - -val inputStreamServiceBuilder = ZServiceBuilder.fromAcquireRelease(acquire)(release) -``` - -### From ZIO Effects - -We can create `ZServiceBuilder` from any `ZIO` effect by using `ZServiceBuilder.fromEffect` constructor, or calling `ZIO#toServiceBuilder` method: - -```scala mdoc -val serviceBuilder = ZServiceBuilder.fromZIO(ZIO.succeed("Hello, World!")) -val serviceBuilder_ = ZIO.succeed("Hello, World!").toServiceBuilder -``` - -Assume we have a `ZIO` effect that read the application config from a file, we can create a service builder from that: - -```scala mdoc:invisible -trait AppConfig -``` - -```scala mdoc:nest -def loadConfig: Task[AppConfig] = Task.attempt(???) -val configServiceBuilder = ZServiceBuilder.fromZIO(loadConfig) -``` - -### From another Service - -Every `ZServiceBuilder` describes an application that requires some services as input and produces some services as output. Sometimes when we are creating a service builder, we may need to access and depend on one or several services. - -The `ZServiceBuilder.fromService` construct a service builder that purely depends on the specified service: - -```scala -def fromService[A: Tag, B: Tag](f: A => B): ZServiceBuilder[A, Nothing, B] -``` - -Assume we want to write a `live` version of the following logging service: - -```scala mdoc:silent:nest -object logging { - type Logging = Logging.Service - - object Logging { - trait Service { - def log(msg: String): UIO[Unit] - } - } -} -``` - -We can create that by using `ZServiceBuilder.fromService` constructor, which depends on `Console` service: - -```scala mdoc:invisible -import logging.Logging -import logging.Logging._ -``` - -```scala mdoc:silent:nest:warn -val live: ZServiceBuilder[Console, Nothing, Logging] = ZServiceBuilder.fromService(console => - new Service { - override def log(msg: String): UIO[Unit] = console.printLine(msg).orDie - } -) -``` - -## Vertical and Horizontal Composition - -We said that we can think of the `ZServiceBuilder` as a more powerful _constructor_. Constructors are not composable, because they are not values. While a constructor is not composable, `ZServiceBuilder` has a nice facility to compose with other `ZServiceBuilder`s. So we can say that a `ZServiceBuilder` turns a constructor into values. - -`ZServiceBuilder`s can be composed together horizontally or vertically: - -1. **Horizontal Composition** — They can be composed together horizontally with the `++` operator. When we compose service builders horizontally, the new service builder requires all the services that both of them require and produces all services that both of them produce. Horizontal composition is a way of composing two service builders side-by-side. It is useful when we combine two service builders that they don't have any relationship with each other. - -2. **Vertical Composition** — If we have a service builder that requires `A` and produces `B`, we can compose this with another service builder that requires `B` and produces `C`; this composition produces a service builder that requires `A` and produces `C`. The feed operator, `>>>`, stack them on top of each other by using vertical composition. This sort of composition is like _function composition_, feeding an output of one service builder to an input of another. - -Let's get into an example, assume we have these services with their implementations: - -```scala mdoc:invisible:reset -import zio._ -``` - -```scala mdoc:silent:nest -trait Logging { } -trait Database { } -trait BlobStorage { } -trait UserRepo { } -trait DocRepo { } - -case class LoggerImpl(console: Console) extends Logging { } -case object DatabaseImp extends Database { } -case class UserRepoImpl(logging: Logging, database: Database) extends UserRepo { } -case class BlobStorageImpl(logging: Logging) extends BlobStorage { } -case class DocRepoImpl(logging: Logging, database: Database, blobStorage: BlobStorage) extends DocRepo { } -``` - -We can't compose these services together, because their constructors are not value. `ZServiceBuilder` can convert these services into values, then we can compose them together. - -Let's assume we have lifted these services into `ZServiceBuilder`s: - -```scala mdoc:silent -val logging: URServiceBuilder[Console, Logging] = - (LoggerImpl.apply _).toServiceBuilder -val database: URServiceBuilder[Any, Database] = - ZServiceBuilder.succeed(DatabaseImp) -val userRepo: URServiceBuilder[Logging with Database, UserRepo] = - (UserRepoImpl(_, _)).toServiceBuilder -val blobStorage: URServiceBuilder[Logging, BlobStorage] = - (BlobStorageImpl(_)).toServiceBuilder -val docRepo: URServiceBuilder[Logging with Database with BlobStorage, DocRepo] = - (DocRepoImpl(_, _, _)).toServiceBuilder -``` - -Now, we can compose logging and database horizontally: - -```scala mdoc:silent -val newServiceBuilder: ZServiceBuilder[Console, Throwable, Logging with Database] = logging ++ database -``` - -And then we can compose the `newServiceBuilder` with `userRepo` vertically: - -```scala mdoc:silent -val myServiceBuilder: ZServiceBuilder[Console, Throwable, UserRepo] = newServiceBuilder >>> userRepo -``` - -## Service Builder Memoization - -One important feature of `ZIO` service builders is that **they are shared by default**, meaning that if the same service builder is used twice, the service builder will only be allocated a single time. - -For every service builder in our dependency graph, there is only one instance of it that is shared between all the service builders that depend on it. - -If we don't want to share a module, we should create a fresh, non-shared version of it through `ZServiceBuilder#fresh`. - -## Updating Local Dependencies - -```scala mdoc:invisible:reset -import zio._ - -trait DBError -trait Product -trait ProductId -trait DBConnection -case class User(id: UserId, name: String) -case class UserId(value: Long) - - -type UserRepo = UserRepo.Service - -object UserRepo { - trait Service { - def getUser(userId: UserId): IO[DBError, Option[User]] - def createUser(user: User): IO[DBError, Unit] - } - - // This simple in-memory version has no dependencies. - // This could be useful for tests where you don't want the additional - // complexity of having to manage DB Connections. - val inMemory: ServiceBuilder[Nothing, UserRepo] = ZServiceBuilder.succeed( - new Service { - def getUser(userId: UserId): IO[DBError, Option[User]] = UIO(???) - def createUser(user: User): IO[DBError, Unit] = UIO(???) - } - ) - - //accessor methods - def getUser(userId: UserId): ZIO[UserRepo, DBError, Option[User]] = - ZIO.serviceWithZIO(_.getUser(userId)) - - def createUser(user: User): ZIO[UserRepo, DBError, Unit] = - ZIO.serviceWithZIO(_.createUser(user)) -} - - -type Logging = Logging.Service - -object Logging { - trait Service { - def info(s: String): UIO[Unit] - def error(s: String): UIO[Unit] - } - - val consoleLogger: ZServiceBuilder[Console, Nothing, Logging] = ZServiceBuilder.fromFunction( environment => - new Service { - def info(s: String): UIO[Unit] = environment.get.printLine(s"info - $s").orDie - def error(s: String): UIO[Unit] = environment.get.printLine(s"error - $s").orDie - } - ) - - //accessor methods - def info(s: String): URIO[Logging, Unit] = - ZIO.serviceWithZIO(_.info(s)) - - def error(s: String): URIO[Logging, Unit] = - ZIO.serviceWithZIO(_.error(s)) -} - - - -import java.sql.Connection -def makeConnection: UIO[Connection] = UIO(???) -val connectionServiceBuilder: ServiceBuilder[Nothing, Connection] = - ZServiceBuilder.fromAcquireRelease(makeConnection)(c => UIO(c.close())) -val postgresServiceBuilder: ZServiceBuilder[Connection, Nothing, UserRepo] = - ZServiceBuilder.fromFunction { environment: ZEnvironment[Connection] => - new UserRepo.Service { - override def getUser(userId: UserId): IO[DBError, Option[User]] = UIO(???) - override def createUser(user: User): IO[DBError, Unit] = UIO(???) - } - } - -val fullRepo: ServiceBuilder[Nothing, UserRepo] = connectionServiceBuilder >>> postgresServiceBuilder - - - -val user2: User = User(UserId(123), "Tommy") -val makeUser: ZIO[Logging with UserRepo, DBError, Unit] = for { - _ <- Logging.info(s"inserting user") // URIO[Logging, Unit] - _ <- UserRepo.createUser(user2) // ZIO[UserRepo, DBError, Unit] - _ <- Logging.info(s"user inserted") // URIO[Logging, Unit] -} yield () - - -// compose horizontally -val horizontal: ZServiceBuilder[Console, Nothing, Logging with UserRepo] = Logging.consoleLogger ++ UserRepo.inMemory - -// fulfill missing services, composing vertically -val fullServiceBuilder: ServiceBuilder[Nothing, Logging with UserRepo] = Console.live >>> horizontal - -// provide the services to the program -makeUser.provideSome(fullServiceBuilder) -``` - -Given a service builder, it is possible to update one or more components it provides. We update a dependency in two ways: - -1. **Using the `update` Method** — This method allows us to replace one requirement with a different implementation: - -```scala mdoc:silent:nest -val withPostgresService = horizontal.update[UserRepo.Service]{ oldRepo => new UserRepo.Service { - override def getUser(userId: UserId): IO[DBError, Option[User]] = UIO(???) - override def createUser(user: User): IO[DBError, Unit] = UIO(???) - } - } -``` - -2. **Using Horizontal Composition** — Another way to update a requirement is to horizontally compose in a service builder that provides the updated service. The resulting composition will replace the old service builder with the new one: - -```scala mdoc:silent:nest -val dbServiceBuilder: ServiceBuilder[Nothing, UserRepo] = ZServiceBuilder.succeed(new UserRepo.Service { - override def getUser(userId: UserId): IO[DBError, Option[User]] = ??? - override def createUser(user: User): IO[DBError, Unit] = ??? - }) - -val updatedHorizontal2 = horizontal ++ dbServiceBuilder -``` - -## Hidden Versus Passed Through Dependencies - -One design decision regarding building dependency graphs is whether to hide or pass through the upstream dependencies of a service. `ZServiceBuilder` defaults to hidden dependencies but makes it easy to pass through dependencies as well. - -To illustrate this, consider the Postgres-based repository discussed above: - -```scala mdoc:silent:nest -val connection: ZServiceBuilder[Any, Nothing, Connection] = connectionServiceBuilder -val userRepo: ZServiceBuilder[Connection, Nothing, UserRepo] = postgresServiceBuilder -val serviceBuilder: ZServiceBuilder[Any, Nothing, UserRepo] = connection >>> userRepo -``` - -Notice that in `serviceBuilder`, the dependency `UserRepo` has on `Connection` has been "hidden", and is no longer expressed in the type signature. From the perspective of a caller, `serviceBuilder` just outputs a `UserRepo` and requires no inputs. The caller does not need to be concerned with the internal implementation details of how the `UserRepo` is constructed. - -To provide only some inputs, we need to explicitly define what inputs still need to be provided: - -```scala mdoc:silent:nest -trait Configuration - -val userRepoWithConfig: ZServiceBuilder[Configuration with Connection, Nothing, UserRepo] = - ZServiceBuilder.succeed(new Configuration{}) ++ postgresServiceBuilder -val partialServiceBuilder: ZServiceBuilder[Configuration, Nothing, UserRepo] = - (ZServiceBuilder.environment[Configuration] ++ connection) >>> userRepoWithConfig -``` - -In this example the requirement for a `Connection` has been satisfied, but `Configuration` is still required by `partialServiceBuilder`. - -This achieves an encapsulation of services and can make it easier to refactor code. For example, say we want to refactor our application to use an in-memory database: - -```scala mdoc:silent:nest -val updatedServiceBuilder: ZServiceBuilder[Any, Nothing, UserRepo] = dbServiceBuilder -``` - -No other code will need to be changed, because the previous implementation's dependency upon a `Connection` was hidden from users, and so they were not able to rely on it. - -However, if an upstream dependency is used by many other services, it can be convenient to "pass through" that dependency, and include it in the output of a service builder. This can be done with the `>+>` operator, which provides the output of one service builder to another service builder, returning a new service builder that outputs the services of _both_. - - -```scala mdoc:silent:nest -val serviceBuilder: ZServiceBuilder[Any, Nothing, Connection with UserRepo] = connection >+> userRepo -``` - -Here, the `Connection` dependency has been passed through, and is available to all downstream services. This allows a style of composition where the `>+>` operator is used to build a progressively larger set of services, with each new service able to depend on all the services before it. - -```scala mdoc:invisible -type Baker = Baker.Service -type Ingredients = Ingredients.Service -type Oven = Oven.Service -type Dough = Dough.Service -type Cake = Cake.Service - -object Baker { - trait Service -} - -object Ingredients { - trait Service -} - -object Oven { - trait Service -} - -object Dough { - trait Service -} - -object Cake { - trait Service -} -``` - -```scala mdoc -lazy val baker: ZServiceBuilder[Any, Nothing, Baker] = ??? -lazy val ingredients: ZServiceBuilder[Any, Nothing, Ingredients] = ??? -lazy val oven: ZServiceBuilder[Any, Nothing, Oven] = ??? -lazy val dough: ZServiceBuilder[Baker with Ingredients, Nothing, Dough] = ??? -lazy val cake: ZServiceBuilder[Baker with Oven with Dough, Nothing, Cake] = ??? - -lazy val all: ZServiceBuilder[Any, Nothing, Baker with Ingredients with Oven with Dough with Cake] = - baker >+> // Baker - ingredients >+> // Baker with Ingredients - oven >+> // Baker with Ingredients with Oven - dough >+> // Baker with Ingredients with Oven with Dough - cake // Baker with Ingredients with Oven with Dough with Cake -``` - -`ZServiceBuilder` makes it easy to mix and match these styles. If you pass through dependencies and later want to hide them you can do so through a simple type ascription: - -```scala mdoc:silent -lazy val hidden: ZServiceBuilder[Any, Nothing, Cake] = all -``` - -And if you do build your dependency graph more explicitly, you can be confident that dependencies used in multiple parts of the dependency graph will only be created once due to memoization and sharing. - -## Cyclic Dependencies - -The `ZServiceBuilder` mechanism makes it impossible to build cyclic dependencies, making the initialization process very linear, by construction. - -## Asynchronous Service Construction - -Another important note about `ZServiceBuilder` is that, unlike constructors which are synchronous, `ZServiceBuilder` is _asynchronous_. Constructors in classes are always synchronous. This is a drawback for non-blocking applications. Because sometimes we might want to use something that is blocking the inside constructor. - -For example, when we are constructing some sort of Kafka streaming service, we might want to connect to the Kafka cluster in the constructor of our service, which takes some time. So that wouldn't be a good idea to blocking inside a constructor. There are some workarounds for fixing this issue, but they are not perfect as the ZIO solution. - -Well, with ZIO ZServiceBuilder, our constructor could be asynchronous, and they also can block definitely. And that is because `ZServiceBuilder` has the full power of ZIO. And as a result, we have strictly more power on our constructors with ZServiceBuilder. - -We can acquire resources asynchronously or in a blocking fashion, and spend some time doing that, and we don't need to worry about it. That is not an anti-pattern. This is the best practice with ZIO. - -## Examples - -### The simplest ZServiceBuilder application - -This application demonstrates a ZIO program with a single dependency on a simple string value: - -```scala mdoc:compile-only -import zio._ - -object Example extends ZIOAppDefault { - - // Define our simple ZIO program - val zio: ZIO[String, Nothing, Unit] = for { - name <- ZIO.service[String] - _ <- UIO(println(s"Hello, $name!")) - } yield () - - // Create a ZServiceBuilder that produces a string and can be used to satisfy a string - // dependency that the program has - val nameServiceBuilder: UServiceBuilder[String] = ZServiceBuilder.succeed("Adam") - - // Run the program, providing the `nameServiceBuilder` - def run = zio.provideSome(nameServiceBuilder) -} - -``` - -### ZServiceBuilder application with dependencies - -In the following example, our ZIO application has several dependencies: - - `zio.Clock` - - `zio.Console` - - `ModuleB` - -`ModuleB` in turn depends upon `ModuleA`: - -```scala -import zio._ -import zio.Clock._ -import zio.Console._ -import java.io.IOException - -object moduleA { - type ModuleA = ModuleA.Service - - object ModuleA { - trait Service { - def letsGoA(v: Int): UIO[String] - } - - val any: ZServiceBuilder[ModuleA, Nothing, ModuleA] = - ZServiceBuilder.requires[ModuleA] - - val live: ServiceBuilder[Nothing, Service] = ZServiceBuilder.succeed { - new Service { - def letsGoA(v: Int): UIO[String] = UIO(s"done: v = $v ") - } - } - } - - def letsGoA(v: Int): URIO[ModuleA, String] = - ZIO.serviceWithZIO(_.letsGoA(v)) -} - -import moduleA._ - -object moduleB { - type ModuleB = ModuleB.Service - - object ModuleB { - trait Service { - def letsGoB(v: Int): UIO[String] - } - - val any: ZServiceBuilder[ModuleB, Nothing, ModuleB] = - ZServiceBuilder.requires[ModuleB] - - val live: ZServiceBuilder[ModuleA, Nothing, ModuleB] = ZServiceBuilder.fromService { (moduleA: ModuleA.Service) => - new Service { - def letsGoB(v: Int): UIO[String] = - moduleA.letsGoA(v) - } - } - } - - def letsGoB(v: Int): URIO[ModuleB, String] = - ZIO.serviceWithZIO(_.letsGoB(v)) -} - -object ZServiceBuilderApp0 extends zio.App { - - import moduleB._ - - val env = Console.live ++ Clock.live ++ (ModuleA.live >>> ModuleB.live) - val program: ZIO[Console with Clock with moduleB.ModuleB, IOException, Unit] = - for { - _ <- printLine(s"Welcome to ZIO!") - _ <- sleep(1.second) - r <- letsGoB(10) - _ <- printLine(r) - } yield () - - def run(args: List[String]) = - program.provideSome(env).exitCode - -} - -// output: -// [info] running ZServiceBuilderApp -// Welcome to ZIO! -// done: v = 10 -``` - -### ZServiceBuilder example with complex dependencies - -In this example, we can see that `ModuleC` depends upon `ModuleA`, `ModuleB`, and `Clock`. The service builder provided to the runnable application shows how dependency service builders can be combined using `++` into a single combined service builder. The combined service builder will then be able to produce both of the outputs of the original sets as a single service builder: - -```scala mdoc:compile-only -import zio._ -import zio.Clock._ - -object ZServiceBuilderApp1 extends scala.App { - val rt = Runtime.default - - type ModuleA = ModuleA.Service - - object ModuleA { - - trait Service {} - - val any: ZServiceBuilder[ModuleA, Nothing, ModuleA] = - ZServiceBuilder.environment[ModuleA] - - val live: ZServiceBuilder[Any, Nothing, ModuleA] = - ZServiceBuilder.succeed(new Service {}) - } - - type ModuleB = ModuleB.Service - - object ModuleB { - - trait Service {} - - val any: ZServiceBuilder[ModuleB, Nothing, ModuleB] = - ZServiceBuilder.environment[ModuleB] - - val live: ZServiceBuilder[Any, Nothing, ModuleB] = - ZServiceBuilder.succeed(new Service {}) - } - - type ModuleC = ModuleC.Service - - object ModuleC { - - trait Service { - def foo: UIO[Int] - } - - val any: ZServiceBuilder[ModuleC, Nothing, ModuleC] = - ZServiceBuilder.environment[ModuleC] - - val live: ZServiceBuilder[ModuleA with ModuleB with Clock, Nothing, ModuleC] = - ZServiceBuilder.succeed { - new Service { - val foo: UIO[Int] = UIO.succeed(42) - } - } - - val foo: URIO[ModuleC, Int] = - ZIO.serviceWithZIO(_.foo) - } - - val env = (ModuleA.live ++ ModuleB.live ++ ZServiceBuilder.environment[Clock]) >>> ModuleC.live - - val res = ModuleC.foo.provideCustom(env) - - val out = rt.unsafeRun(res) - println(out) - // 42 -} -``` diff --git a/docs/datatypes/core/runtime.md b/docs/datatypes/core/runtime.md index 56c299f8baee..032444cf6bca 100644 --- a/docs/datatypes/core/runtime.md +++ b/docs/datatypes/core/runtime.md @@ -198,13 +198,13 @@ val program: ZIO[Console, Throwable, Unit] = _ <- putStrLn("Thank you for " + a) } yield () -val diagnosticsServiceBuilder: ZServiceBuilder[ZEnv, Throwable, Diagnostics] = +val diagnosticsLayer: ZLayer[ZEnv, Throwable, Diagnostics] = Diagnostics.make("localhost", 1111) val runtime: Runtime[ZEnv] = Runtime.default.mapRuntimeConfig(_.withSupervisor(ZMXSupervisor)) -runtime.unsafeRun(program.provideCustom(diagnosticsServiceBuilder)) +runtime.unsafeRun(program.provideCustom(diagnosticsLayer)) ``` ### User-defined Executor diff --git a/docs/datatypes/core/zioapp.md b/docs/datatypes/core/zioapp.md index dc65b5020fdf..e5c377e5d420 100644 --- a/docs/datatypes/core/zioapp.md +++ b/docs/datatypes/core/zioapp.md @@ -3,7 +3,7 @@ id: zioapp title: "ZIOApp" --- -The `ZIOApp` trait is an entry point for a ZIO application that allows sharing service builders between applications. It also +The `ZIOApp` trait is an entry point for a ZIO application that allows sharing layers between applications. It also provides us the ability to compose multiple ZIO applications. There is another simpler version of `ZIOApp` called `ZIOAppDefault`. We usually use `ZIOAppDefault` which uses the default ZIO environment (`ZEnv`). @@ -111,4 +111,4 @@ object MyApp2 extends ZIOAppDefault { object Main extends ZIOApp.Proxy(MyApp1 <> MyApp2) ``` -The `<>` operator combines the service builders of the two applications, composes their hooks, and then runs the two applications in parallel. +The `<>` operator combines the layers of the two applications, composes their hooks, and then runs the two applications in parallel. diff --git a/docs/datatypes/index.md b/docs/datatypes/index.md index 233f7317fa3c..bb05b16aa5d6 100644 --- a/docs/datatypes/index.md +++ b/docs/datatypes/index.md @@ -28,12 +28,12 @@ ZIO contains a few data types that can help you solve complex problems in asynch - **[Cause](core/cause.md)** - `Cause[E]` is a description of a full story of a fiber failure. ## Contextual Data Types -- **[ZServiceBuilder](contextual/zservicebuilder.md)** — The `ZIO[-R, +E, +A]` data type describes an effect that requires an input type of `R`, as an environment, may fail with an error of type `E` or succeed and produces a value of type `A`. - + **[RServiceBuilder](contextual/rservicebuilder.md)** — `RServiceBuilder[-RIn, +ROut]` is a type alias for `ZServiceBuilder[RIn, Throwable, ROut]`, which represents a service builder that requires `RIn` as its input, it may fail with `Throwable` value, or returns `ROut` as its output. - + **[UServiceBuilder](contextual/uservicebuilder.md)** — UServiceBuilder[+ROut] is a type alias for ZServiceBuilder[Any, Nothing, ROut], which represents a service builder that doesn't require any services as its input, it can't fail, and returns ROut as its output. - + **[ServiceBuilder](contextual/servicebuilder.md)** — ServiceBuilder[+E, +ROut] is a type alias for ZServiceBuilder[Any, E, ROut], which represents a service builder that doesn't require any services, it may fail with an error type of E, and returns ROut as its output. - + **[URServiceBuilder](contextual/urservicebuilder.md)** — URServiceBuilder[-RIn, +ROut] is a type alias for ZServiceBuilder[RIn, Nothing, ROut], which represents a set of services that requires RIn as its input, it can't fail, and returns ROut as its output. - + **[TaskServiceBuilder](contextual/task-servicebuilder.md)** — TaskServiceBuilder[+ROut] is a type alias for ZServiceBuilder[Any, Throwable, ROut], which represents a set of services that doesn't require any services as its input, it may fail with Throwable value, and returns ROut as its output. +- **[ZLayer](contextual/zlayer.md)** — The `ZIO[-R, +E, +A]` data type describes an effect that requires an input type of `R`, as an environment, may fail with an error of type `E` or succeed and produces a value of type `A`. + + **[RLayer](contextual/rlayer.md)** — `RLayer[-RIn, +ROut]` is a type alias for `ZLayer[RIn, Throwable, ROut]`, which represents a layer that requires `RIn` as its input, it may fail with `Throwable` value, or returns `ROut` as its output. + + **[ULayer](contextual/ulayer.md)** — ULayer[+ROut] is a type alias for ZLayer[Any, Nothing, ROut], which represents a layer that doesn't require any services as its input, it can't fail, and returns ROut as its output. + + **[Layer](contextual/layer.md)** — Layer[+E, +ROut] is a type alias for ZLayer[Any, E, ROut], which represents a layer that doesn't require any services, it may fail with an error type of E, and returns ROut as its output. + + **[URLayer](contextual/urlayer.md)** — URLayer[-RIn, +ROut] is a type alias for ZLayer[RIn, Nothing, ROut], which represents a set of services that requires RIn as its input, it can't fail, and returns ROut as its output. + + **[TaskLayer](contextual/task-layer.md)** — TaskLayer[+ROut] is a type alias for ZLayer[Any, Throwable, ROut], which represents a set of services that doesn't require any services as its input, it may fail with Throwable value, and returns ROut as its output. ## Concurrency diff --git a/docs/datatypes/misc/zstate.md b/docs/datatypes/misc/zstate.md index e937fef346fd..d361a4a61796 100644 --- a/docs/datatypes/misc/zstate.md +++ b/docs/datatypes/misc/zstate.md @@ -21,7 +21,7 @@ val myApp: ZIO[Console, IOException, Unit] = } yield () ``` -The idiomatic way to work with `ZState` is as part of the environment using operators defined on `ZIO`. So instead of creating `ZState` directly using `ZState.make` constructor, we can access the `ZState` from the environment, and finally, provide proper service builder using `ZState.makeServiceBuilder` constructor: +The idiomatic way to work with `ZState` is as part of the environment using operators defined on `ZIO`. So instead of creating `ZState` directly using `ZState.make` constructor, we can access the `ZState` from the environment, and finally, provide proper layer using `ZState.makeLayer` constructor: ```scala mdoc:compile-only import zio._ @@ -37,7 +37,7 @@ object ZStateExample extends zio.ZIOAppDefault { _ <- Console.printLine(s"current state: $state") } yield () - def run = myApp.injectCustom(ZState.makeServiceBuilder(0)) + def run = myApp.injectCustom(ZState.makeLayer(0)) } ``` @@ -60,7 +60,7 @@ object ZStateExample extends zio.ZIOAppDefault { _ <- Console.printLine(s"Current state: $state") } yield () - def run = myApp.injectCustom(ZState.makeServiceBuilder(MyState(0))) + def run = myApp.injectCustom(ZState.makeLayer(MyState(0))) } ``` @@ -106,7 +106,7 @@ object ZStateExample extends ZIOAppDefault { def run = myApp.injectCustom( - ZState.makeServiceBuilder(MyState(0)) + ZState.makeLayer(MyState(0)) ) } ``` diff --git a/docs/howto/howto-macros.md b/docs/howto/howto-macros.md index fb1387f3c58d..1f856b9ecf2c 100644 --- a/docs/howto/howto-macros.md +++ b/docs/howto/howto-macros.md @@ -106,7 +106,7 @@ libraryDependencies += "dev.zio" %% "zio-test" % "" ### Description -The `@mockable[A]` generates _capability tags_ and _mock service builder_ into annotated object. +The `@mockable[A]` generates _capability tags_ and _mock layer_ into annotated object. ```scala import zio.test.mock.mockable @@ -118,7 +118,7 @@ object AccountObserverMock Will result in: ```scala -import zio.{ Has, UIO, URServiceBuilder, ZServiceBuilder } +import zio.{ Has, UIO, URLayer, ZLayer } import zio.test.mock.{ Mock, Proxy } object AccountObserverMock extends Mock[Has[AccountObserver.Service]] { @@ -126,8 +126,8 @@ object AccountObserverMock extends Mock[Has[AccountObserver.Service]] { object ProcessEvent extends Effect[AccountEvent, Nothing, Unit] object RunCommand extends Effect[Unit, Nothing, Unit] - val compose: URServiceBuilder[Has[Proxy], AccountObserver] = - ZServiceBuilder.fromServiceM { proxy => + val compose: URLayer[Has[Proxy], AccountObserver] = + ZLayer.fromServiceM { proxy => withRuntime.map { rts => new AccountObserver.Service { def processEvent(event: AccountEvent) = proxy(ProcessEvent, event) diff --git a/docs/howto/migrate/migration-guide.md b/docs/howto/migrate/migration-guide.md index d61b5a4f6680..8bee0e1d8580 100644 --- a/docs/howto/migrate/migration-guide.md +++ b/docs/howto/migrate/migration-guide.md @@ -100,9 +100,9 @@ Here are some of the most important changes: - **`Discard` instead of the underscore `_` suffix** — The underscore suffix is another legacy naming convention from Haskell's world. In ZIO 1.x, the underscore suffix means we are going to discard the result. The underscore version works exactly like the one without the underscore, but it discards the result and returns `Unit` in the ZIO context. For example, the `collectAll_` operator renamed to `collectAllDiscard`. -- **`as`, `to`, `into` prefixes** — The `ZIO#asService` method is renamed to `ZIO#toServiceBuilder` and also the `ZIO#to` is renamed to the `ZIO#intoPromise`. So now we have three categories of conversion: +- **`as`, `to`, `into` prefixes** — The `ZIO#asService` method is renamed to `ZIO#toLayer` and also the `ZIO#to` is renamed to the `ZIO#intoPromise`. So now we have three categories of conversion: 1. **as** — The `ZIO#as` method and its variants like `ZIO#asSome`, `ZIO#asSomeError` and `ZIO#asService` are used when transforming the `A` inside of a `ZIO`, generally as shortcuts for `map(aToFoo(_))`. - 2. **to** — The `ZIO#to` method and its variants like `ZIO#toServiceBuilder`, `ZIO#toManaged`, and `ZIO#toFuture` are used when the `ZIO` is transformed into something else other than the `ZIO` data-type. + 2. **to** — The `ZIO#to` method and its variants like `ZIO#toLayer`, `ZIO#toManaged`, and `ZIO#toFuture` are used when the `ZIO` is transformed into something else other than the `ZIO` data-type. 3. **into** — All `into*` methods, accept secondary data-type, modify it with the result of the current effect (e.g. `ZIO#intoPromise`, `ZStream#intoHub`, `ZStream#intoQueue` and `ZStream#intoManaged`) | ZIO 1.x | ZIO 2.x | @@ -130,7 +130,7 @@ Here are some of the most important changes: | `ZIO#timeoutHalt` | `ZIO#timeoutFailCause` | | | | | `ZIO#to` | `ZIO#intoPromise` | -| `ZIO#asService` | `ZIO#toServiceBuilder` | +| `ZIO#asService` | `ZIO#toLayer` | | | | | `ZIO.accessM` | `ZIO.environmentWithZIO` | | `ZIO.fromFunctionM` | `ZIO.environmentWithZIO` | @@ -501,15 +501,15 @@ ZIO.withRuntimeConfig(newRuntimeConfiguration)(effect) ``` After running the effect on the specified runtime configuration, it will restore the old runtime configuration. -## ZServiceBuilder +## ZLayer ### Functions to Service Builders -In ZIO 1.x, when we want to write a service that depends on other services, we need to use `ZServiceBuilder.fromService*` variants with a lot of boilerplate: +In ZIO 1.x, when we want to write a service that depends on other services, we need to use `ZLayer.fromService*` variants with a lot of boilerplate: ```scala -val live: URServiceBuilder[Clock with Console, Logging] = - ZServiceBuilder.fromServices[Clock.Service, Console.Service, Logging.Service] { +val live: URLayer[Clock with Console, Logging] = + ZLayer.fromServices[Clock.Service, Console.Service, Logging.Service] { (clock: Clock.Service, console: Console.Service) => new Service { override def log(line: String): UIO[Unit] = @@ -521,24 +521,24 @@ val live: URServiceBuilder[Clock with Console, Logging] = } ``` -ZIO 2.x deprecates all `ZServiceBuilder.fromService*` functions: +ZIO 2.x deprecates all `ZLayer.fromService*` functions: | ZIO 1.0 | ZIO 2.x | |----------------------------------|---------| -| `ZServiceBuilder.fromService` | `toServiceBuilder` | -| `ZServiceBuilder.fromServices` | `toServiceBuilder` | -| `ZServiceBuilder.fromServiceM` | `toServiceBuilder` | -| `ZServiceBuilder.fromServicesM` | `toServiceBuilder` | -| `ZServiceBuilder.fromServiceManaged` | `toServiceBuilder` | -| `ZServiceBuilder.fromServicesManaged` | `toServiceBuilder` | -| `ZServiceBuilder.fromServiceMany` | `toServiceBuilder` | -| `ZServiceBuilder.fromServicesMany` | `toServiceBuilder` | -| `ZServiceBuilder.fromServiceManyM` | `toServiceBuilder` | -| `ZServiceBuilder.fromServicesManyM` | `toServiceBuilder` | -| `ZServiceBuilder.fromServiceManyManaged` | `toServiceBuilder` | -| `ZServiceBuilder.fromServicesManyManaged` | `toServiceBuilder` | - -Instead, it provides the `toServiceBuilder` extension methods for functions: +| `ZLayer.fromService` | `toLayer` | +| `ZLayer.fromServices` | `toLayer` | +| `ZLayer.fromServiceM` | `toLayer` | +| `ZLayer.fromServicesM` | `toLayer` | +| `ZLayer.fromServiceManaged` | `toLayer` | +| `ZLayer.fromServicesManaged` | `toLayer` | +| `ZLayer.fromServiceMany` | `toLayer` | +| `ZLayer.fromServicesMany` | `toLayer` | +| `ZLayer.fromServiceManyM` | `toLayer` | +| `ZLayer.fromServicesManyM` | `toLayer` | +| `ZLayer.fromServiceManyManaged` | `toLayer` | +| `ZLayer.fromServicesManyManaged` | `toLayer` | + +Instead, it provides the `toLayer` extension methods for functions: ```scala case class LoggingLive(console: Console, clock: Clock) extends Logging { @@ -550,12 +550,12 @@ case class LoggingLive(console: Console, clock: Clock) extends Logging { } object LoggingLive { - val serviceBuilder: URServiceBuilder[Console with Clock, Logging] = - (LoggingLive(_, _)).toServiceBuilder[Logging] + val layer: URLayer[Console with Clock, Logging] = + (LoggingLive(_, _)).toLayer[Logging] } ``` -Note that the `LoggingLive(_, _)` is a `Function2` of type `(Console, Clock) => LoggingLive`. As the ZIO 2.x provides the `toServiceBuilder` extension method for all `Function` arities, we can call the `toServiceBuilder` on any function to convert that to the `ZServiceBuilder`. Unlike the `ZServiceBuilder.fromService*` functions, this can completely infer the input types, so it saves us from a lot of boilerplates we have had in ZIO 1.x. +Note that the `LoggingLive(_, _)` is a `Function2` of type `(Console, Clock) => LoggingLive`. As the ZIO 2.x provides the `toLayer` extension method for all `Function` arities, we can call the `toLayer` on any function to convert that to the `ZLayer`. Unlike the `ZLayer.fromService*` functions, this can completely infer the input types, so it saves us from a lot of boilerplates we have had in ZIO 1.x. ### Accessing a Service from the Environment @@ -620,7 +620,7 @@ for { ### Building the Dependency Graph -To create the dependency graph in ZIO 1.x, we should compose the required service buildera manually. As the ordering of service builder compositions matters, and also we should care about composing service builders in both vertical and horizontal manner, it would be a cumbersome job to create a dependency graph with a lot of boilerplates. +To create the dependency graph in ZIO 1.x, we should compose the required layera manually. As the ordering of layer compositions matters, and also we should care about composing layers in both vertical and horizontal manner, it would be a cumbersome job to create a dependency graph with a lot of boilerplates. Assume we have the following dependency graph with two top-level dependencies: @@ -635,7 +635,7 @@ Assume we have the following dependency graph with two top-level dependencies: Console ``` -In ZIO 1.x, we had to compose these different service builders together to create the whole application dependency graph: +In ZIO 1.x, we had to compose these different layers together to create the whole application dependency graph: ```scala mdoc:invisible:nest trait Logging {} @@ -659,43 +659,43 @@ case class BlobStorageImpl(logging: Logging) extends BlobStorage {} case class DocRepoImpl(logging: Logging, database: Database, blobStorage: BlobStorage) extends DocRepo {} object Logging { - val live: URServiceBuilder[Console, Logging] = - LoggerImpl.toServiceBuilder[Logging] + val live: URLayer[Console, Logging] = + LoggerImpl.toLayer[Logging] } object Database { - val live: URServiceBuilder[Any, Database] = - DatabaseImp.toServiceBuilder[Database] + val live: URLayer[Any, Database] = + DatabaseImp.toLayer[Database] } object UserRepo { - val live: URServiceBuilder[Logging with Database, UserRepo] = - (UserRepoImpl(_, _)).toServiceBuilder[UserRepo] + val live: URLayer[Logging with Database, UserRepo] = + (UserRepoImpl(_, _)).toLayer[UserRepo] } object BlobStorage { - val live: URServiceBuilder[Logging, BlobStorage] = - BlobStorageImpl.toServiceBuilder[BlobStorage] + val live: URLayer[Logging, BlobStorage] = + BlobStorageImpl.toLayer[BlobStorage] } object DocRepo { - val live: URServiceBuilder[Logging with Database with BlobStorage, DocRepo] = - (DocRepoImpl(_, _, _)).toServiceBuilder[DocRepo] + val live: URLayer[Logging with Database with BlobStorage, DocRepo] = + (DocRepoImpl(_, _, _)).toLayer[DocRepo] } val myApp: ZIO[DocRepo with UserRepo, Nothing, Unit] = ZIO.succeed(???) ``` ```scala mdoc:silent:nest -val appServiceBuilder: URServiceBuilder[Any, DocRepo with UserRepo] = +val appLayer: URLayer[Any, DocRepo with UserRepo] = (((Console.live >>> Logging.live) ++ Database.live ++ (Console.live >>> Logging.live >>> BlobStorage.live)) >>> DocRepo.live) ++ (((Console.live >>> Logging.live) ++ Database.live) >>> UserRepo.live) -val res: ZIO[Any, Nothing, Unit] = myApp.provide(appServiceBuilder) +val res: ZIO[Any, Nothing, Unit] = myApp.provide(appLayer) ``` -As the development of our application progress, the number of service builders will grow, and maintaining the dependency graph would be tedious and hard to debug. +As the development of our application progress, the number of layers will grow, and maintaining the dependency graph would be tedious and hard to debug. For example, if we miss the `Logging.live` dependency, the compile-time error would be very messy: @@ -708,9 +708,9 @@ myApp.provide( ``` type mismatch; - found : zio.URServiceBuilder[zio.Logging with zio.Database with zio.BlobStorage,zio.DocRepo] - (which expands to) zio.ZServiceBuilder[zio.Logging with zio.Database with zio.BlobStorage,Nothing,zio.DocRepo] - required: zio.ZServiceBuilder[zio.Database with zio.BlobStorage,?,?] + found : zio.URLayer[zio.Logging with zio.Database with zio.BlobStorage,zio.DocRepo] + (which expands to) zio.ZLayer[zio.Logging with zio.Database with zio.BlobStorage,Nothing,zio.DocRepo] + required: zio.ZLayer[zio.Database with zio.BlobStorage,?,?] ((Database.live ++ BlobStorage.live) >>> DocRepo.live) ++ ``` @@ -757,7 +757,7 @@ val app: ZIO[Any, Nothing, Unit] = ``` ``` - ZServiceBuilder Wiring Error + ZLayer Wiring Error ❯ missing Logging ❯ for DocRepo.live @@ -766,10 +766,10 @@ val app: ZIO[Any, Nothing, Unit] = ❯ for UserRepo.live ``` -We can also directly construct a service builder using `ZServiceBuilder.wire`: +We can also directly construct a layer using `ZLayer.wire`: ```scala mdoc:silent:nest -val serviceBuilder = ZServiceBuilder.wire[DocRepo with UserRepo]( +val layer = ZLayer.wire[DocRepo with UserRepo]( Console.live, Logging.live, DocRepo.live, @@ -779,10 +779,10 @@ val serviceBuilder = ZServiceBuilder.wire[DocRepo with UserRepo]( ) ``` -And also the `ZServiceBuilder.wireSome` helps us to construct a service builder which requires on some service and produces some other services (`URServiceBuilder[Int, Out]`) using `ZServiceBuilder.wireSome[In, Out]`: +And also the `ZLayer.wireSome` helps us to construct a layer which requires on some service and produces some other services (`URLayer[Int, Out]`) using `ZLayer.wireSome[In, Out]`: ```scala mdoc:silent:nest -val serviceBuilder = ZServiceBuilder.wireSome[Console, DocRepo with UserRepo]( +val layer = ZLayer.wireSome[Console, DocRepo with UserRepo]( Logging.live, DocRepo.live, Database.live, @@ -846,27 +846,27 @@ val app: ZIO[zio.ZEnv, Nothing, Unit] = | `ZIO#provide` | `ZIO#inject` | | `ZIO#provideSome` | `ZIO#injectSome` | | `ZIO#provideCustom` | `ZIO#injectCustom` | -| Composing manually using `ZServiceBuilder` combinators | `ZServiceBuilder#wire` | -| Composing manually using `ZServiceBuilder` combinators | `ZServiceBuilder#wireSome` | +| Composing manually using `ZLayer` combinators | `ZLayer#wire` | +| Composing manually using `ZLayer` combinators | `ZLayer#wireSome` | -### ZServiceBuilder Debugging +### ZLayer Debugging -To debug ZServiceBuilder construction, we have two built-in service builders, i.e., `ZServiceBuilder.Debug.tree` and `ZServiceBuilder.Debug.mermaid`. For example, by including `ZServiceBuilder.Debug.mermaid` into our service builder construction, the compiler generates the following debug information: +To debug ZLayer construction, we have two built-in layers, i.e., `ZLayer.Debug.tree` and `ZLayer.Debug.mermaid`. For example, by including `ZLayer.Debug.mermaid` into our layer construction, the compiler generates the following debug information: ```scala -val serviceBuilder = ZServiceBuilder.wire[DocRepo with UserRepo]( +val layer = ZLayer.wire[DocRepo with UserRepo]( Console.live, Logging.live, DocRepo.live, Database.live, BlobStorage.live, UserRepo.live, - ZServiceBuilder.Debug.mermaid + ZLayer.Debug.mermaid ) ``` ```scala -[info] ZServiceBuilder Wiring Graph +[info] ZLayer Wiring Graph [info] [info] ◉ DocRepo.live [info] ├─◑ Logging.live @@ -901,8 +901,8 @@ object logging { } // Live implementation of the Logging service - val live: ZServiceBuilder[Clock with Console, Nothing, Logging] = - ZServiceBuilder.fromServices[Clock.Service, Console.Service, Logging.Service] { + val live: ZLayer[Clock with Console, Nothing, Logging] = + ZLayer.fromServices[Clock.Service, Console.Service, Logging.Service] { (clock: Clock.Service, console: Console.Service) => new Logging.Service { override def log(line: String): UIO[Unit] = @@ -949,10 +949,10 @@ case class LoggingLive(console: Console, clock: Clock) extends Logging { } yield () } -// Converting the Service Implementation into the ZServiceBuilder +// Converting the Service Implementation into the ZLayer object LoggingLive { - val serviceBuilder: URServiceBuilder[Console with Clock, Logging] = - (LoggingLive(_, _)).toServiceBuilder[Logging] + val layer: URLayer[Console with Clock, Logging] = + (LoggingLive(_, _)).toLayer[Logging] } ``` @@ -960,9 +960,9 @@ As we see, we have the following changes: 1. **Deprecation of Type Alias for `Has` Wrappers** — In _Module Pattern 1.0_ although the type aliases were to prevent using `Has[ServiceName]` boilerplate everywhere, they were confusing, and led to doubly nested `Has[Has[ServiceName]]`. So the _Module Pattern 2.0_ doesn't anymore encourage using type aliases. Also, they were removed from all built-in ZIO services. So, the `type Console = Has[Console.Service]` removed and the `Console.Service` will just be `Console`. -2. **Introducing Constructor-based Dependency Injection** — In _Module Pattern 1.0_ when we wanted to create a service builder that depends on other services, we had to use `ZServiceBuilder.fromService*` constructors. The problem with the `ZServiceBuilder` constructors is that there are too many constructors each one is useful for a specific use-case, but people had troubled in spending a lot of time figuring out which one to use. +2. **Introducing Constructor-based Dependency Injection** — In _Module Pattern 1.0_ when we wanted to create a layer that depends on other services, we had to use `ZLayer.fromService*` constructors. The problem with the `ZLayer` constructors is that there are too many constructors each one is useful for a specific use-case, but people had troubled in spending a lot of time figuring out which one to use. - In _Module Pattern 2.0_ we don't worry about all these different `ZServiceBuilder` constructors. It recommends **providing dependencies as interfaces through the case class constructor**, and then we have direct access to all of these dependencies to implement the service. Finally, to create the `ZServiceBuilder` we call `toServiceBuilder` on the service implementation. + In _Module Pattern 2.0_ we don't worry about all these different `ZLayer` constructors. It recommends **providing dependencies as interfaces through the case class constructor**, and then we have direct access to all of these dependencies to implement the service. Finally, to create the `ZLayer` we call `toLayer` on the service implementation. > **_Note:_** > @@ -974,29 +974,29 @@ As we see, we have the following changes: > } > > object LoggingLive { - > val serviceBuilder: URServiceBuilder[Any, Logging] = LoggingLive().toServiceBuilder + > val layer: URLayer[Any, Logging] = LoggingLive().toLayer > } >``` > Compiler Error: > ``` - > value toServiceBuilder is not a member of LoggingLive - > val serviceBuilder: URServiceBuilder[Any, Logging] = LoggingLive().toServiceBuilder + > value toLayer is not a member of LoggingLive + > val layer: URLayer[Any, Logging] = LoggingLive().toLayer > ``` > The problem here is that the companion object won't automatically extend `() => Logging`. So the workaround is doing that manually: > ```scala > object LoggingLive extends (() => Logging) { - > val serviceBuilder: URServiceBuilder[Any, Logging] = LoggingLive.toServiceBuilder + > val layer: URLayer[Any, Logging] = LoggingLive.toLayer > } > ``` - > Or we can just write the `val serviceBuilder: URServiceBuilder[Any, Logging] = (() => Logging).toServiceBuilder` to fix that. + > Or we can just write the `val layer: URLayer[Any, Logging] = (() => Logging).toLayer` to fix that. > **_Note:_** > - > The new pattern encourages us to parametrize _case classes_ to introduce service dependencies and then using `toServiceBuilder` syntax as a very simple way that always works. But it doesn't enforce us to do that. We can also just pull whatever services we want from the environment using `ZIO.service` or `ZManaged.service` and then implement the service and call `toServiceBuilder` on it: + > The new pattern encourages us to parametrize _case classes_ to introduce service dependencies and then using `toLayer` syntax as a very simple way that always works. But it doesn't enforce us to do that. We can also just pull whatever services we want from the environment using `ZIO.service` or `ZManaged.service` and then implement the service and call `toLayer` on it: > ```scala mdoc:silent:nest > object LoggingLive { - > val serviceBuilder: ZServiceBuilder[Clock with Console, Nothing, Logging] = - > ZServiceBuilder { + > val layer: ZLayer[Clock with Console, Nothing, Logging] = + > ZLayer { > for { > console <- ZIO.service[Console] > clock <- ZIO.service[Clock] @@ -1013,7 +1013,7 @@ As we see, we have the following changes: 3. **Separated Interface** — In the _Module Pattern 2.0_, ZIO supports the _Separated Interface_ pattern which encourages keeping the implementation of an interface decoupled from the client and its definition. - As our application grows, where we define our service builders matters more. _Separated Interface_ is a very useful pattern while we are developing a complex application. It helps us to reduce the coupling between application components. + As our application grows, where we define our layers matters more. _Separated Interface_ is a very useful pattern while we are developing a complex application. It helps us to reduce the coupling between application components. Following two changes in _Module Pattern_ we can define the service definition in one package but its implementations in other packages: @@ -1023,9 +1023,9 @@ As we see, we have the following changes: > > Module Pattern 2.0 supports the idea of _Separated Interface_, but it doesn't enforce us grouping them into different packages and modules. The decision is up to us, based on the complexity and requirements of our application. - 2. **Decoupling Interfaces from Implementation** — Assume we have a complex application, and our interface is `Logging` with different implementations that potentially depend on entirely different modules. Putting service builders in the service definition means anyone depending on the service definition needs to depend on all the dependencies of all the implementations, which is not a good practice. + 2. **Decoupling Interfaces from Implementation** — Assume we have a complex application, and our interface is `Logging` with different implementations that potentially depend on entirely different modules. Putting layers in the service definition means anyone depending on the service definition needs to depend on all the dependencies of all the implementations, which is not a good practice. - In Module Pattern 2.0, service builders are defined in the implementation's companion object, not in the interface's companion object. So instead of calling `Logging.live` to access the live implementation we call `LoggingLive.serviceBuilder`. + In Module Pattern 2.0, layers are defined in the implementation's companion object, not in the interface's companion object. So instead of calling `Logging.live` to access the live implementation we call `LoggingLive.layer`. 4. **Accessor Methods** — The new pattern reduced one level of indirection on writing accessor methods. So instead of accessing the environment (`ZIO.access/ZIO.accessM`) and then retrieving the service from the environment (`Has#get`) and then calling the service method, the _Module Pattern 2.0_ introduced the `ZIO.serviceWith` that is a more concise way of writing accessor methods. For example, instead of `ZIO.accessM(_.get.log(line))` we write `ZIO.serviceWith(_.log(line))`. @@ -1056,12 +1056,12 @@ Here is list of other deprecated methods: | ZIO 1.x | ZIO 2.x | |-------------------------------------|---------------------------------------| -| `ZServiceBuilder.fromEffect` | `ZServiceBuilder.fromZIO` | -| `ZServiceBuilder.fromEffectMany` | `ZServiceBuilder.fromZIOMany` | -| `ZServiceBuilder.fromFunctionM` | `ZServiceBuilder.fromFunctionZIO` | -| `ZServiceBuilder.fromFunctionManyM` | `ZServiceBuilder.fromFunctionManyZIO` | -| `ZServiceBuilder.identity` | `ZServiceBuilder.environment` | -| `ZServiceBuilder.requires` | `ZServiceBuilder.environment` | +| `ZLayer.fromEffect` | `ZLayer.fromZIO` | +| `ZLayer.fromEffectMany` | `ZLayer.fromZIOMany` | +| `ZLayer.fromFunctionM` | `ZLayer.fromFunctionZIO` | +| `ZLayer.fromFunctionManyM` | `ZLayer.fromFunctionManyZIO` | +| `ZLayer.identity` | `ZLayer.environment` | +| `ZLayer.requires` | `ZLayer.environment` | ## ZManaged @@ -1079,7 +1079,7 @@ Here is list of other deprecated methods: | `ZManaged#get` | `ZManaged#some` | | `ZManaged#someOrElseM` | `ZManaged#someOrElseManaged` | | | | -| `ZManaged#asService` | `ZManaged#toServiceBuilder` | +| `ZManaged#asService` | `ZManaged#toLayer` | | `ZManaged.services` | `ZManaged.service` | | | | | `ZManaged.foreach_` | `ZManaged.foreachDiscard` | @@ -1427,7 +1427,7 @@ There is a slight change in the Clock service; the return value of the `currentD In ZIO 2.0, without changing any API, the _retrying_, _repetition_, and _scheduling_ logic moved into the `Clock` service. -Working with these three time-related APIs, always made us require `Clock` as our environment. So by moving these primitives into the `Clock` service, now we can directly call them via the `Clock` service. This change solves a common anti-pattern in ZIO 1.0, whereby a middleware that uses `Clock` via this retrying, repetition, or scheduling logic must provide the `Clock` service builder on every method invocation: +Working with these three time-related APIs, always made us require `Clock` as our environment. So by moving these primitives into the `Clock` service, now we can directly call them via the `Clock` service. This change solves a common anti-pattern in ZIO 1.0, whereby a middleware that uses `Clock` via this retrying, repetition, or scheduling logic must provide the `Clock` layer on every method invocation: ```scala mdoc:silent:nest trait Journal { @@ -1540,7 +1540,7 @@ object ZStateExample extends zio.ZIOAppDefault { _ <- Console.printLine(count) } yield count - def run = app.injectCustom(ZState.makeServiceBuilder(MyState(0))) + def run = app.injectCustom(ZState.makeLayer(MyState(0))) } ``` diff --git a/docs/howto/mock-services.md b/docs/howto/mock-services.md index 94ef13ea11c5..d582929f00aa 100644 --- a/docs/howto/mock-services.md +++ b/docs/howto/mock-services.md @@ -77,7 +77,7 @@ ZIO Test provides a framework for mocking your modules. ## Creating a mock service -We'll be assuming you've read about modules and service builders in the [contextual types][doc-contextual-types] guide. In the main sources we define the _service_, a module alias and _capability accessors_. In test sources we're defining the _mock object_ which extends `zio.test.mock.Mock` which holds _capability tags_ and _compose service builder_. +We'll be assuming you've read about modules and layers in the [contextual types][doc-contextual-types] guide. In the main sources we define the _service_, a module alias and _capability accessors_. In test sources we're defining the _mock object_ which extends `zio.test.mock.Mock` which holds _capability tags_ and _compose layer_. ```scala mdoc:silent // main sources @@ -124,7 +124,7 @@ object ExampleMock extends Mock[Example] { object Sink extends Sink[Any, String, Int, String, Int, List[Int]] object Stream extends Stream[Any, String, Int] - val compose: URServiceBuilder[Proxy, Example] = ??? + val compose: URLayer[Proxy, Example] = ??? } ``` @@ -144,7 +144,7 @@ We model input arguments according to following scheme: For overloaded methods we nest a list of numbered objects, each representing subsequent overloads. -Finally we need to define a _compose service builder_ that can create our environment from a `Proxy`. +Finally we need to define a _compose layer_ that can create our environment from a `Proxy`. A `Proxy` holds the mock state and serves predefined responses to calls. ```scala mdoc:invisible @@ -154,7 +154,7 @@ def withRuntime[R]: URIO[R, Runtime[R]] = ??? ```scala mdoc:silent import ExampleMock._ -val compose: URServiceBuilder[Proxy, Example] = +val compose: URLayer[Proxy, Example] = ZIO.serviceWithZIO[Proxy] { proxy => withRuntime[Any].map { rts => new Example.Service { @@ -172,12 +172,12 @@ val compose: URServiceBuilder[Proxy, Example] = def stream(a: Int) = rts.unsafeRun(proxy(Stream, a)) } } - }.toServiceBuilder + }.toLayer ``` > **Note:** The `withRuntime` helper is defined in `Mock`. It accesses the Runtime via `ZIO.runtime` and if you're on JS platform, it will replace the executor to an unyielding one. -A reference to this service builder is passed to _capability tags_ so it can be used to automatically build environment for composed expectations on +A reference to this layer is passed to _capability tags_ so it can be used to automatically build environment for composed expectations on multiple services. > **Note:** for non-effectful capabilities you need to unsafely run the final effect to satisfy the required interface. For `ZSink` you also need to map the error into a failed sink as demonstrated above. @@ -208,7 +208,7 @@ object AccountObserver { def runCommand() = ZIO.serviceWithZIO[AccountObserver](_.runCommand()) - val live: ZServiceBuilder[Console, Nothing, AccountObserver] = + val live: ZLayer[Console, Nothing, AccountObserver] = { (console: Console) => new Service { def processEvent(event: AccountEvent): UIO[Unit] = @@ -221,7 +221,7 @@ object AccountObserver { def runCommand(): UIO[Unit] = console.printLine("Done!").orDie } - }.toServiceBuilder + }.toLayer } ``` @@ -233,13 +233,13 @@ object AccountObserverMock extends Mock[AccountObserver] { object ProcessEvent extends Effect[AccountEvent, Nothing, Unit] object RunCommand extends Effect[Unit, Nothing, Unit] - val compose: URServiceBuilder[Proxy, AccountObserver] = + val compose: URLayer[Proxy, AccountObserver] = ZIO.service[Proxy].map { proxy => new AccountObserver.Service { def processEvent(event: AccountEvent) = proxy(ProcessEvent, event) def runCommand(): UIO[Unit] = proxy(RunCommand) } - }.toServiceBuilder + }.toLayer } ``` @@ -267,13 +267,13 @@ object Example { object ExampleMock extends Mock[Example.Service] { object ZeroArgs extends Effect[Unit, Nothing, Int] object SingleArg extends Effect[Int, Nothing, String] - val compose: URServiceBuilder[Proxy, Example.Service] = + val compose: URLayer[Proxy, Example.Service] = ZIO.service[Proxy].map { proxy => new Example.Service { def zeroArgs = proxy(ZeroArgs) def singleArg(arg1: Int) = proxy(SingleArg, arg1) } - }.toServiceBuilder + }.toLayer } ``` @@ -329,7 +329,7 @@ import zio.test._ val event = new AccountEvent {} val app: URIO[AccountObserver, Unit] = AccountObserver.processEvent(event) -val mockEnv: UServiceBuilder[Console] = ( +val mockEnv: ULayer[Console] = ( MockConsole.PrintLine(equalTo(s"Got $event"), unit) ++ MockConsole.ReadLine(value("42")) ++ MockConsole.PrintLine(equalTo("You entered: 42"), unit) @@ -361,7 +361,7 @@ object AccountObserverSpec extends DefaultRunnableSpec { ## Mocking unused collaborators -Often the dependency on a collaborator is only in some branches of the code. To test the correct behaviour of branches without depedencies, we still have to provide it to the environment, but we would like to assert it was never called. With the `Mock.empty` method you can obtain a `ZServiceBuilder` with an empty service (no calls expected). +Often the dependency on a collaborator is only in some branches of the code. To test the correct behaviour of branches without depedencies, we still have to provide it to the environment, but we would like to assert it was never called. With the `Mock.empty` method you can obtain a `ZLayer` with an empty service (no calls expected). ```scala mdoc:silent object MaybeConsoleSpec extends DefaultRunnableSpec { @@ -380,12 +380,12 @@ object MaybeConsoleSpec extends DefaultRunnableSpec { ## Mocking multiple collaborators -In some cases we have more than one collaborating service being called. You can create mocks for rich environments and as you enrich the environment by using _capability tags_ from another service, the underlying mocked service builder will be updated. +In some cases we have more than one collaborating service being called. You can create mocks for rich environments and as you enrich the environment by using _capability tags_ from another service, the underlying mocked layer will be updated. ```scala mdoc:silent import zio.test.mock.MockRandom -val combinedEnv: UServiceBuilder[Console with Random] = ( +val combinedEnv: ULayer[Console with Random] = ( MockConsole.PrintLine(equalTo("What is your name?"), unit) ++ MockConsole.ReadLine(value("Mike")) ++ MockRandom.NextInt(value(42)) ++ @@ -435,7 +435,7 @@ object PolyExampleMock extends Mock[PolyExample] { object PolyOutput extends Poly.Effect.Output[Int, Throwable] object PolyAll extends Poly.Effect.InputErrorOutput - val compose: URServiceBuilder[Proxy, PolyExample] = + val compose: URLayer[Proxy, PolyExample] = ZIO.serviceWithZIO[Proxy] { proxy => withRuntime[Any].map { rts => new PolyExample.Service { @@ -445,7 +445,7 @@ object PolyExampleMock extends Mock[PolyExample] { def polyAll[I: Tag, E: Tag, A: Tag](input: I) = proxy(PolyAll.of[I, E, A], input) } } - }.toServiceBuilder + }.toLayer } ``` diff --git a/docs/howto/test_effects.md b/docs/howto/test_effects.md index 3116fc90aced..27cb8b1f2c0c 100644 --- a/docs/howto/test_effects.md +++ b/docs/howto/test_effects.md @@ -365,8 +365,8 @@ trait LoggingService { def log(msg: String): ZIO[Any, Exception, Unit] } -val schedulingServiceBuilder: ZServiceBuilder[Clock with LoggingService, Nothing, SchedulingService] = - ZServiceBuilder.fromFunction { env => +val schedulingLayer: ZLayer[Clock with LoggingService, Nothing, SchedulingService] = + ZLayer.fromFunction { env => new SchedulingService { def schedule(promise: Promise[Unit, Int]): ZIO[Any, Exception, Boolean] = (ZIO.sleep(10.seconds) *> promise.succeed(1)) @@ -376,11 +376,11 @@ val schedulingServiceBuilder: ZServiceBuilder[Clock with LoggingService, Nothing } test("One can control time for failing effects too") { - val failingLogger = ZServiceBuilder.succeed(new LoggingService { + val failingLogger = ZLayer.succeed(new LoggingService { override def log(msg: String): ZIO[Any, Exception, Unit] = ZIO.fail(new Exception("BOOM")) }) - val partialServiceBuilder = (Clock.any ++ failingLogger) >>> schedulingServiceBuilder + val partialLayer = (Clock.any ++ failingLogger) >>> schedulingLayer val testCase = for { @@ -390,7 +390,7 @@ test("One can control time for failing effects too") { readRef <- promise.await result <- result.join } yield assert(1)(equalTo(readRef)) && assert(result)(fails(isSubtype[Exception](anything))) - testCase.provideSome[TestEnvironment](partialServiceBuilder) + testCase.provideSome[TestEnvironment](partialLayer) } ``` diff --git a/docs/resources/ecosystem/community/logstage.md b/docs/resources/ecosystem/community/logstage.md index 131a2d0782da..2bab1597aa72 100644 --- a/docs/resources/ecosystem/community/logstage.md +++ b/docs/resources/ecosystem/community/logstage.md @@ -61,11 +61,11 @@ object LogStageExample extends zio.App { _ <- f.join } yield () - val loggerServiceBuilder: UServiceBuilder[Has[LogIO2[IO]]] = - ZServiceBuilder.succeed(LogZIO.withFiberId(IzLogger())) + val loggerLayer: ULayer[Has[LogIO2[IO]]] = + ZLayer.succeed(LogZIO.withFiberId(IzLogger())) override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = - myApp.provide(loggerServiceBuilder).exitCode + myApp.provide(loggerLayer).exitCode } ``` diff --git a/docs/resources/ecosystem/community/quill.md b/docs/resources/ecosystem/community/quill.md index fec38545f487..149b72a08691 100644 --- a/docs/resources/ecosystem/community/quill.md +++ b/docs/resources/ecosystem/community/quill.md @@ -88,6 +88,6 @@ object QuillZIOExample extends zio.App { override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = myApp - .provideCustom(DataSourceServiceBuilder.fromPrefix("myH2DB")) + .provideCustom(DataSourceLayer.fromPrefix("myH2DB")) .exitCode } diff --git a/docs/resources/ecosystem/community/tamer.md b/docs/resources/ecosystem/community/tamer.md index f2808210017e..10ea00975b86 100644 --- a/docs/resources/ecosystem/community/tamer.md +++ b/docs/resources/ecosystem/community/tamer.md @@ -57,7 +57,7 @@ from = Instant.parse("2020-01-01T00:00:00.00Z"), tumblingStep = 5.days ) - .runWith(dbServiceBuilderFromEnvironment ++ tamer.kafkaConfigFromEnvironment) + .runWith(dbLayerFromEnvironment ++ tamer.kafkaConfigFromEnvironment) override final def run(args: List[String]): URIO[ZEnv, ExitCode] = program.exitCode diff --git a/docs/resources/ecosystem/community/tranzactio.md b/docs/resources/ecosystem/community/tranzactio.md index aa448ac5302f..f3e50b0c03b5 100644 --- a/docs/resources/ecosystem/community/tranzactio.md +++ b/docs/resources/ecosystem/community/tranzactio.md @@ -36,7 +36,7 @@ import org.h2.jdbcx.JdbcDataSource import zio.blocking.Blocking import zio.clock.Clock import zio.console.{Console, putStrLn} -import zio.{ExitCode, Has, URIO, ZIO, ZServiceBuilder, blocking} +import zio.{ExitCode, Has, URIO, ZIO, ZLayer, blocking} import javax.sql.DataSource @@ -81,8 +81,8 @@ object PersonQuery { } object services { - val datasource: ZServiceBuilder[Blocking, Throwable, Has[DataSource]] = - ZServiceBuilder.fromEffect( + val datasource: ZLayer[Blocking, Throwable, Has[DataSource]] = + ZLayer.fromEffect( blocking.effectBlocking { val ds = new JdbcDataSource ds.setURL(s"jdbc:h2:mem:mydb;DB_CLOSE_DELAY=10") @@ -92,7 +92,7 @@ object services { } ) - val database: ZServiceBuilder[Any, Throwable, doobie.Database.Database] = + val database: ZLayer[Any, Throwable, doobie.Database.Database] = (Blocking.live >>> datasource ++ Blocking.live ++ Clock.live) >>> Database.fromDatasource } ``` diff --git a/docs/resources/ecosystem/community/zio-aws-s3.md b/docs/resources/ecosystem/community/zio-aws-s3.md index af9a32a0db9e..284bba55529d 100644 --- a/docs/resources/ecosystem/community/zio-aws-s3.md +++ b/docs/resources/ecosystem/community/zio-aws-s3.md @@ -31,8 +31,8 @@ import scala.jdk.CollectionConverters._ object ZIOAWSS3Example extends zio.App { val BUCKET = "" - val awsEnv: ZServiceBuilder[S3AsyncClient, Throwable, AwsLink] = - AwsApp.ExtServiceBuilder.live >>> AwsApp.AwsLink.live + val awsEnv: ZLayer[S3AsyncClient, Throwable, AwsLink] = + AwsApp.ExtLayer.live >>> AwsApp.AwsLink.live val app: ZIO[Any, Throwable, Unit] = for { s3 <- AwsAgent.createClient(Region.US_WEST_2, "") diff --git a/docs/resources/ecosystem/community/zio-aws.md b/docs/resources/ecosystem/community/zio-aws.md index c5613aaab01f..f772c4a0c4df 100644 --- a/docs/resources/ecosystem/community/zio-aws.md +++ b/docs/resources/ecosystem/community/zio-aws.md @@ -11,8 +11,8 @@ The goal is to have access to all AWS functionality for cases when only simple, Key features of ZIO AWS: -- Common configuration service builder -- ZIO module service builder per AWS service +- Common configuration layer +- ZIO module layer per AWS service - Wrapper for all operations on all services - HTTP service implementations for functional Scala HTTP libraries, injected through ZIO’s module system - ZStream wrapper around paginated operations diff --git a/docs/resources/ecosystem/community/zio-grpc.md b/docs/resources/ecosystem/community/zio-grpc.md index 84c9158b871d..77173c41b860 100644 --- a/docs/resources/ecosystem/community/zio-grpc.md +++ b/docs/resources/ecosystem/community/zio-grpc.md @@ -121,7 +121,7 @@ object HelloWorldClient extends zio.App { _ <- putStrLn(r.message) } yield () - val clientServiceBuilder = + val clientLayer = GreeterClient.live( ZManagedChannel( ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext() @@ -129,7 +129,7 @@ object HelloWorldClient extends zio.App { ) override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = - myApp.provideCustom(clientServiceBuilder).exitCode + myApp.provideCustom(clientLayer).exitCode } ``` diff --git a/docs/resources/ecosystem/community/zio-kinesis.md b/docs/resources/ecosystem/community/zio-kinesis.md index 3650dbb5c6ff..f6ba7883bffa 100644 --- a/docs/resources/ecosystem/community/zio-kinesis.md +++ b/docs/resources/ecosystem/community/zio-kinesis.md @@ -31,7 +31,7 @@ import zio.logging.Logging import zio.{ExitCode, URIO, _} object ZIOKinesisConsumerExample extends zio.App { - val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = + val loggingLayer: ZLayer[Any, Nothing, Logging] = (Console.live ++ Clock.live) >>> Logging.console() >>> Logging.withRootLoggerName(getClass.getName) @@ -46,7 +46,7 @@ object ZIOKinesisConsumerExample extends zio.App { checkpointBatchSize = 1000L, checkpointDuration = 5.minutes )(record => putStrLn(s"Processing record $record")) - .provideCustom(Consumer.defaultEnvironment ++ loggingServiceBuilder) + .provideCustom(Consumer.defaultEnvironment ++ loggingLayer) .exitCode } ``` diff --git a/docs/resources/ecosystem/community/zio-slick-interop.md b/docs/resources/ecosystem/community/zio-slick-interop.md index 176745196beb..a6380816009f 100644 --- a/docs/resources/ecosystem/community/zio-slick-interop.md +++ b/docs/resources/ecosystem/community/zio-slick-interop.md @@ -31,7 +31,7 @@ import slick.jdbc.H2Profile.api._ import slick.jdbc.JdbcProfile import zio.console.Console import zio.interop.console.cats.putStrLn -import zio.{ExitCode, IO, URIO, ZEnvironment, ZIO, ZServiceBuilder} +import zio.{ExitCode, IO, URIO, ZEnvironment, ZIO, ZLayer} import scala.jdk.CollectionConverters._ @@ -61,8 +61,8 @@ object ItemsTable { } object SlickItemRepository { - val live: ZServiceBuilder[DatabaseProvider, Throwable, ItemRepository] = - ZServiceBuilder.fromServiceM { db => + val live: ZLayer[DatabaseProvider, Throwable, ItemRepository] = + ZLayer.fromServiceM { db => db.profile.flatMap { profile => import profile.api._ @@ -111,8 +111,8 @@ object Main extends zio.App { ).asJava ) - private val env: ZServiceBuilder[Any, Throwable, ItemRepository] = - (ZServiceBuilder.succeed(config) ++ ZServiceBuilder.succeed[JdbcProfile]( + private val env: ZLayer[Any, Throwable, ItemRepository] = + (ZLayer.succeed(config) ++ ZLayer.succeed[JdbcProfile]( slick.jdbc.H2Profile )) >>> DatabaseProvider.live >>> SlickItemRepository.live diff --git a/docs/resources/ecosystem/officials/zio-akka-cluster.md b/docs/resources/ecosystem/officials/zio-akka-cluster.md index b4f6407b7372..47aeacad5a92 100644 --- a/docs/resources/ecosystem/officials/zio-akka-cluster.md +++ b/docs/resources/ecosystem/officials/zio-akka-cluster.md @@ -33,7 +33,7 @@ import com.typesafe.config.{Config, ConfigFactory} import zio.akka.cluster.Cluster import zio.akka.cluster.sharding.{Entity, Sharding} import zio.console.putStrLn -import zio.{ExitCode, Has, Managed, Task, URIO, ZIO, ZServiceBuilder} +import zio.{ExitCode, Has, Managed, Task, URIO, ZIO, ZLayer} sealed trait Counter extends Product with Serializable case object Inc extends Counter @@ -59,8 +59,8 @@ case class CounterApp(port: String) { |} |""".stripMargin) - val actorSystem: ZServiceBuilder[Any, Throwable, Has[ActorSystem]] = - ZServiceBuilder.fromManaged( + val actorSystem: ZLayer[Any, Throwable, Has[ActorSystem]] = + ZLayer.fromManaged( Managed.make(Task(ActorSystem("CounterApp", config)))(sys => Task.fromFuture(_ => sys.terminate()).either ) @@ -71,11 +71,11 @@ case class CounterApp(port: String) { for { queue <- Cluster .clusterEvents(true) - .provideCustom(ZServiceBuilder.succeedMany(sys)) + .provideCustom(ZLayer.succeedMany(sys)) pubsub <- zio.akka.cluster.pubsub.PubSub .createPubSub[Int] - .provideCustom(ZServiceBuilder.succeedMany(sys)) + .provideCustom(ZLayer.succeedMany(sys)) liveUsersLogger <- pubsub .listen("LiveUsers") @@ -108,7 +108,7 @@ case class CounterApp(port: String) { } yield () cluster <- Sharding .start("CounterEntity", counterEntityLogic) - .provideCustom(ZServiceBuilder.succeedMany(sys)) + .provideCustom(ZLayer.succeedMany(sys)) _ <- cluster.send("LiveUsers", Inc) _ <- cluster.send("TotalRequests", Inc) diff --git a/docs/resources/ecosystem/officials/zio-kafka.md b/docs/resources/ecosystem/officials/zio-kafka.md index 797d54210be8..c10f3ca5e8b4 100644 --- a/docs/resources/ecosystem/officials/zio-kafka.md +++ b/docs/resources/ecosystem/officials/zio-kafka.md @@ -90,22 +90,22 @@ object ZIOKafkaProducerConsumerExample extends zio.App { producer .merge(consumer) .runDrain - .provideCustom(appServiceBuilder) + .provideCustom(appLayer) .exitCode - def producerServiceBuilder = ZServiceBuilder.fromManaged( + def producerLayer = ZLayer.fromManaged( Producer.make( settings = ProducerSettings(List("localhost:29092")) ) ) - def consumerServiceBuilder = ZServiceBuilder.fromManaged( + def consumerLayer = ZLayer.fromManaged( Consumer.make( ConsumerSettings(List("localhost:29092")).withGroupId("group") ) ) - def appServiceBuilder = producerServiceBuilder ++ consumerServiceBuilder + def appLayer = producerLayer ++ consumerLayer } ``` diff --git a/docs/resources/ecosystem/officials/zio-metrics.md b/docs/resources/ecosystem/officials/zio-metrics.md index 239a0dc15a08..c0cd8b2712ed 100644 --- a/docs/resources/ecosystem/officials/zio-metrics.md +++ b/docs/resources/ecosystem/officials/zio-metrics.md @@ -50,7 +50,7 @@ object ZIOMetricsExample extends scala.App { } yield s Runtime - .unsafeFromServiceBuilder( + .unsafeFromLayer( Registry.live ++ Exporters.live ++ Console.live ) .unsafeRun(myApp) diff --git a/docs/resources/ecosystem/officials/zio-redis.md b/docs/resources/ecosystem/officials/zio-redis.md index bd24ba9832db..f7d8b06fc527 100644 --- a/docs/resources/ecosystem/officials/zio-redis.md +++ b/docs/resources/ecosystem/officials/zio-redis.md @@ -20,7 +20,7 @@ Since the ZIO Redis is in the experimental phase, it is not released yet. ## Example -To execute our ZIO Redis effect, we should provide the `RedisExecutor` service builder to that effect. To create this service builder we should also provide the following service builders: +To execute our ZIO Redis effect, we should provide the `RedisExecutor` layer to that effect. To create this layer we should also provide the following layers: - **Logging** — For simplicity, we ignored the logging functionality. - **RedisConfig** — Using default one, will connect to the `localhost:6379` Redis instance. @@ -33,7 +33,7 @@ import zio.logging.Logging import zio.redis._ import zio.redis.codec.StringUtf8Codec import zio.schema.codec.Codec -import zio.{ExitCode, URIO, ZIO, ZServiceBuilder} +import zio.{ExitCode, URIO, ZIO, ZLayer} object ZIORedisExample extends zio.App { @@ -46,11 +46,11 @@ object ZIORedisExample extends zio.App { _ <- sAdd("mySet", "a", "b", "a", "c") } yield () - val serviceBuilder: ZServiceBuilder[Any, RedisError.IOError, RedisExecutor] = - Logging.ignore ++ ZServiceBuilder.succeed(RedisConfig.Default) ++ ZServiceBuilder.succeed(StringUtf8Codec) >>> RedisExecutor.live + val layer: ZLayer[Any, RedisError.IOError, RedisExecutor] = + Logging.ignore ++ ZLayer.succeed(RedisConfig.Default) ++ ZLayer.succeed(StringUtf8Codec) >>> RedisExecutor.live override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = - myApp.provideCustom(serviceBuilder).exitCode + myApp.provideCustom(layer).exitCode } ``` diff --git a/docs/resources/ecosystem/officials/zio-sqs.md b/docs/resources/ecosystem/officials/zio-sqs.md index a39fe8bbff19..4de012a61a65 100644 --- a/docs/resources/ecosystem/officials/zio-sqs.md +++ b/docs/resources/ecosystem/officials/zio-sqs.md @@ -35,13 +35,13 @@ import zio.sqs.producer.{Producer, ProducerEvent} import zio.sqs.serialization.Serializer import zio.sqs.{SqsStream, SqsStreamSettings, Utils} import zio.stream.ZStream -import zio.{ExitCode, RIO, URIO, ZServiceBuilder, _} +import zio.{ExitCode, RIO, URIO, ZLayer, _} object ProducerConsumerExample extends zio.App { val queueName = "MyQueue" - val client: ZServiceBuilder[Any, Throwable, Sqs] = zioaws.netty.default ++ - ZServiceBuilder.succeed( + val client: ZLayer[Any, Throwable, Sqs] = zioaws.netty.default ++ + ZLayer.succeed( CommonAwsConfig( region = Some(Region.of("ap-northeast-2")), credentialsProvider = StaticCredentialsProvider.create( diff --git a/docs/resources/ecosystem/officials/zio-telemetry.md b/docs/resources/ecosystem/officials/zio-telemetry.md index 0ece25c65946..bca6c4304fe0 100644 --- a/docs/resources/ecosystem/officials/zio-telemetry.md +++ b/docs/resources/ecosystem/officials/zio-telemetry.md @@ -81,21 +81,21 @@ lazy val openTracingExample = Seq( ) ``` -Let's create a `ZServiceBuilder` for `OpenTracing` which provides us Jaeger tracer. Each microservice uses this dependency to send its tracing data to the _Jaeger Backend_: +Let's create a `ZLayer` for `OpenTracing` which provides us Jaeger tracer. Each microservice uses this dependency to send its tracing data to the _Jaeger Backend_: ```scala import io.jaegertracing.Configuration import io.jaegertracing.internal.samplers.ConstSampler import io.jaegertracing.zipkin.ZipkinV2Reporter import org.apache.http.client.utils.URIBuilder -import zio.ZServiceBuilder +import zio.ZLayer import zio.clock.Clock import zio.telemetry.opentracing.OpenTracing import zipkin2.reporter.AsyncReporter import zipkin2.reporter.okhttp3.OkHttpSender object JaegerTracer { - def makeJaegerTracer(host: String, serviceName: String): ZServiceBuilder[Clock, Throwable, Clock with OpenTracing] = + def makeJaegerTracer(host: String, serviceName: String): ZLayer[Clock, Throwable, Clock with OpenTracing] = OpenTracing.live(new Configuration(serviceName) .getTracerBuilder .withSampler(new ConstSampler(true)) diff --git a/examples/shared/src/main/scala-2/zio/examples/macros/AccessibleMacroExample.scala b/examples/shared/src/main/scala-2/zio/examples/macros/AccessibleMacroExample.scala index 5ce842161743..655e3aa04f6a 100644 --- a/examples/shared/src/main/scala-2/zio/examples/macros/AccessibleMacroExample.scala +++ b/examples/shared/src/main/scala-2/zio/examples/macros/AccessibleMacroExample.scala @@ -116,7 +116,7 @@ object AccessibleMacroExample { def withEx1(p: String): String } - val live: ZServiceBuilder[Console, Nothing, Service] = + val live: ZLayer[Console, Nothing, Service] = ZIO .service[Console] .map(console => @@ -139,7 +139,7 @@ object AccessibleMacroExample { def withEx1(p: String): String = throw new Exception("test") } ) - .toServiceBuilder + .toLayer // can use accessors even in the same compilation unit val program: URIO[ diff --git a/examples/shared/src/main/scala/zio/examples/InjectExample.scala b/examples/shared/src/main/scala/zio/examples/InjectExample.scala new file mode 100644 index 000000000000..988dcb6ff28c --- /dev/null +++ b/examples/shared/src/main/scala/zio/examples/InjectExample.scala @@ -0,0 +1,76 @@ +//package zio.examples +// +//import zio._ +//import java.io.IOException +// +//object ZLayerInjectExample extends ZIOAppDefault { +// val program: ZIO[OldLady with Console, IOException, Unit] = +// OldLady.contentsOfStomach.flatMap { contents => +// Console.printLine(s"There was an old who lady swallowed:\n- ${contents.mkString("\n- ")}") +// } +// +// val autoLayer: ZLayer[Any, Nothing, OldLady] = +// ZLayer.wire[OldLady]( +// OldLady.live, +// Spider.live, +// Fly.live, +// Bear.live, +// Console.live +// ) +// +// def run: ZIO[Any, IOException, Unit] = +// program +// .inject(OldLady.live, Spider.live, Fly.live, Bear.live, Console.live, ZLayer.Debug.tree) +// +// trait OldLady { +// def contentsOfStomach: UIO[List[String]] +// } +// +// object OldLady { +// def contentsOfStomach: ZIO[OldLady, Nothing, List[String]] = ZIO.serviceWithZIO(_.contentsOfStomach) +// +// def live: URLayer[Spider with Bear, OldLady] = +// ZLayer { +// for { +// spiderGuts <- Spider.contentsOfStomach +// } yield new OldLady { +// def contentsOfStomach: UIO[List[String]] = UIO("a Spdder" :: spiderGuts) +// } +// } +// } +// +// trait Spider { +// def contentsOfStomach: UIO[List[String]] +// } +// +// object Spider { +// def contentsOfStomach: ZIO[Spider, Nothing, List[String]] = ZIO.serviceWithZIO(_.contentsOfStomach) +// +// def live: URLayer[Fly, Spider] = +// ZLayer { +// for { +// _ <- ZIO.service[Fly] +// } yield new Spider { +// def contentsOfStomach: UIO[List[String]] = UIO(List("a Fly")) +// } +// } +// } +// +// trait Bear {} +// +// object Bear { +// def live: URLayer[Fly, Bear] = +// ZLayer.succeed(new Bear {}) +// } +// +// trait Fly {} +// +// object Fly { +// +// def live: URLayer[Console, Fly] = { +// println("FLY") +// +// Console.printLine("Bzzzzzzzzzz...").orDie.as(new Fly {}).toLayer +// } +// } +//} diff --git a/examples/shared/src/main/scala/zio/examples/ServiceBuilderDefinitionExample.scala b/examples/shared/src/main/scala/zio/examples/ServiceBuilderDefinitionExample.scala deleted file mode 100644 index a554f04a7acf..000000000000 --- a/examples/shared/src/main/scala/zio/examples/ServiceBuilderDefinitionExample.scala +++ /dev/null @@ -1,31 +0,0 @@ -// package zio.examples -// import zio._ - -// object ServiceBuilderDefinitionExample extends ZIOAppDefault { -// trait Foo { -// def bar: UIO[Unit] -// } - -// object Foo { -// val live: URServiceBuilder[Console with String with Int, Foo] = -// (FooLive.apply _).toServiceBuilder - -// case class FooLive(console: Console, string: String, int: Int) extends Foo { -// override def bar: UIO[Unit] = console.printLine(s"$string and $int").orDie -// } -// } - -// override def run: ZIO[ZEnv with ZIOAppArgs, Any, Any] = { - -// val program: ZIO[Foo, Nothing, Unit] = ZIO.serviceWith[Foo](_.bar) - -// program -// .inject( -// Console.live, -// ZServiceBuilder.succeed("Hello"), -// ZServiceBuilder.succeed(3), -// Foo.live -// ) -// } - -// } diff --git a/examples/shared/src/main/scala/zio/examples/ZServiceBuilderInjectExample.scala b/examples/shared/src/main/scala/zio/examples/ZServiceBuilderInjectExample.scala deleted file mode 100644 index 231f89beee35..000000000000 --- a/examples/shared/src/main/scala/zio/examples/ZServiceBuilderInjectExample.scala +++ /dev/null @@ -1,76 +0,0 @@ -// package zio.examples - -// import zio._ -// import java.io.IOException - -// object ZServiceBuilderInjectExample extends ZIOAppDefault { -// val program: ZIO[OldLady with Console, IOException, Unit] = -// OldLady.contentsOfStomach.flatMap { contents => -// Console.printLine(s"There was an old who lady swallowed:\n- ${contents.mkString("\n- ")}") -// } - -// val autoServiceBuilder: ZServiceBuilder[Any, Nothing, OldLady] = -// ZServiceBuilder.wire[OldLady]( -// OldLady.live, -// Spider.live, -// Fly.live, -// Bear.live, -// Console.live -// ) - -// def run: ZIO[Any, IOException, Unit] = -// program -// .inject(OldLady.live, Spider.live, Fly.live, Bear.live, Console.live, ZServiceBuilder.Debug.tree) - -// trait OldLady { -// def contentsOfStomach: UIO[List[String]] -// } - -// object OldLady { -// def contentsOfStomach: ZIO[OldLady, Nothing, List[String]] = ZIO.serviceWithZIO(_.contentsOfStomach) - -// def live: URServiceBuilder[Spider with Bear, OldLady] = -// ZServiceBuilder { -// for { -// spiderGuts <- Spider.contentsOfStomach -// } yield new OldLady { -// def contentsOfStomach: UIO[List[String]] = UIO("a Spdder" :: spiderGuts) -// } -// } -// } - -// trait Spider { -// def contentsOfStomach: UIO[List[String]] -// } - -// object Spider { -// def contentsOfStomach: ZIO[Spider, Nothing, List[String]] = ZIO.serviceWithZIO(_.contentsOfStomach) - -// def live: URServiceBuilder[Fly, Spider] = -// ZServiceBuilder { -// for { -// _ <- ZIO.service[Fly] -// } yield new Spider { -// def contentsOfStomach: UIO[List[String]] = UIO(List("a Fly")) -// } -// } -// } - -// trait Bear {} - -// object Bear { -// def live: URServiceBuilder[Fly, Bear] = -// ZServiceBuilder.succeed(new Bear {}) -// } - -// trait Fly {} - -// object Fly { - -// def live: URServiceBuilder[Console, Fly] = { -// println("FLY") - -// Console.printLine("Bzzzzzzzzzz...").orDie.as(new Fly {}).toServiceBuilder -// } -// } -// } diff --git a/examples/shared/src/test/scala/zio/examples/test/MockExampleSpec.scala b/examples/shared/src/test/scala/zio/examples/test/MockExampleSpec.scala index 2b4d2c5a3d72..381e7815b2a8 100644 --- a/examples/shared/src/test/scala/zio/examples/test/MockExampleSpec.scala +++ b/examples/shared/src/test/scala/zio/examples/test/MockExampleSpec.scala @@ -26,11 +26,11 @@ object MockExampleSpec extends DefaultRunnableSpec { case false => Clock.nanoTime } - val clockServiceBuilder = MockClock.NanoTime(value(42L)).toServiceBuilder - val noCallToConsole = branchingProgram(false).inject(MockConsole.empty ++ clockServiceBuilder) + val clockLayer = MockClock.NanoTime(value(42L)).toLayer + val noCallToConsole = branchingProgram(false).inject(MockConsole.empty ++ clockLayer) - val consoleServiceBuilder = MockConsole.ReadLine(value("foo")).toServiceBuilder - val noCallToClock = branchingProgram(true).inject(MockClock.empty ++ consoleServiceBuilder) + val consoleLayer = MockConsole.ReadLine(value("foo")).toLayer + val noCallToClock = branchingProgram(true).inject(MockClock.empty ++ consoleLayer) assertM(noCallToConsole)(equalTo(42L)) *> assertM(noCallToClock)(equalTo("foo")) }, test("expect no call on multiple skipped branches") { @@ -43,14 +43,14 @@ object MockExampleSpec extends DefaultRunnableSpec { def composedBranchingProgram(p1: Boolean, p2: Boolean) = branchingProgram(p1) <*> branchingProgram(p2) - val clockServiceBuilder = (MockClock.NanoTime(value(42L)) andThen MockClock.NanoTime(value(42L))).toServiceBuilder + val clockLayer = (MockClock.NanoTime(value(42L)) andThen MockClock.NanoTime(value(42L))).toLayer val noCallToConsole = composedBranchingProgram(false, false) - .inject(MockConsole.empty ++ clockServiceBuilder) + .inject(MockConsole.empty ++ clockLayer) - val consoleServiceBuilder = - (MockConsole.ReadLine(value("foo")) andThen MockConsole.ReadLine(value("foo"))).toServiceBuilder + val consoleLayer = + (MockConsole.ReadLine(value("foo")) andThen MockConsole.ReadLine(value("foo"))).toLayer val noCallToClock = composedBranchingProgram(true, true) - .inject(MockClock.empty ++ consoleServiceBuilder) + .inject(MockClock.empty ++ consoleLayer) assertM(noCallToConsole)(equalTo((42L, 42L))) *> assertM(noCallToClock)(equalTo(("foo", "foo"))) }, diff --git a/examples/shared/src/test/scala/zio/examples/test/ZLayerInjectExampleSpec.scala b/examples/shared/src/test/scala/zio/examples/test/ZLayerInjectExampleSpec.scala new file mode 100644 index 000000000000..6801293731a5 --- /dev/null +++ b/examples/shared/src/test/scala/zio/examples/test/ZLayerInjectExampleSpec.scala @@ -0,0 +1,30 @@ +//package zio.examples.test +// +//import zio._ +//import zio.examples.ZLayerInjectExample.{Bear, Fly, OldLady, Spider} +//import zio.test.Assertion.anything +//import zio.test._ +// +//object ZLayerInjectExampleSpec extends DefaultRunnableSpec { +// +// private val exampleZio: ZIO[Console with OldLady, Nothing, Unit] = +// OldLady.contentsOfStomach.flatMap { contents => +// Console.printLine(s"There was an old who lady swallowed:\n- ${contents.mkString("\n- ")}").orDie +// } +// +// def spec: ZSpec[Environment, Failure] = +// suite("AutoLayerExampleSpec")( +// test("inject") { +// assertM(exampleZio)(anything) +// }.inject(Console.live, OldLady.live, Spider.live, Fly.live, Bear.live), +// test("injectCustom") { +// assertM(exampleZio)(anything) +// }.injectCustom(OldLady.live, Spider.live, Fly.live, Bear.live), +// test("injectShared") { +// assertM(exampleZio)(anything) +// }.injectShared(Console.live, OldLady.live, Spider.live, Fly.live, Bear.live), +// test("injectCustomShared") { +// assertM(exampleZio)(anything) +// }.injectCustomShared(OldLady.live, Spider.live, Fly.live, Bear.live) +// ) +//} diff --git a/examples/shared/src/test/scala/zio/examples/test/ZServiceBuilderInjectExampleSpec.scala b/examples/shared/src/test/scala/zio/examples/test/ZServiceBuilderInjectExampleSpec.scala deleted file mode 100644 index 720d0ba46e25..000000000000 --- a/examples/shared/src/test/scala/zio/examples/test/ZServiceBuilderInjectExampleSpec.scala +++ /dev/null @@ -1,30 +0,0 @@ -// package zio.examples.test - -// import zio._ -// import zio.examples.ZServiceBuilderInjectExample.{Bear, Fly, OldLady, Spider} -// import zio.test.Assertion.anything -// import zio.test._ - -// object ZServiceBuilderInjectExampleSpec extends DefaultRunnableSpec { - -// private val exampleZio: ZIO[Console with OldLady, Nothing, Unit] = -// OldLady.contentsOfStomach.flatMap { contents => -// Console.printLine(s"There was an old who lady swallowed:\n- ${contents.mkString("\n- ")}").orDie -// } - -// def spec: ZSpec[Environment, Failure] = -// suite("AutoServiceBuilderExampleSpec")( -// test("inject") { -// assertM(exampleZio)(anything) -// }.inject(Console.live, OldLady.live, Spider.live, Fly.live, Bear.live), -// test("injectCustom") { -// assertM(exampleZio)(anything) -// }.injectCustom(OldLady.live, Spider.live, Fly.live, Bear.live), -// test("injectShared") { -// assertM(exampleZio)(anything) -// }.injectShared(Console.live, OldLady.live, Spider.live, Fly.live, Bear.live), -// test("injectCustomShared") { -// assertM(exampleZio)(anything) -// }.injectCustomShared(OldLady.live, Spider.live, Fly.live, Bear.live) -// ) -// } diff --git a/macros-tests/shared/src/test/scala-2/zio/macros/AccessibleSpec.scala b/macros-tests/shared/src/test/scala-2/zio/macros/AccessibleSpec.scala index 0097c247e766..ee9cb9284a41 100644 --- a/macros-tests/shared/src/test/scala-2/zio/macros/AccessibleSpec.scala +++ b/macros-tests/shared/src/test/scala-2/zio/macros/AccessibleSpec.scala @@ -360,8 +360,8 @@ object AccessibleSpec extends DefaultRunnableSpec { def test(): Unit = throw new Exception("ups") } } - def serviceBuilder = ZServiceBuilder.succeed(new Module.Service {}) - assertM(Module.test().flip.inject(serviceBuilder))(hasField("message", _.getMessage, equalTo("ups"))) + def layer = ZLayer.succeed(new Module.Service {}) + assertM(Module.test().flip.inject(layer))(hasField("message", _.getMessage, equalTo("ups"))) } ) ) diff --git a/macros-tests/shared/src/test/scala-2/zio/macros/AccessibleSpecFlat.scala b/macros-tests/shared/src/test/scala-2/zio/macros/AccessibleSpecFlat.scala index aaafb0345a75..0013fea5e4b2 100644 --- a/macros-tests/shared/src/test/scala-2/zio/macros/AccessibleSpecFlat.scala +++ b/macros-tests/shared/src/test/scala-2/zio/macros/AccessibleSpecFlat.scala @@ -330,8 +330,8 @@ object AccessibleSpecFlat extends DefaultRunnableSpec { @throwing def test(): Unit = throw new Exception("ups") } - def serviceBuilder = ZServiceBuilder.succeed(new Module {}) - assertM(Module.test().flip.provide(serviceBuilder))(hasField("message", _.getMessage, equalTo("ups"))) + def layer = ZLayer.succeed(new Module {}) + assertM(Module.test().flip.provide(layer))(hasField("message", _.getMessage, equalTo("ups"))) } ) ) diff --git a/scalafix/input/src/main/scala/fix/ZManagedSpec.scala b/scalafix/input/src/main/scala/fix/ZManagedSpec.scala index db17b8ef9065..e97b33b043a3 100644 --- a/scalafix/input/src/main/scala/fix/ZManagedSpec.scala +++ b/scalafix/input/src/main/scala/fix/ZManagedSpec.scala @@ -1,3 +1,4 @@ +//format: off /* rule = Zio2Upgrade */ diff --git a/scalafix/output/src/main/scala/fix/ZIOSpec.scala b/scalafix/output/src/main/scala/fix/ZIOSpec.scala index 2ff156e6aabc..a448684329e5 100644 --- a/scalafix/output/src/main/scala/fix/ZIOSpec.scala +++ b/scalafix/output/src/main/scala/fix/ZIOSpec.scala @@ -11,7 +11,7 @@ import zio.test._ import scala.annotation.tailrec import scala.util.{Failure, Success, Try} -import zio.{ Clock, FiberId, Random, Random, ZServiceBuilder, _ } +import zio.{ Clock, FiberId, Random, Random, _ } import zio.test.{ Gen, Live, Sized } object ZIOSpec extends DefaultRunnableSpec { @@ -1637,17 +1637,17 @@ object ZIOSpec extends DefaultRunnableSpec { ), suite("provideCustomLayer")( test("provides the part of the environment that is not part of the `ZEnv`") { - val loggingLayer: ZServiceBuilder[Any, Nothing, Logging] = Logging.live + val loggingLayer: ZLayer[Any, Nothing, Logging] = Logging.live val zio: ZIO[ZEnv with Logging, Nothing, Unit] = ZIO.unit - val zio2: URIO[ZEnv, Unit] = zio.provideCustomServices(loggingLayer) + val zio2: URIO[ZEnv, Unit] = zio.provideCustomLayer(loggingLayer) assertM(zio2)(anything) } ), suite("provideSomeLayer")( test("can split environment into two parts") { - val clockLayer: ZServiceBuilder[Any, Nothing, Clock] = Clock.live + val clockLayer: ZLayer[Any, Nothing, Clock] = Clock.live val zio: ZIO[Clock with Random, Nothing, Unit] = ZIO.unit - val zio2: URIO[Random, Unit] = zio.provideSomeServices[Random](clockLayer) + val zio2: URIO[Random, Unit] = zio.provideSomeLayer[Random](clockLayer) assertM(zio2)(anything) } ), @@ -3076,7 +3076,7 @@ object ZIOSpec extends DefaultRunnableSpec { suite("serviceWith")( test("effectfully accesses a service in the environment") { val zio = ZIO.serviceWith[Int](int => UIO(int + 3)) - assertM(zio.provideServices(ZServiceBuilder.succeed(0)))(equalTo(3)) + assertM(zio.provideLayer(ZLayer.succeed(0)))(equalTo(3)) } ), suite("schedule")( @@ -3359,7 +3359,7 @@ object ZIOSpec extends DefaultRunnableSpec { a <- ZIO.service[Int].updateService[Int](_ + 1) b <- ZIO.service[Int] } yield (a, b) - assertM(zio.provideServices(ZServiceBuilder.succeed(0)))(equalTo((1, 0))) + assertM(zio.provideLayer(ZLayer.succeed(0)))(equalTo((1, 0))) } ), suite("validate")( @@ -3795,6 +3795,6 @@ object ZIOSpec extends DefaultRunnableSpec { object Logging { trait Service - val live: ZServiceBuilder[Any, Nothing, Logging] = ZServiceBuilder.succeed(new Logging.Service {}) + val live: ZLayer[Any, Nothing, Logging] = ZLayer.succeed(new Logging.Service {}) } } diff --git a/scalafix/output/src/main/scala/fix/ZManagedSpec.scala b/scalafix/output/src/main/scala/fix/ZManagedSpec.scala index 0d3720ab16db..ba28650d8b21 100644 --- a/scalafix/output/src/main/scala/fix/ZManagedSpec.scala +++ b/scalafix/output/src/main/scala/fix/ZManagedSpec.scala @@ -1,3 +1,5 @@ +//format: off + package zio import zio.Cause.Interrupt @@ -1225,16 +1227,16 @@ object ZManagedSpec extends DefaultRunnableSpec { ), suite("toLayer")( test("converts a managed effect to a layer") { - ZEnv.live.build.toServiceBuilder + ZEnv.live.build.toLayer ??? } ), suite("toLayerMany")( test("converts a managed effect to a layer") { val managed = ZEnv.live.build - val layer = managed.toServiceBuilderMany + val layer = managed.toLayerMany val zio1 = ZIO.environment[ZEnv] - val zio2 = zio1.provideServices(layer) + val zio2 = zio1.provideLayer(layer) assertM(zio2)(anything) } ), diff --git a/scalafix/rules/src/main/scala/fix/Zio2Upgrade.scala b/scalafix/rules/src/main/scala/fix/Zio2Upgrade.scala index 1fb481cd57bc..86720059e952 100644 --- a/scalafix/rules/src/main/scala/fix/Zio2Upgrade.scala +++ b/scalafix/rules/src/main/scala/fix/Zio2Upgrade.scala @@ -157,58 +157,56 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { normalizedRenames.flatMap(_.unapply(tree)).headOption } } - + val UniversalRenames = Renames(scopes, renames) val ZIORenames = Renames( List("zio.ZIO"), - Map("run" -> "exit", - "provideLayer" -> "provideServices", - "provideSomeLayer" -> "provideSomeServices", - "provideCustomLayer" -> "provideCustomServices", + Map( + "run" -> "exit" ) ) val STMRenames = Renames( List("zio.stm.ZSTM", "zio.stm.STM"), Map( - "collectAll_" -> "collectAllDiscard", - "foldM" -> "foldSTM", - "foreach_" -> "foreachDiscard", - "fromFunction" -> "access", - "fromFunctionM" -> "accessSTM", - "ifM" -> "ifSTM", - "loop_" -> "loopDiscard", - "partial" -> "attempt", - "replicateM" -> "replicateSTM", - "replicateM_" -> "replicateSTMDiscard", - "require" -> "someOrFail", - "unlessM" -> "unlessSTM", - "whenCaseM" -> "whenCaseSTM", - "whenM" -> "whenSTM", + "collectAll_" -> "collectAllDiscard", + "foldM" -> "foldSTM", + "foreach_" -> "foreachDiscard", + "fromFunction" -> "access", + "fromFunctionM" -> "accessSTM", + "ifM" -> "ifSTM", + "loop_" -> "loopDiscard", + "partial" -> "attempt", + "replicateM" -> "replicateSTM", + "replicateM_" -> "replicateSTMDiscard", + "require" -> "someOrFail", + "unlessM" -> "unlessSTM", + "whenCaseM" -> "whenCaseSTM", + "whenM" -> "whenSTM" ) ) - + val ScheduleRenames = Renames( List("zio.Schedule", "zio.stm.STM"), Map( - "addDelayM" -> "addDelayZIO", - "checkM" -> "checkZIO", - "contramapM" -> "contramapZIO", - "delayedM" -> "delayedZIO", - "dimapM" -> "dimapZIO", - "foldM" -> "foldZIO", - "mapM" -> "mapZIO", - "modifyDelayM" -> "modifyDelayZIO", - "reconsiderM" -> "reconsiderZIO", - "untilInputM" -> "untilInputZIO", - "untilOutputM" -> "untilOutputZIO", - "whileInputM" -> "whileInputZIO", - "whileOutputM" -> "whileOutputZIO", + "addDelayM" -> "addDelayZIO", + "checkM" -> "checkZIO", + "contramapM" -> "contramapZIO", + "delayedM" -> "delayedZIO", + "dimapM" -> "dimapZIO", + "foldM" -> "foldZIO", + "mapM" -> "mapZIO", + "modifyDelayM" -> "modifyDelayZIO", + "reconsiderM" -> "reconsiderZIO", + "untilInputM" -> "untilInputZIO", + "untilOutputM" -> "untilOutputZIO", + "whileInputM" -> "whileInputZIO", + "whileOutputM" -> "whileOutputZIO", "collectWhileM" -> "collectWhileZIO", "collectUntilM" -> "collectUntilZIO", - "recurWhileM" -> "recureWhileZIO", - "recurUntilM" -> "recureUntilZIO", + "recurWhileM" -> "recureWhileZIO", + "recurUntilM" -> "recureUntilZIO" ) ) @@ -234,25 +232,21 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { "rejectM" -> "rejectManaged", "run" -> "exit", "someOrElseM" -> "someOrElseManaged", - "toLayer" -> "toServiceBuilder", - "toLayerMany" -> "toServiceBuilderMany", "unlessM" -> "unlessManaged", "whenCaseM" -> "whenCaseManaged", "whenM" -> "whenManaged" ) ) - val FiberId_Old = SymbolMatcher.normalized("zio/Fiber.Id#") + val FiberId_Old = SymbolMatcher.normalized("zio/Fiber.Id#") - val Blocking_Old_Exact = SymbolMatcher.exact("zio/blocking/package.Blocking#") - - val FiberId_Old_Exact = SymbolMatcher.exact("zio/Fiber.Id#") + val Blocking_Old_Exact = SymbolMatcher.exact("zio/blocking/package.Blocking#") - val hasNormalized = SymbolMatcher.normalized("zio/Has#") - - + val FiberId_Old_Exact = SymbolMatcher.exact("zio/Fiber.Id#") - val newFiberId = Symbol("zio/FiberId#") + val hasNormalized = SymbolMatcher.normalized("zio/Has#") + + val newFiberId = Symbol("zio/FiberId#") def replaceSymbols(implicit doc: SemanticDocument) = Patch.replaceSymbols( // System @@ -306,40 +300,39 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { "zio.blocking.blocking" -> "zio.ZIO.blocking", "zio.blocking.blockingExecutor" -> "zio.ZIO.blockingExecutor", // Gen - "zio.test.Gen.anyInt" -> "zio.test.Gen.int", - "zio.test.Gen.anyString" -> "zio.test.Gen.string", - "zio.test.Gen.anyUnicodeChar" -> "zio.test.Gen.unicodeChar", - "zio.test.Gen.anyASCIIChar" -> "zio.test.Gen.asciiChar", - "zio.test.Gen.anyByte" -> "zio.test.Gen.byte", - "zio.test.Gen.anyChar" -> "zio.test.Gen.char", - "zio.test.Gen.anyDouble" -> "zio.test.Gen.double", - "zio.test.Gen.anyFloat" -> "zio.test.Gen.float", - "zio.test.Gen.anyHexChar" -> "zio.test.Gen.hexChar", - "zio.test.Gen.anyLong" -> "zio.test.Gen.long", - "zio.test.Gen.anyLowerHexChar" -> "zio.test.Gen.hexCharLower", - "zio.test.Gen.anyShort" -> "zio.test.Gen.short", - "zio.test.Gen.anyUpperHexChar" -> "zio.test.Gen.hexCharUpper", - "zio.test.Gen.anyASCIIString" -> "zio.test.Gen.asciiString", - "zio.test.Gen.anyUUID" -> "zio.test.Gen.uuid", - "zio.test.TimeVariants.anyDayOfWeek" -> "zio.test.Gen.dayOfWeek", + "zio.test.Gen.anyInt" -> "zio.test.Gen.int", + "zio.test.Gen.anyString" -> "zio.test.Gen.string", + "zio.test.Gen.anyUnicodeChar" -> "zio.test.Gen.unicodeChar", + "zio.test.Gen.anyASCIIChar" -> "zio.test.Gen.asciiChar", + "zio.test.Gen.anyByte" -> "zio.test.Gen.byte", + "zio.test.Gen.anyChar" -> "zio.test.Gen.char", + "zio.test.Gen.anyDouble" -> "zio.test.Gen.double", + "zio.test.Gen.anyFloat" -> "zio.test.Gen.float", + "zio.test.Gen.anyHexChar" -> "zio.test.Gen.hexChar", + "zio.test.Gen.anyLong" -> "zio.test.Gen.long", + "zio.test.Gen.anyLowerHexChar" -> "zio.test.Gen.hexCharLower", + "zio.test.Gen.anyShort" -> "zio.test.Gen.short", + "zio.test.Gen.anyUpperHexChar" -> "zio.test.Gen.hexCharUpper", + "zio.test.Gen.anyASCIIString" -> "zio.test.Gen.asciiString", + "zio.test.Gen.anyUUID" -> "zio.test.Gen.uuid", + "zio.test.TimeVariants.anyDayOfWeek" -> "zio.test.Gen.dayOfWeek", "zio.test.TimeVariants.anyFiniteDuration" -> "zio.test.Gen.finiteDuration", - "zio.test.TimeVariants.anyLocalDate" -> "zio.test.Gen.localDate", - "zio.test.TimeVariants.anyLocalTime" -> "zio.test.Gen.localTime", - "zio.test.TimeVariants.anyLocalDateTime" -> "zio.test.Gen.localDateTime", - "zio.test.TimeVariants.anyMonth" -> "zio.test.Gen.month", - "zio.test.TimeVariants.anyMonthDay" -> "zio.test.Gen.monthDay", + "zio.test.TimeVariants.anyLocalDate" -> "zio.test.Gen.localDate", + "zio.test.TimeVariants.anyLocalTime" -> "zio.test.Gen.localTime", + "zio.test.TimeVariants.anyLocalDateTime" -> "zio.test.Gen.localDateTime", + "zio.test.TimeVariants.anyMonth" -> "zio.test.Gen.month", + "zio.test.TimeVariants.anyMonthDay" -> "zio.test.Gen.monthDay", "zio.test.TimeVariants.anyOffsetDateTime" -> "zio.test.Gen.offsetDateTime", - "zio.test.TimeVariants.anyOffsetTime" -> "zio.test.Gen.offsetTime", - "zio.test.TimeVariants.anyPeriod" -> "zio.test.Gen.period", - "zio.test.TimeVariants.anyYear" -> "zio.test.Gen.year", - "zio.test.TimeVariants.anyYearMonth" -> "zio.test.Gen.yearMonth", - "zio.test.TimeVariants.anyZonedDateTime" -> "zio.test.Gen.zonedDateTime", - "zio.test.TimeVariants.anyZoneOffset" -> "zio.test.Gen.zoneOffset", - "zio.test.TimeVariants.anyZoneId" -> "zio.test.Gen.zoneId", + "zio.test.TimeVariants.anyOffsetTime" -> "zio.test.Gen.offsetTime", + "zio.test.TimeVariants.anyPeriod" -> "zio.test.Gen.period", + "zio.test.TimeVariants.anyYear" -> "zio.test.Gen.year", + "zio.test.TimeVariants.anyYearMonth" -> "zio.test.Gen.yearMonth", + "zio.test.TimeVariants.anyZonedDateTime" -> "zio.test.Gen.zonedDateTime", + "zio.test.TimeVariants.anyZoneOffset" -> "zio.test.Gen.zoneOffset", + "zio.test.TimeVariants.anyZoneId" -> "zio.test.Gen.zoneId", // App - "zio.App" -> "zio.ZIOAppDefault", - "zio.Executor.asEC" -> "zio.Executor.asExecutionContext", - "zio.ZLayer" -> "zio.ZServiceBuilder" + "zio.App" -> "zio.ZIOAppDefault", + "zio.Executor.asEC" -> "zio.Executor.asExecutionContext" ) val foreachParN = ParNRenamer("foreachPar", 3) @@ -351,7 +344,7 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { val mergeAllParN = ParNRenamer("mergeAllPar", 4) object BuiltInServiceFixer { // TODO Handle all built-in services? - + object ImporteeRenamer { def importeeRenames(implicit sdoc: SemanticDocument): PartialFunction[Tree, Option[Patch]] = List( @@ -367,18 +360,17 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { testClockMigrator, clockMigrator, sizedMigrator, - testLiveMigrator, - ).foldLeft(List[SymbolMatcher](hasNormalized)) { - case (serviceMatchers, serviceMigrator) => serviceMatchers ++ List(serviceMigrator.normalizedOld, serviceMigrator.normalizedOldService) - }.map[PartialFunction[Tree, Patch]] ( - symbolMatcher => { - case t@ImporteeNameOrRename(symbolMatcher(_) ) => Patch.removeImportee(t) - } - ).foldLeft[PartialFunction[Tree, Option[Patch]]]{case (_: Tree) => None}{ case (totalPatch, nextPatch) => (tree: Tree) => nextPatch.lift(tree).orElse(totalPatch(tree)) } + testLiveMigrator + ).foldLeft(List[SymbolMatcher](hasNormalized)) { case (serviceMatchers, serviceMigrator) => + serviceMatchers ++ List(serviceMigrator.normalizedOld, serviceMigrator.normalizedOldService) + }.map[PartialFunction[Tree, Patch]](symbolMatcher => { case t @ ImporteeNameOrRename(symbolMatcher(_)) => + Patch.removeImportee(t) + }).foldLeft[PartialFunction[Tree, Option[Patch]]] { case (_: Tree) => None } { case (totalPatch, nextPatch) => + (tree: Tree) => nextPatch.lift(tree).orElse(totalPatch(tree)) + } - def unapply(tree: Tree)(implicit sdoc: SemanticDocument): Option[Patch] = { + def unapply(tree: Tree)(implicit sdoc: SemanticDocument): Option[Patch] = importeeRenames.apply(tree) - } } private val testLiveMigrator = @@ -386,21 +378,21 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { private val sizedMigrator = ServiceMigrator(name = "Sized", oldPath = "zio/test/package.", newPath = "zio/test/") - + private val clockMigrator = ServiceMigrator(name = "Clock", oldPath = "zio/clock/environment/package.", newPath = "zio/") private val testClockMigrator = - ServiceMigrator(name = "TestClock", oldPath = "zio/test/environment/package.", newPath = "zio/test/") + ServiceMigrator(name = "TestClock", oldPath = "zio/test/environment/package.", newPath = "zio/test/") private val testConsoleMigrator = - ServiceMigrator(name = "TestConsole", oldPath = "zio/test/environment/package.", newPath = "zio/test/") - + ServiceMigrator(name = "TestConsole", oldPath = "zio/test/environment/package.", newPath = "zio/test/") + val testRandomMigrator = ServiceMigrator(name = "TestRandom", oldPath = "zio/test/environment/package.", newPath = "zio/test/") - private val testLoggerMigrator = - ServiceMigrator(name = "TestLogger", oldPath = "zio/test/package.", newPath = "zio/test/") + private val testLoggerMigrator = + ServiceMigrator(name = "TestLogger", oldPath = "zio/test/package.", newPath = "zio/test/") private val testAnnotationsMigrator = ServiceMigrator(name = "Annotations", oldPath = "zio/test/package.", newPath = "zio/test/") @@ -409,19 +401,26 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { ServiceMigrator(name = "TestSystem", oldPath = "zio/test/environment/package.", newPath = "zio/test/") private val testConfigMigrator = - ServiceMigrator(name = "TestConfig", oldPath = "zio/test/package.", newPath = "zio/test/") - + ServiceMigrator(name = "TestConfig", oldPath = "zio/test/package.", newPath = "zio/test/") + private val consoleMigrator = ServiceMigrator(name = "Console", oldPath = "zio/console/package.", newPath = "zio/") - case class ServiceMigrator(oldExact: SymbolMatcher, oldService: SymbolMatcher, newSymbol: Symbol, plainName: String, normalizedOld: SymbolMatcher, normalizedOldService: SymbolMatcher) { + case class ServiceMigrator( + oldExact: SymbolMatcher, + oldService: SymbolMatcher, + newSymbol: Symbol, + plainName: String, + normalizedOld: SymbolMatcher, + normalizedOldService: SymbolMatcher + ) { def unapply(tree: Tree)(implicit sdoc: SemanticDocument): Option[Patch] = { val partial: PartialFunction[Tree, Patch] = { - case t@oldService(Name(_)) => + case t @ oldService(Name(_)) => Patch.replaceTree(unwindSelect(t), plainName) + Patch.addGlobalImport(newSymbol) - case t@oldExact(Name(_)) => + case t @ oldExact(Name(_)) => Patch.addGlobalImport(newSymbol) + Patch.replaceTree(unwindSelect(t), plainName) } @@ -429,8 +428,8 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { } } object ServiceMigrator { - - def apply(name: String, oldPath: String, newPath: String): ServiceMigrator = { + + def apply(name: String, oldPath: String, newPath: String): ServiceMigrator = ServiceMigrator( SymbolMatcher.exact(oldPath + name + "#"), SymbolMatcher.exact(oldPath + name + ".Service#"), @@ -439,19 +438,17 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { SymbolMatcher.normalized(oldPath + name + "#"), SymbolMatcher.normalized(oldPath + name + ".Service#") ) - } } - + private val randomMigrator = ServiceMigrator(name = "Random", oldPath = "zio/random/package.", newPath = "zio/") - + private val systemMigrator = ServiceMigrator(name = "System", oldPath = "zio/system/package.", newPath = "zio/") - + def unapply(tree: Tree)(implicit sdoc: SemanticDocument): Option[Patch] = { val partial: PartialFunction[Tree, Patch] = { case t @ Type.Apply(tpe: Type, args: List[Type]) if hasNormalized.matches(tpe.symbol) => - val builtInServices: Seq[SymbolMatcher] = List( randomMigrator, @@ -466,9 +463,9 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { testClockMigrator, clockMigrator, sizedMigrator, - testLiveMigrator, - ).foldLeft(List.empty[SymbolMatcher]) { - case (serviceMatchers, serviceMigrator) => serviceMatchers ++ List(serviceMigrator.oldService, serviceMigrator.oldExact) + testLiveMigrator + ).foldLeft(List.empty[SymbolMatcher]) { case (serviceMatchers, serviceMigrator) => + serviceMatchers ++ List(serviceMigrator.oldService, serviceMigrator.oldExact) } if (builtInServices.exists(_.matches(args.head))) @@ -476,20 +473,20 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { else Patch.replaceTree(t, args.head.toString) - case randomMigrator(patch) => patch - case systemMigrator(patch) => patch - case consoleMigrator(patch) => patch - case testConfigMigrator(patch) => patch - case testSystemMigrator(patch) => patch + case randomMigrator(patch) => patch + case systemMigrator(patch) => patch + case consoleMigrator(patch) => patch + case testConfigMigrator(patch) => patch + case testSystemMigrator(patch) => patch case testAnnotationsMigrator(patch) => patch - case testConsoleMigrator(patch) => patch - case testRandomMigrator(patch) => patch - case testLoggerMigrator(patch) => patch - case testClockMigrator(patch) => patch - case sizedMigrator(patch) => patch - case testLiveMigrator(patch) => patch - - case t@q"zio.random.Random" => + case testConsoleMigrator(patch) => patch + case testRandomMigrator(patch) => patch + case testLoggerMigrator(patch) => patch + case testClockMigrator(patch) => patch + case sizedMigrator(patch) => patch + case testLiveMigrator(patch) => patch + + case t @ q"zio.random.Random" => Patch.replaceTree(t, "zio.Random") case t @ q"import zio.duration._" => @@ -511,10 +508,10 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { case ZIORenames.Matcher(patch) => patch case ZManagedRenames.Matcher(patch) => patch - case STMRenames.Matcher(patch) => patch - case ScheduleRenames.Matcher(patch) => patch + case STMRenames.Matcher(patch) => patch + case ScheduleRenames.Matcher(patch) => patch case UniversalRenames.Matcher(patch) => patch - + case BuiltInServiceFixer(patch) => patch // Replace >>= with flatMap. For some reason, this doesn't work with the @@ -542,12 +539,12 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { case t @ q"import zio.blocking._" => Patch.removeTokens(t.tokens) - + case t @ q"import zio.blocking.Blocking" => Patch.removeTokens(t.tokens) case t @ Blocking_Old_Exact(Name(_)) => - Patch.replaceTree(unwindSelect(t), s"Any") + Patch.replaceTree(unwindSelect(t), s"Any") case t @ FiberId_Old_Exact(Name(_)) => Patch.replaceTree(unwindSelect(t), "FiberId") + @@ -556,7 +553,7 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { case t @ q"import zio.console._" => Patch.replaceTree(t, "") + Patch.addGlobalImport(wildcardImport(q"zio.Console")) - + case t @ q"import zio.test.environment._" => Patch.removeTokens(t.tokens) @@ -570,26 +567,26 @@ class Zio2Upgrade extends SemanticRule("Zio2Upgrade") { case t @ q"zio.duration.Duration" => Patch.replaceTree(t, "zio.Duration") - + case t @ q"import zio.clock.Clock" => Patch.replaceTree(t, "import zio.Clock") - + case t @ q"zio.internal.Executor" => Patch.replaceTree(t, "zio.Executor") case t @ q"Platform.fromExecutor" => Patch.replaceTree(t, "RuntimeConfig.fromExecutor") - + case t @ q"zio.internal.Platform" => Patch.replaceTree(t, "zio.RuntimeConfig") case t @ q"zio.internal.Tracing" => Patch.replaceTree(t, "zio.internal.tracing.Tracing") - + case t @ q"import zio.internal.Tracing" => Patch.replaceTree(t, "import zio.internal.tracing.Tracing") - case t @ ImporteeNameOrRename( FiberId_Old(_)) => Patch.removeImportee(t) + case t @ ImporteeNameOrRename(FiberId_Old(_)) => Patch.removeImportee(t) }.asPatch + replaceSymbols diff --git a/streams-tests/shared/src/test/scala/zio/stream/ZStreamSpec.scala b/streams-tests/shared/src/test/scala/zio/stream/ZStreamSpec.scala index 1c39b91a4dc9..44ed146e3f16 100644 --- a/streams-tests/shared/src/test/scala/zio/stream/ZStreamSpec.scala +++ b/streams-tests/shared/src/test/scala/zio/stream/ZStreamSpec.scala @@ -2961,7 +2961,7 @@ object ZStreamSpec extends ZIOBaseSpec { ZStream .serviceWithZIO[A](_.live) - .provideCustom(ZServiceBuilder.succeed(new A { + .provideCustom(ZLayer.succeed(new A { override def live: UIO[Int] = UIO(10) })) .runCollect @@ -2976,7 +2976,7 @@ object ZStreamSpec extends ZIOBaseSpec { ZStream .serviceWithStream[A](_.live) - .provideCustom(ZServiceBuilder.succeed(new A { + .provideCustom(ZLayer.succeed(new A { override def live: ZStream[Any, Nothing, Int] = ZStream.fromIterable(numbers) })) diff --git a/streams/shared/src/main/scala-2/zio.stream/ZStreamVersionSpecific.scala b/streams/shared/src/main/scala-2/zio.stream/ZStreamVersionSpecific.scala index 15b4fe8e5275..2a0648be70c9 100644 --- a/streams/shared/src/main/scala-2/zio.stream/ZStreamVersionSpecific.scala +++ b/streams/shared/src/main/scala-2/zio.stream/ZStreamVersionSpecific.scala @@ -1,7 +1,7 @@ package zio.stream -import zio.internal.macros.ServiceBuilderMacros -import zio.{NeedsEnv, ZEnv, ZServiceBuilder} +import zio.internal.macros.LayerMacros +import zio.{NeedsEnv, ZEnv, ZLayer} private[stream] trait ZStreamVersionSpecific[-R, +E, +O] { self: ZStream[R, E, O] => @@ -13,36 +13,36 @@ private[stream] trait ZStreamVersionSpecific[-R, +E, +O] { self: ZStream[R, E, O * * {{{ * val stream: ZStream[OldLady with Console, Nothing, Unit] = ??? - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The ZEnv you use later will provide both Blocking to flyServiceBuilder and Console to stream - * val stream2 : ZStream[ZEnv, Nothing, Unit] = stream.injectCustom(oldLadyServiceBuilder, flyServiceBuilder) + * // The ZEnv you use later will provide both Blocking to flyLayer and Console to stream + * val stream2 : ZStream[ZEnv, Nothing, Unit] = stream.injectCustom(oldLadyLayer, flyLayer) * }}} */ - def injectCustom[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZStream[ZEnv, E1, O] = - macro ServiceBuilderMacros.injectSomeImpl[ZStream, ZEnv, R, E1, O] + def injectCustom[E1 >: E](layer: ZLayer[_, E1, _]*): ZStream[ZEnv, E1, O] = + macro LayerMacros.injectSomeImpl[ZStream, ZEnv, R, E1, O] /** * Splits the environment into two parts, assembling one part using the - * specified service builder and leaving the remainder `R0`. + * specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val managed: ZStream[Clock with Random, Nothing, Unit] = ??? * - * val managed2 = managed.injectSome[Random](clockServiceBuilder) + * val managed2 = managed.injectSome[Random](clockLayer) * }}} */ def injectSome[R0]: ProvideSomeStreamPartiallyApplied[R0, R, E, O] = new ProvideSomeStreamPartiallyApplied[R0, R, E, O](self) /** - * Automatically assembles a service builder for the ZStream effect. + * Automatically assembles a layer for the ZStream effect. */ - def inject[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZStream[Any, E1, O] = - macro ServiceBuilderMacros.injectImpl[ZStream, R, E1, O] + def inject[E1 >: E](layer: ZLayer[_, E1, _]*): ZStream[Any, E1, O] = + macro LayerMacros.injectImpl[ZStream, R, E1, O] } @@ -50,10 +50,10 @@ private final class ProvideSomeStreamPartiallyApplied[R0, -R, +E, +O]( val self: ZStream[R, E, O] ) extends AnyVal { def provide[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R]): ZStream[R0, E1, O] = - self.provide(serviceBuilder) + self.provide(layer) - def apply[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): ZStream[R0, E1, O] = - macro ServiceBuilderMacros.injectSomeImpl[ZStream, R0, R, E1, O] + def apply[E1 >: E](layer: ZLayer[_, E1, _]*): ZStream[R0, E1, O] = + macro LayerMacros.injectSomeImpl[ZStream, R0, R, E1, O] } diff --git a/streams/shared/src/main/scala-3/zio.stream/ZStreamVersionSpecific.scala b/streams/shared/src/main/scala-3/zio.stream/ZStreamVersionSpecific.scala index 66a33a85332a..aeccf9c7c88e 100644 --- a/streams/shared/src/main/scala-3/zio.stream/ZStreamVersionSpecific.scala +++ b/streams/shared/src/main/scala-3/zio.stream/ZStreamVersionSpecific.scala @@ -1,7 +1,7 @@ package zio.stream -import zio.{ZServiceBuilder, ZEnv} -import zio.internal.macros.ServiceBuilderMacros +import zio.{ZLayer, ZEnv} +import zio.internal.macros.LayerMacros trait ZStreamVersionSpecific[-R, +E, +O] { self: ZStream[R, E, O] => /** @@ -11,30 +11,30 @@ trait ZStreamVersionSpecific[-R, +E, +O] { self: ZStream[R, E, O] => * * {{{ * val stream: ZStream[OldLady with Console, Nothing, Unit] = ??? - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The ZEnv you use later will provide both Blocking to flyServiceBuilder and Console to stream - * val stream2 : ZStream[ZEnv, Nothing, Unit] = stream.injectCustom(oldLadyServiceBuilder, flyServiceBuilder) + * // The ZEnv you use later will provide both Blocking to flyLayer and Console to stream + * val stream2 : ZStream[ZEnv, Nothing, Unit] = stream.injectCustom(oldLadyLayer, flyLayer) * }}} */ - inline def injectCustom[E1 >: E](inline serviceBuilder: ZServiceBuilder[_,E1,_]*): ZStream[ZEnv, E1, O] = - ${ZStreamProvideMacro.injectImpl[ZEnv, R, E1, O]('self, 'serviceBuilder)} + inline def injectCustom[E1 >: E](inline layer: ZLayer[_,E1,_]*): ZStream[ZEnv, E1, O] = + ${ZStreamProvideMacro.injectImpl[ZEnv, R, E1, O]('self, 'layer)} /** - * Automatically assembles a service builder for the ZStream effect, + * Automatically assembles a layer for the ZStream effect, * which translates it to another level. */ - inline def inject[E1 >: E](inline serviceBuilder: ZServiceBuilder[_,E1,_]*): ZStream[Any, E1, O] = - ${ZStreamProvideMacro.injectImpl[Any, R, E1, O]('self, 'serviceBuilder)} + inline def inject[E1 >: E](inline layer: ZLayer[_,E1,_]*): ZStream[Any, E1, O] = + ${ZStreamProvideMacro.injectImpl[Any, R, E1, O]('self, 'layer)} } object ZStreamProvideMacro { import scala.quoted._ - def injectImpl[R0: Type, R: Type, E: Type, A: Type](zstream: Expr[ZStream[R,E,A]], serviceBuilder: Expr[Seq[ZServiceBuilder[_,E,_]]])(using Quotes): Expr[ZStream[R0,E,A]] = { - val serviceBuilderExpr = ServiceBuilderMacros.fromAutoImpl[R0, R, E](serviceBuilder) - '{$zstream.provide($serviceBuilderExpr.asInstanceOf[ZServiceBuilder[R0,E,R]])} + def injectImpl[R0: Type, R: Type, E: Type, A: Type](zstream: Expr[ZStream[R,E,A]], layer: Expr[Seq[ZLayer[_,E,_]]])(using Quotes): Expr[ZStream[R0,E,A]] = { + val layerExpr = LayerMacros.fromAutoImpl[R0, R, E](layer) + '{$zstream.provide($layerExpr.asInstanceOf[ZLayer[R0,E,R]])} } } \ No newline at end of file diff --git a/streams/shared/src/main/scala/zio/stream/ZStream.scala b/streams/shared/src/main/scala/zio/stream/ZStream.scala index b249c013db9e..748e7315de6d 100644 --- a/streams/shared/src/main/scala/zio/stream/ZStream.scala +++ b/streams/shared/src/main/scala/zio/stream/ZStream.scala @@ -159,13 +159,13 @@ class ZStream[-R, +E, +A](val channel: ZChannel[R, Any, Any, Any, E, Chunk[A], A type SinkEndReason = ZStream.SinkEndReason[C] import ZStream.SinkEndReason._ - val serviceBuilder = + val layer = ZStream.Handoff.make[HandoffSignal] <*> Ref.make[SinkEndReason](SinkEnd) <*> Ref.make(Chunk[A1]()) <*> schedule.driver - ZStream.fromZIO(serviceBuilder).flatMap { case (handoff, sinkEndReason, sinkLeftovers, scheduleDriver) => + ZStream.fromZIO(layer).flatMap { case (handoff, sinkEndReason, sinkLeftovers, scheduleDriver) => lazy val handoffProducer: ZChannel[Any, E1, Chunk[A], Any, Nothing, Nothing, Any] = ZChannel.readWithCause( (in: Chunk[A]) => ZChannel.fromZIO(handoff.offer(Emit(in))) *> handoffProducer, @@ -2819,13 +2819,12 @@ class ZStream[-R, +E, +A](val channel: ZChannel[R, Any, Any, Any, E, Chunk[A], A new ZStream(self.channel >>> channel) /** - * Provides a service builder to the stream, which translates it to another - * level. + * Provides a layer to the stream, which translates it to another level. */ final def provide[E1 >: E, R0, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): ZStream[R0, E1, A] = - new ZStream(ZChannel.managed(serviceBuilder.build) { r => + new ZStream(ZChannel.managed(layer.build) { r => self.channel.provideEnvironment(r.upcast(ev)) }) @@ -2834,28 +2833,28 @@ class ZStream[-R, +E, +A](val channel: ZChannel[R, Any, Any, Any, E, Chunk[A], A * leaving a stream that only depends on the `ZEnv`. * * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val stream: ZStream[ZEnv with Logging, Nothing, Unit] = ??? * - * val stream2 = stream.provideCustom(loggingServiceBuilder) + * val stream2 = stream.provideCustom(loggingLayer) * }}} */ def provideCustom[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[ZEnv, E1, R1] + layer: ZLayer[ZEnv, E1, R1] )(implicit ev: ZEnv with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement ): ZStream[ZEnv, E1, A] = - provideSome[ZEnv](serviceBuilder) + provideSome[ZEnv](layer) /** * Provides the part of the environment that is not part of the `ZEnv`, * leaving a stream that only depends on the `ZEnv`. * * {{{ - * val loggingLayer: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val stream: ZStream[ZEnv with Logging, Nothing, Unit] = ??? * @@ -2864,7 +2863,7 @@ class ZStream[-R, +E, +A](val channel: ZChannel[R, Any, Any, Any, E, Chunk[A], A */ @deprecated("use provideCustom", "2.0.0") def provideCustomLayer[E1 >: E, R1]( - layer: ZServiceBuilder[ZEnv, E1, R1] + layer: ZLayer[ZEnv, E1, R1] )(implicit ev: ZEnv with R1 <:< R, tagged: Tag[R1], @@ -2872,28 +2871,6 @@ class ZStream[-R, +E, +A](val channel: ZChannel[R, Any, Any, Any, E, Chunk[A], A ): ZStream[ZEnv, E1, A] = provideSomeLayer[ZEnv](layer) - /** - * Provides the part of the environment that is not part of the `ZEnv`, - * leaving a stream that only depends on the `ZEnv`. - * - * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? - * - * val stream: ZStream[ZEnv with Logging, Nothing, Unit] = ??? - * - * val stream2 = stream.provideCustom(loggingServiceBuilder) - * }}} - */ - @deprecated("use provideCustom", "2.0.0") - def provideCustomServices[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[ZEnv, E1, R1] - )(implicit - ev: ZEnv with R1 <:< R, - tagged: Tag[R1], - trace: ZTraceElement - ): ZStream[ZEnv, E1, A] = - provideCustom(serviceBuilder) - /** * Provides the stream with its required environment, which eliminates its * dependency on `R`. @@ -2902,8 +2879,7 @@ class ZStream[-R, +E, +A](val channel: ZChannel[R, Any, Any, Any, E, Chunk[A], A new ZStream(channel.provideEnvironment(r)) /** - * Provides a service builder to the stream, which translates it to another - * level. + * Provides a layer to the stream, which translates it to another level. */ @deprecated("use provide", "2.0.0") final def provideLayer[E1 >: E, R0, R1]( @@ -2911,26 +2887,16 @@ class ZStream[-R, +E, +A](val channel: ZChannel[R, Any, Any, Any, E, Chunk[A], A )(implicit ev: R1 <:< R, trace: ZTraceElement): ZStream[R0, E1, A] = provide(layer) - /** - * Provides a service builder to the stream, which translates it to another - * level. - */ - @deprecated("use provide", "2.0.0") - final def provideServices[E1 >: E, R0, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] - )(implicit ev: R1 <:< R, trace: ZTraceElement): ZStream[R0, E1, A] = - provide(serviceBuilder) - /** * Splits the environment into two parts, providing one part using the - * specified service builder and leaving the remainder `R0`. + * specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val stream: ZStream[Clock with Random, Nothing, Unit] = ??? * - * val stream2 = stream.provideSome[Random](clockServiceBuilder) + * val stream2 = stream.provideSome[Random](clockLayer) * }}} */ final def provideSome[R0]: ZStream.ProvideSome[R0, R, E, A] = @@ -2963,22 +2929,6 @@ class ZStream[-R, +E, +A](val channel: ZChannel[R, Any, Any, Any, E, Chunk[A], A final def provideSomeLayer[R0]: ZStream.ProvideSome[R0, R, E, A] = provideSome - /** - * Splits the environment into two parts, providing one part using the - * specified service builder and leaving the remainder `R0`. - * - * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? - * - * val stream: ZStream[Clock with Random, Nothing, Unit] = ??? - * - * val stream2 = stream.provideSome[Random](clockServiceBuilder) - * }}} - */ - @deprecated("use provideSome", "2.0.0") - final def provideSomeServices[R0]: ZStream.ProvideSome[R0, R, E, A] = - provideSome - /** * Re-chunks the elements of the stream into chunks of `n` elements each. The * last chunk might contain less than `n` elements @@ -5258,10 +5208,10 @@ object ZStream extends ZStreamPlatformSpecificConstructors { def paginateM[R, E, A, S](s: S)(f: S => ZIO[R, E, (A, Option[S])])(implicit trace: ZTraceElement): ZStream[R, E, A] = paginateZIO(s)(f) - def provide[RIn, E, ROut, RIn2, ROut2](builder: ZServiceBuilder[RIn, E, ROut])( + def provide[RIn, E, ROut, RIn2, ROut2](builder: ZLayer[RIn, E, ROut])( stream: ZStream[ROut with RIn2, E, ROut2] )(implicit ev: Tag[RIn2], tag: Tag[ROut], trace: ZTraceElement): ZStream[RIn with RIn2, E, ROut2] = - stream.provideSomeServices[RIn with RIn2](ZServiceBuilder.environment[RIn2] ++ builder) + stream.provideSomeLayer[RIn with RIn2](ZLayer.environment[RIn2] ++ builder) /** * Like [[unfoldZIO]], but allows the emission of values to end one step @@ -5783,13 +5733,13 @@ object ZStream extends ZStreamPlatformSpecificConstructors { final class ProvideSome[R0, -R, +E, +A](private val self: ZStream[R, E, A]) extends AnyVal { def apply[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev: R0 with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement ): ZStream[R0, E1, A] = - self.provide[E1, R0, R0 with R1](ZServiceBuilder.environment[R0] ++ serviceBuilder) + self.provide[E1, R0, R0 with R1](ZLayer.environment[R0] ++ layer) } final class UpdateService[-R, +E, +A, M](private val self: ZStream[R, E, A]) extends AnyVal { diff --git a/test-sbt/js/src/main/scala/zio/test/sbt/ZTestRunner.scala b/test-sbt/js/src/main/scala/zio/test/sbt/ZTestRunner.scala index fef177bf6daf..696d1bfed3c6 100644 --- a/test-sbt/js/src/main/scala/zio/test/sbt/ZTestRunner.scala +++ b/test-sbt/js/src/main/scala/zio/test/sbt/ZTestRunner.scala @@ -18,7 +18,7 @@ package zio.test.sbt import sbt.testing._ import zio.test.{AbstractRunnableSpec, Summary, TestArgs, ZIOSpecAbstract, sbt} -import zio.{Chunk, Exit, Runtime, UIO, ZEnvironment, ZServiceBuilder, ZIO, ZIOAppArgs} +import zio.{Chunk, Exit, Runtime, UIO, ZEnvironment, ZLayer, ZIO, ZIOAppArgs} import scala.collection.mutable @@ -90,7 +90,7 @@ sealed class ZTestTask( case NewSpecWrapper(zioSpec) => Runtime(ZEnvironment.empty, zioSpec.runtime.runtimeConfig).unsafeRunAsyncWith { zioSpec.run - .provide(ZServiceBuilder.succeed(ZIOAppArgs(Chunk.empty)) ++ zio.ZEnv.live) + .provide(ZLayer.succeed(ZIOAppArgs(Chunk.empty)) ++ zio.ZEnv.live) .onError(e => UIO(println(e.prettyPrint))) } { exit => exit match { @@ -102,7 +102,7 @@ sealed class ZTestTask( case LegacySpecWrapper(abstractRunnableSpec) => Runtime(ZEnvironment.empty, abstractRunnableSpec.runtimeConfig).unsafeRunAsyncWith { run(eventHandler, abstractRunnableSpec).toManaged - .provide(sbtTestServiceBuilder(loggers)) + .provide(sbtTestLayer(loggers)) .useDiscard(ZIO.unit) } { exit => exit match { diff --git a/test-sbt/jvm/src/test/scala/zio/test/sbt/ZTestFrameworkSpec.scala b/test-sbt/jvm/src/test/scala/zio/test/sbt/ZTestFrameworkSpec.scala index debbea3b324b..60909d76c994 100644 --- a/test-sbt/jvm/src/test/scala/zio/test/sbt/ZTestFrameworkSpec.scala +++ b/test-sbt/jvm/src/test/scala/zio/test/sbt/ZTestFrameworkSpec.scala @@ -4,7 +4,7 @@ import sbt.testing._ import zio.test.Assertion.equalTo import zio.test.sbt.TestingSupport._ import zio.test.{assertCompletes, assert => _, test => _, _} -import zio.{ZEnvironment, ZIO, ZServiceBuilder, ZTraceElement, durationInt} +import zio.{ZEnvironment, ZIO, ZLayer, ZTraceElement, durationInt} import java.util.concurrent.atomic.AtomicInteger import java.util.regex.Pattern @@ -24,7 +24,7 @@ object ZTestFrameworkSpec { test("should correctly display colorized output for multi-line strings")(testColored()), test("should test only selected test")(testTestSelection()), test("should return summary when done")(testSummary()), - test("should use a shared service builder without re-initializing it")(testSharedServiceBuilder()), + test("should use a shared layer without re-initializing it")(testSharedLayer()), test("should warn when no tests are executed")(testNoTestsExecutedWarning()) ) @@ -120,8 +120,8 @@ object ZTestFrameworkSpec { private val counter = new AtomicInteger(0) - lazy val sharedServiceBuilder: ZServiceBuilder[Any, Nothing, Int] = { - ZServiceBuilder.fromZIO(ZIO.succeed(counter.getAndUpdate(value => value + 1))) + lazy val sharedLayer: ZLayer[Any, Nothing, Int] = { + ZLayer.fromZIO(ZIO.succeed(counter.getAndUpdate(value => value + 1))) } val randomFailure = @@ -133,9 +133,9 @@ object ZTestFrameworkSpec { // randomFailure } - lazy val spec1UsingSharedServiceBuilder = Spec1UsingSharedServiceBuilder.getClass.getName - object Spec1UsingSharedServiceBuilder extends zio.test.ZIOSpec[Int] { - override def serviceBuilder = sharedServiceBuilder + lazy val spec1UsingSharedLayer = Spec1UsingSharedLayer.getClass.getName + object Spec1UsingSharedLayer extends zio.test.ZIOSpec[Int] { + override def layer = sharedLayer /* TODO @@ -155,21 +155,21 @@ object ZTestFrameworkSpec { ) @@ TestAspect.parallel } - lazy val spec2UsingSharedServiceBuilder = Spec2UsingSharedServiceBuilder.getClass.getName - object Spec2UsingSharedServiceBuilder extends zio.test.ZIOSpec[Int] { - override def serviceBuilder = sharedServiceBuilder + lazy val spec2UsingSharedLayer = Spec2UsingSharedLayer.getClass.getName + object Spec2UsingSharedLayer extends zio.test.ZIOSpec[Int] { + override def layer = sharedLayer def spec = - zio.test.test("test completes with shared service builder 2") { + zio.test.test("test completes with shared layer 2") { assertCompletes } } - def testSharedServiceBuilder(): Unit = { + def testSharedLayer(): Unit = { val reported = ArrayBuffer[Event]() -// loadAndExecuteAll(Seq.fill(200)(spec2UsingSharedServiceBuilder), reported.append(_)) - loadAndExecuteAll(Seq.fill(2)(spec1UsingSharedServiceBuilder), reported.append(_)) +// loadAndExecuteAll(Seq.fill(200)(spec2UsingSharedLayer), reported.append(_)) + loadAndExecuteAll(Seq.fill(2)(spec1UsingSharedLayer), reported.append(_)) assert(counter.get() == 1) } diff --git a/test-sbt/native/src/main/scala/zio/test/sbt/ZTestRunner.scala b/test-sbt/native/src/main/scala/zio/test/sbt/ZTestRunner.scala index 807974211539..5413ffad3e99 100644 --- a/test-sbt/native/src/main/scala/zio/test/sbt/ZTestRunner.scala +++ b/test-sbt/native/src/main/scala/zio/test/sbt/ZTestRunner.scala @@ -18,7 +18,7 @@ package zio.test.sbt import sbt.testing._ import zio.test.{AbstractRunnableSpec, Summary, TestArgs, ZIOSpec, ZIOSpecAbstract, sbt} -import zio.{Chunk, Exit, Runtime, UIO, ZEnvironment, ZIO, ZIOAppArgs, ZServiceBuilder} +import zio.{Chunk, Exit, Runtime, UIO, ZEnvironment, ZIO, ZIOAppArgs, ZLayer} import scala.collection.mutable @@ -90,7 +90,7 @@ sealed class ZTestTask( case NewSpecWrapper(zioSpec) => Runtime(ZEnvironment.empty, zioSpec.runtime.runtimeConfig).unsafeRunAsyncWith { zioSpec.run - .provide(ZServiceBuilder.succeed(ZIOAppArgs(Chunk.empty)) ++ zio.ZEnv.live) + .provide(ZLayer.succeed(ZIOAppArgs(Chunk.empty)) ++ zio.ZEnv.live) .onError(e => UIO(println(e.prettyPrint))) } { exit => exit match { @@ -102,7 +102,7 @@ sealed class ZTestTask( case LegacySpecWrapper(abstractRunnableSpec) => Runtime(ZEnvironment.empty, abstractRunnableSpec.runtimeConfig).unsafeRunAsyncWith { run(eventHandler, abstractRunnableSpec).toManaged - .provide(sbtTestServiceBuilder(loggers)) + .provide(sbtTestLayer(loggers)) .useDiscard(ZIO.unit) } { exit => exit match { diff --git a/test-sbt/shared/src/main/scala/zio/test/sbt/BaseTestTask.scala b/test-sbt/shared/src/main/scala/zio/test/sbt/BaseTestTask.scala index 71f4cf46f9ab..c43a96d78026 100644 --- a/test-sbt/shared/src/main/scala/zio/test/sbt/BaseTestTask.scala +++ b/test-sbt/shared/src/main/scala/zio/test/sbt/BaseTestTask.scala @@ -10,19 +10,7 @@ import zio.test.{ TestEnvironment, ZIOSpecAbstract } -import zio.{ - Chunk, - Clock, - ServiceBuilder, - Runtime, - UIO, - UServiceBuilder, - ZEnvironment, - ZIO, - ZIOAppArgs, - ZServiceBuilder, - ZTraceElement -} +import zio.{Chunk, Clock, Layer, Runtime, UIO, ULayer, ZEnvironment, ZIO, ZIOAppArgs, ZLayer, ZTraceElement} abstract class BaseTestTask( val taskDef: TaskDef, @@ -48,35 +36,35 @@ abstract class BaseTestTask( eventHandler: EventHandler, spec: ZIOSpecAbstract )(implicit trace: ZTraceElement): ZIO[Any, Throwable, Unit] = { - val argsserviceBuilder: UServiceBuilder[ZIOAppArgs] = - ZServiceBuilder.succeed( + val argslayer: ULayer[ZIOAppArgs] = + ZLayer.succeed( ZIOAppArgs(Chunk.empty) ) - val filledTestserviceBuilder: ServiceBuilder[Nothing, TestEnvironment] = + val filledTestlayer: Layer[Nothing, TestEnvironment] = zio.ZEnv.live >>> TestEnvironment.live - val serviceBuilder: ServiceBuilder[Error, spec.Environment] = - (argsserviceBuilder +!+ filledTestserviceBuilder) >>> spec.serviceBuilder.mapError(e => new Error(e.toString)) + val layer: Layer[Error, spec.Environment] = + (argslayer +!+ filledTestlayer) >>> spec.layer.mapError(e => new Error(e.toString)) - val fullServiceBuilder: ServiceBuilder[Error, spec.Environment with ZIOAppArgs with TestEnvironment with zio.ZEnv] = - serviceBuilder +!+ argsserviceBuilder +!+ filledTestserviceBuilder + val fullLayer: Layer[Error, spec.Environment with ZIOAppArgs with TestEnvironment with zio.ZEnv] = + layer +!+ argslayer +!+ filledTestlayer for { spec <- spec .runSpec(FilteredSpec(spec.spec, args), args) .provide( - fullServiceBuilder + fullLayer ) events = ZTestEvent.from(spec, taskDef.fullyQualifiedName(), taskDef.fingerprint()) _ <- ZIO.foreach(events)(e => ZIO.attempt(eventHandler.handle(e))) } yield () } - protected def sbtTestServiceBuilder( + protected def sbtTestLayer( loggers: Array[Logger] - ): ServiceBuilder[Nothing, TestLogger with Clock] = - ZServiceBuilder.succeed[TestLogger](new TestLogger { + ): Layer[Nothing, TestLogger with Clock] = + ZLayer.succeed[TestLogger](new TestLogger { def logLine(line: String)(implicit trace: ZTraceElement): UIO[Unit] = ZIO.attempt(loggers.foreach(_.info(colored(line)))).ignore }) ++ Clock.live @@ -92,7 +80,7 @@ abstract class BaseTestTask( case LegacySpecWrapper(abstractRunnableSpec) => Runtime(ZEnvironment.empty, abstractRunnableSpec.runtimeConfig).unsafeRun { run(eventHandler, abstractRunnableSpec) - .provide(sbtTestServiceBuilder(loggers)) + .provide(sbtTestLayer(loggers)) .onError(e => UIO(println(e.prettyPrint))) } } diff --git a/test-tests/shared/src/test/scala/zio/test/AutoWireSpec.scala b/test-tests/shared/src/test/scala/zio/test/AutoWireSpec.scala index ca303f748cab..73067747b126 100644 --- a/test-tests/shared/src/test/scala/zio/test/AutoWireSpec.scala +++ b/test-tests/shared/src/test/scala/zio/test/AutoWireSpec.scala @@ -13,25 +13,25 @@ object AutoWireSpec extends ZIOBaseSpec { suite("AutoWireSpec")( suite("inject")( suite("meta-suite") { - val doubleServiceBuilder = ZServiceBuilder.succeed(100.1) - val stringServiceBuilder = ZServiceBuilder.succeed("this string is 28 chars long") - val intServiceBuilder = - ZServiceBuilder { + val doubleLayer = ZLayer.succeed(100.1) + val stringLayer = ZLayer.succeed("this string is 28 chars long") + val intLayer = + ZLayer { for { str <- ZIO.service[String] double <- ZIO.service[Double] } yield str.length + double.toInt } - test("automatically constructs a service builder") { + test("automatically constructs a layer") { val program = ZIO.environment[ZEnv] *> ZIO.service[Int] assertM(program)(equalTo(128)) - }.injectCustom(doubleServiceBuilder, stringServiceBuilder, intServiceBuilder) + }.injectCustom(doubleLayer, stringLayer, intLayer) }, test("reports missing top-level dependencies") { val program: URIO[String with Int, String] = UIO("test") val _ = program val checked = - typeCheck("""test("foo")(assertM(program)(anything)).inject(ZServiceBuilder.succeed(3))""") + typeCheck("""test("foo")(assertM(program)(anything)).inject(ZLayer.succeed(3))""") assertM(checked)(isLeft(containsStringWithoutAnsi("missing String"))) } @@ TestAspect.exceptDotty, test("reports multiple missing top-level dependencies") { @@ -44,20 +44,20 @@ object AutoWireSpec extends ZIOBaseSpec { ) } @@ TestAspect.exceptDotty, test("reports missing transitive dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URIO[OldLady, Boolean] = ZIO.service[OldLady].flatMap(_.willDie) val _ = program val checked = typeCheck("""test("foo")(assertM(program)(anything)).inject(OldLady.live)""") assertM(checked)( isLeft( - containsStringWithoutAnsi("missing zio.test.AutoWireSpec.TestServiceBuilder.Fly") && - containsStringWithoutAnsi("for TestServiceBuilder.OldLady.live") + containsStringWithoutAnsi("missing zio.test.AutoWireSpec.TestLayer.Fly") && + containsStringWithoutAnsi("for TestLayer.OldLady.live") ) ) } @@ TestAspect.exceptDotty, test("reports nested missing transitive dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URIO[OldLady, Boolean] = ZIO.service[OldLady].flatMap(_.willDie) val _ = program @@ -65,13 +65,13 @@ object AutoWireSpec extends ZIOBaseSpec { typeCheck("""test("foo")(assertM(program)(anything)).inject(OldLady.live, Fly.live)""") assertM(checked)( isLeft( - containsStringWithoutAnsi("missing zio.test.AutoWireSpec.TestServiceBuilder.Spider") && - containsStringWithoutAnsi("for TestServiceBuilder.Fly.live") + containsStringWithoutAnsi("missing zio.test.AutoWireSpec.TestLayer.Spider") && + containsStringWithoutAnsi("for TestLayer.Fly.live") ) ) } @@ TestAspect.exceptDotty, test("reports circular dependencies") { - import TestServiceBuilder._ + import TestLayer._ val program: URIO[OldLady, Boolean] = ZIO.service[OldLady].flatMap(_.willDie) val _ = program @@ -81,19 +81,19 @@ object AutoWireSpec extends ZIOBaseSpec { ) assertM(checked)( isLeft( - containsStringWithoutAnsi("TestServiceBuilder.Fly.manEatingFly") && + containsStringWithoutAnsi("TestLayer.Fly.manEatingFly") && containsStringWithoutAnsi( - "both requires and is transitively required by TestServiceBuilder.OldLady.live" + "both requires and is transitively required by TestLayer.OldLady.live" ) ) ) } @@ TestAspect.exceptDotty ), suite(".injectShared") { - val addOne = ZIO.service[Ref[Int]].flatMap(_.getAndUpdate(_ + 1)) - val refServiceBuilder = Ref.make(1).toServiceBuilder + val addOne = ZIO.service[Ref[Int]].flatMap(_.getAndUpdate(_ + 1)) + val refLayer = Ref.make(1).toLayer - suite("service builders are shared between tests and suites")( + suite("layers are shared between tests and suites")( suite("suite 1")( test("test 1")(assertM(addOne)(equalTo(1))), test("test 2")(assertM(addOne)(equalTo(2))) @@ -102,7 +102,7 @@ object AutoWireSpec extends ZIOBaseSpec { test("test 3")(assertM(addOne)(equalTo(3))), test("test 4")(assertM(addOne)(equalTo(4))) ) - ).injectShared(refServiceBuilder) @@ TestAspect.sequential + ).injectShared(refLayer) @@ TestAspect.sequential }, suite(".injectCustomShared") { case class IntService(ref: Ref[Int]) { @@ -115,9 +115,9 @@ object AutoWireSpec extends ZIOBaseSpec { .zip(Random.nextIntBounded(2)) .flatMap { case (ref, int) => ref.add(int) } - val refServiceBuilder: UServiceBuilder[IntService] = Ref.make(1).map(IntService(_)).toServiceBuilder + val refLayer: ULayer[IntService] = Ref.make(1).map(IntService(_)).toLayer - suite("service builders are shared between tests and suites")( + suite("layers are shared between tests and suites")( suite("suite 1")( test("test 1")(assertM(addOne)(equalTo(1))), test("test 2")(assertM(addOne)(equalTo(2))) @@ -126,14 +126,14 @@ object AutoWireSpec extends ZIOBaseSpec { test("test 3")(assertM(addOne)(equalTo(2))), test("test 4")(assertM(addOne)(equalTo(3))) ) - ).injectCustomShared(refServiceBuilder) @@ TestAspect.sequential + ).injectCustomShared(refLayer) @@ TestAspect.sequential } @@ TestAspect.exceptDotty, suite(".injectSomeShared") { val addOne = ZIO.service[Ref[Int]].zip(Random.nextIntBounded(2)).flatMap { case (ref, int) => ref.getAndUpdate(_ + int) } - val refServiceBuilder = Ref.make(1).toServiceBuilder + val refLayer = Ref.make(1).toLayer - suite("service builders are shared between tests and suites")( + suite("layers are shared between tests and suites")( suite("suite 1")( test("test 1")(assertM(addOne)(equalTo(1))), test("test 2")(assertM(addOne)(equalTo(2))) @@ -142,44 +142,44 @@ object AutoWireSpec extends ZIOBaseSpec { test("test 3")(assertM(addOne)(equalTo(2))), test("test 4")(assertM(addOne)(equalTo(3))) ) - ).injectSomeShared[Random](refServiceBuilder) @@ TestAspect.sequential + ).injectSomeShared[Random](refLayer) @@ TestAspect.sequential }, suite(".injectSome") { - test("automatically constructs a service builder, leaving off TestEnvironment") { + test("automatically constructs a layer, leaving off TestEnvironment") { for { result <- ZIO.service[String].zipWith(Random.nextInt)((str, int) => s"$str $int") } yield assertTrue(result == "Your Lucky Number is -1295463240") - }.injectSome[Random](ZServiceBuilder.succeed("Your Lucky Number is")) + }.injectSome[Random](ZLayer.succeed("Your Lucky Number is")) }, suite(".injectCustom") { - test("automatically constructs a service builder, leaving off TestEnvironment") { + test("automatically constructs a layer, leaving off TestEnvironment") { for { result <- ZIO.service[String].zipWith(Random.nextInt)((str, int) => s"$str $int") } yield assertTrue(result == "Your Lucky Number is -1295463240") - }.injectCustom(ZServiceBuilder.succeed("Your Lucky Number is")) + }.injectCustom(ZLayer.succeed("Your Lucky Number is")) } @@ TestAspect.exceptDotty ) - object TestServiceBuilder { + object TestLayer { trait OldLady { def willDie: UIO[Boolean] } object OldLady { - def live: URServiceBuilder[Fly, OldLady] = ZServiceBuilder.succeed(new OldLady { + def live: URLayer[Fly, OldLady] = ZLayer.succeed(new OldLady { override def willDie: UIO[Boolean] = UIO(false) }) } trait Fly {} object Fly { - def live: URServiceBuilder[Spider, Fly] = ZServiceBuilder.succeed(new Fly {}) - def manEatingFly: URServiceBuilder[OldLady, Fly] = ZServiceBuilder.succeed(new Fly {}) + def live: URLayer[Spider, Fly] = ZLayer.succeed(new Fly {}) + def manEatingFly: URLayer[OldLady, Fly] = ZLayer.succeed(new Fly {}) } trait Spider {} object Spider { - def live: UServiceBuilder[Spider] = ZServiceBuilder.succeed(new Spider {}) + def live: ULayer[Spider] = ZLayer.succeed(new Spider {}) } } } diff --git a/test-tests/shared/src/test/scala/zio/test/IntellijRendererSpec.scala b/test-tests/shared/src/test/scala/zio/test/IntellijRendererSpec.scala index 76075d939b66..76f836cef5f8 100644 --- a/test-tests/shared/src/test/scala/zio/test/IntellijRendererSpec.scala +++ b/test-tests/shared/src/test/scala/zio/test/IntellijRendererSpec.scala @@ -4,7 +4,7 @@ import zio.test.Assertion.equalTo import zio.test.ReportingTestUtils._ import zio.test.TestAspect.silent import zio.test.render.IntelliJRenderer -import zio.{Clock, ServiceBuilder, ZIO, ZTraceElement} +import zio.{Clock, Layer, ZIO, ZTraceElement} object IntellijRendererSpec extends ZIOBaseSpec { import IntelliJRenderUtils._ @@ -266,7 +266,7 @@ object IntelliJRenderUtils { } yield output.mkString private[this] def IntelliJTestRunner( - testEnvironment: ServiceBuilder[Nothing, TestEnvironment] + testEnvironment: Layer[Nothing, TestEnvironment] )(implicit trace: ZTraceElement) = TestRunner[TestEnvironment, String]( executor = TestExecutor.default[TestEnvironment, String](testEnvironment), diff --git a/test-tests/shared/src/test/scala/zio/test/ManagedSpec.scala b/test-tests/shared/src/test/scala/zio/test/ManagedSpec.scala index 2beab668768c..87bf51c556a9 100644 --- a/test-tests/shared/src/test/scala/zio/test/ManagedSpec.scala +++ b/test-tests/shared/src/test/scala/zio/test/ManagedSpec.scala @@ -12,7 +12,7 @@ object ManagedSpec extends ZIOBaseSpec { object Counter { - val live: ServiceBuilder[Nothing, Counter] = + val live: Layer[Nothing, Counter] = Ref .make(1) .toManagedWith(_.set(-10)) @@ -21,7 +21,7 @@ object ManagedSpec extends ZIOBaseSpec { val incrementAndGet: UIO[Int] = ref.updateAndGet(_ + 1) } } - .toServiceBuilder + .toLayer val incrementAndGet: URIO[Counter, Int] = ZIO.serviceWithZIO(_.incrementAndGet) diff --git a/test-tests/shared/src/test/scala/zio/test/ReportingTestUtils.scala b/test-tests/shared/src/test/scala/zio/test/ReportingTestUtils.scala index db41333560c3..2f6e4128145e 100644 --- a/test-tests/shared/src/test/scala/zio/test/ReportingTestUtils.scala +++ b/test-tests/shared/src/test/scala/zio/test/ReportingTestUtils.scala @@ -6,7 +6,7 @@ import zio.test.mock.internal.InvalidCall._ import zio.test.mock.internal.MockException._ import zio.test.mock.module.{PureModule, PureModuleMock} import zio.test.render.TestRenderer -import zio.{Cause, Clock, ServiceBuilder, Promise, ZIO, ZTraceElement} +import zio.{Cause, Clock, Layer, Promise, ZIO, ZTraceElement} import scala.{Console => SConsole} @@ -68,7 +68,7 @@ object ReportingTestUtils { actualSummary = SummaryBuilder.buildSummary(results) } yield actualSummary.summary - private[this] def TestTestRunner(testEnvironment: ServiceBuilder[Nothing, TestEnvironment])(implicit + private[this] def TestTestRunner(testEnvironment: Layer[Nothing, TestEnvironment])(implicit trace: ZTraceElement ) = TestRunner[TestEnvironment, String]( @@ -249,20 +249,20 @@ object ReportingTestUtils { withOffset(2)(s"""${red("- invalid repetition range 4 to 2 by -1")}\n""") ) - val mock5: ZSpec[Any, String] = test("Failing service builder") { + val mock5: ZSpec[Any, String] = test("Failing layer") { for { - promise <- Promise.make[Nothing, Unit] - failingServiceBuilder = (promise.await *> ZIO.fail("failed!")).toServiceBuilder[String] - mock = PureModuleMock.ZeroParams(value("mocked")).toServiceBuilder.tap { _ => + promise <- Promise.make[Nothing, Unit] + failingLayer = (promise.await *> ZIO.fail("failed!")).toLayer[String] + mock = PureModuleMock.ZeroParams(value("mocked")).toLayer.tap { _ => promise.succeed(()) } f = ZIO.serviceWithZIO[PureModule.Service](_.zeroParams) <* ZIO.service[String] - result <- f.provide(failingServiceBuilder ++ mock) + result <- f.provide(failingLayer ++ mock) } yield assert(result)(equalTo("mocked")) } val mock5Expected: Vector[String] = Vector( - """.*Failing service builder.*""", + """.*Failing layer.*""", """.*- unsatisfied expectations.*""", """\s*zio\.test\.mock\.module\.PureModuleMock\.ZeroParams with arguments.*""", """\s*Fiber failed\.""", diff --git a/test-tests/shared/src/test/scala/zio/test/SpecSpec.scala b/test-tests/shared/src/test/scala/zio/test/SpecSpec.scala index 2bee48985dcc..1e5f1b0fc547 100644 --- a/test-tests/shared/src/test/scala/zio/test/SpecSpec.scala +++ b/test-tests/shared/src/test/scala/zio/test/SpecSpec.scala @@ -7,8 +7,8 @@ import zio.test.TestUtils._ object SpecSpec extends ZIOBaseSpec { - val serviceBuilder: ZServiceBuilder[Any, Nothing, Unit] = - ZServiceBuilder.succeed(()) + val layer: ZLayer[Any, Nothing, Unit] = + ZLayer.succeed(()) def spec: Spec[TestEnvironment, TestFailure[Nothing], TestSuccess] = suite("SpecSpec")( suite("provideCustom")( @@ -17,14 +17,14 @@ object SpecSpec extends ZIOBaseSpec { _ <- ZIO.environment[TestEnvironment] _ <- ZIO.service[Unit] } yield assertCompletes - }.provideCustom(serviceBuilder) + }.provideCustom(layer) ), suite("provide")( test("does not have early initialization issues") { for { _ <- ZIO.service[Unit] } yield assertCompletes - }.provide(serviceBuilder) + }.provide(layer) ), suite("provideShared")( test("gracefully handles fiber death") { @@ -32,7 +32,7 @@ object SpecSpec extends ZIOBaseSpec { test("test") { assert(true)(isTrue) } - ).provideShared(ZServiceBuilder.fromZIOEnvironment(ZIO.dieMessage("everybody dies"))) + ).provideShared(ZLayer.fromZIOEnvironment(ZIO.dieMessage("everybody dies"))) for { _ <- execute(spec) } yield assertCompletes @@ -47,10 +47,10 @@ object SpecSpec extends ZIOBaseSpec { } ) for { - ref <- Ref.make(true) - serviceBuilder = ZServiceBuilder.fromZIO(ref.set(false).as(ref)) - _ <- execute(spec.provideCustomShared(serviceBuilder) @@ ifEnvSet("foo")) - result <- ref.get + ref <- Ref.make(true) + layer = ZLayer.fromZIO(ref.set(false).as(ref)) + _ <- execute(spec.provideCustomShared(layer) @@ ifEnvSet("foo")) + result <- ref.get } yield assert(result)(isTrue) }, test("is not interfered with by test level failures") { @@ -64,7 +64,7 @@ object SpecSpec extends ZIOBaseSpec { test("test3") { assertM(ZIO.service[Int])(Assertion.equalTo(42)) } - ).provideShared(ZServiceBuilder.succeed(43)) + ).provideShared(ZLayer.succeed(43)) for { executedSpec <- execute(spec) successes = executedSpec.fold[Int] { c => @@ -107,7 +107,7 @@ object SpecSpec extends ZIOBaseSpec { _ <- ref.update(_ + n) } yield assertCompletes } - ).provideSomeShared[TestEnvironment](serviceBuilder) @@ nondeterministic + ).provideSomeShared[TestEnvironment](layer) @@ nondeterministic _ <- execute(spec) result <- ref.get } yield assert(result)(hasSize(isGreaterThan(1))) @@ -126,16 +126,16 @@ object SpecSpec extends ZIOBaseSpec { output <- TestConsole.output } yield assert(output)(equalTo(Vector("Hello, World!\n"))) } - ).provideSomeShared[TestEnvironment](serviceBuilder) @@ silent + ).provideSomeShared[TestEnvironment](layer) @@ silent assertM(succeeded(spec))(isTrue) }, test("releases resources as soon as possible") { for { - ref <- Ref.make[List[String]](List.empty) - acquire = ref.update("Acquiring" :: _) - release = ref.update("Releasing" :: _) - update = ZIO.service[Ref[Int]].flatMap(_.updateAndGet(_ + 1)) - serviceBuilder = ZManaged.acquireReleaseWith(acquire *> Ref.make(0))(_ => release).toServiceBuilder + ref <- Ref.make[List[String]](List.empty) + acquire = ref.update("Acquiring" :: _) + release = ref.update("Releasing" :: _) + update = ZIO.service[Ref[Int]].flatMap(_.updateAndGet(_ + 1)) + layer = ZManaged.acquireReleaseWith(acquire *> Ref.make(0))(_ => release).toLayer spec = suite("spec")( suite("suite1")( test("test1") { @@ -144,7 +144,7 @@ object SpecSpec extends ZIOBaseSpec { test("test2") { assertM(update)(equalTo(2)) } - ).provideCustomShared(serviceBuilder), + ).provideCustomShared(layer), suite("suite2")( test("test1") { assertM(update)(equalTo(1)) @@ -152,7 +152,7 @@ object SpecSpec extends ZIOBaseSpec { test("test2") { assertM(update)(equalTo(2)) } - ).provideCustomShared(serviceBuilder) + ).provideCustomShared(layer) ) @@ sequential succeeded <- succeeded(spec) log <- ref.get.map(_.reverse) @@ -173,7 +173,7 @@ object SpecSpec extends ZIOBaseSpec { } ) ) - ).provideCustomShared(ZManaged.acquireReleaseWith(Ref.make(0))(_.set(-1)).toServiceBuilder) + ).provideCustomShared(ZManaged.acquireReleaseWith(Ref.make(0))(_.set(-1)).toLayer) assertM(succeeded(spec))(isTrue) } ) diff --git a/test-tests/shared/src/test/scala/zio/test/mock/ComposedMockSpec.scala b/test-tests/shared/src/test/scala/zio/test/mock/ComposedMockSpec.scala index 1c9434655c76..f73dda0ba068 100644 --- a/test-tests/shared/src/test/scala/zio/test/mock/ComposedMockSpec.scala +++ b/test-tests/shared/src/test/scala/zio/test/mock/ComposedMockSpec.scala @@ -11,7 +11,7 @@ object ComposedMockSpec extends ZIOBaseSpec { import Expectation._ private def testValueComposed[R1: Tag, E, A](name: String)( - mock: UServiceBuilder[R1], + mock: ULayer[R1], app: ZIO[R1, E, A], check: Assertion[A] ) = test(name) { diff --git a/test-tests/shared/src/test/scala/zio/test/mock/MockSpecUtils.scala b/test-tests/shared/src/test/scala/zio/test/mock/MockSpecUtils.scala index e7f3e2a5a951..17911b4620c0 100644 --- a/test-tests/shared/src/test/scala/zio/test/mock/MockSpecUtils.scala +++ b/test-tests/shared/src/test/scala/zio/test/mock/MockSpecUtils.scala @@ -10,7 +10,7 @@ trait MockSpecUtils[R] { (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22) private[mock] def testValue[E, A](name: String)( - mock: UServiceBuilder[R], + mock: ULayer[R], app: ZIO[R, E, A], check: Assertion[A] ): ZSpec[Any, E] = test(name) { @@ -19,7 +19,7 @@ trait MockSpecUtils[R] { } private[mock] def testError[E, A](name: String)( - mock: UServiceBuilder[R], + mock: ULayer[R], app: ZIO[R, E, A], check: Assertion[E] ): ZSpec[Any, A] = test(name) { @@ -28,7 +28,7 @@ trait MockSpecUtils[R] { } private[mock] def testValueTimeboxed[E, A](name: String)(duration: Duration)( - mock: UServiceBuilder[R], + mock: ULayer[R], app: ZIO[R, E, A], check: Assertion[Option[A]] ): ZSpec[Live, E] = test(name) { @@ -43,7 +43,7 @@ trait MockSpecUtils[R] { } private[mock] def testDied[E, A](name: String)( - mock: UServiceBuilder[R], + mock: ULayer[R], app: ZIO[R, E, A], check: Assertion[Throwable] ): ZSpec[Any, Any] = test(name) { diff --git a/test-tests/shared/src/test/scala/zio/test/mock/module/ImpureModuleMock.scala b/test-tests/shared/src/test/scala/zio/test/mock/module/ImpureModuleMock.scala index e7d66780f152..b2baa55018eb 100644 --- a/test-tests/shared/src/test/scala/zio/test/mock/module/ImpureModuleMock.scala +++ b/test-tests/shared/src/test/scala/zio/test/mock/module/ImpureModuleMock.scala @@ -2,7 +2,7 @@ package zio.test.mock.module import com.github.ghik.silencer.silent import zio.test.mock.{Mock, Proxy} -import zio.{Tag, URServiceBuilder, ZIO} +import zio.{Tag, URLayer, ZIO} /** * Example module used for testing ZIO Mock framework. @@ -36,7 +36,7 @@ object ImpureModuleMock extends Mock[ImpureModule] { object MaxParams extends Method[T22[Int], Throwable, String] - val compose: URServiceBuilder[Proxy, ImpureModule] = + val compose: URLayer[Proxy, ImpureModule] = ZIO .service[Proxy] .flatMap { proxy => @@ -96,5 +96,5 @@ object ImpureModuleMock extends Mock[ImpureModule] { } } } - .toServiceBuilder + .toLayer } diff --git a/test-tests/shared/src/test/scala/zio/test/mock/module/PureModuleMock.scala b/test-tests/shared/src/test/scala/zio/test/mock/module/PureModuleMock.scala index 83951757c21b..ad4d51bcc806 100644 --- a/test-tests/shared/src/test/scala/zio/test/mock/module/PureModuleMock.scala +++ b/test-tests/shared/src/test/scala/zio/test/mock/module/PureModuleMock.scala @@ -2,7 +2,7 @@ package zio.test.mock.module import com.github.ghik.silencer.silent import zio.test.mock.{Mock, Proxy} -import zio.{IO, Tag, UIO, URServiceBuilder, ZIO} +import zio.{IO, Tag, UIO, URLayer, ZIO} /** * Example pure module used for testing ZIO Mock framework. @@ -39,7 +39,7 @@ object PureModuleMock extends Mock[PureModule] { object MaxParams extends Effect[T22[Int], String, String] @silent("is never used") - val compose: URServiceBuilder[Proxy, PureModule] = + val compose: URLayer[Proxy, PureModule] = ZIO .service[Proxy] .flatMap { proxy => @@ -98,5 +98,5 @@ object PureModuleMock extends Mock[PureModule] { } } } - .toServiceBuilder + .toLayer } diff --git a/test-tests/shared/src/test/scala/zio/test/mock/module/StreamModuleMock.scala b/test-tests/shared/src/test/scala/zio/test/mock/module/StreamModuleMock.scala index b0ecb9046630..39437572a291 100644 --- a/test-tests/shared/src/test/scala/zio/test/mock/module/StreamModuleMock.scala +++ b/test-tests/shared/src/test/scala/zio/test/mock/module/StreamModuleMock.scala @@ -2,7 +2,7 @@ package zio.test.mock.module import zio.stream.ZSink import zio.test.mock.{Mock, Proxy} -import zio.{UIO, URServiceBuilder, ZIO} +import zio.{UIO, URLayer, ZIO} /** * Example module used for testing ZIO Mock framework. @@ -12,7 +12,7 @@ object StreamModuleMock extends Mock[StreamModule] { object Sink extends Sink[Any, String, Int, String, Nothing, List[Int]] object Stream extends Stream[Any, String, Int] - val compose: URServiceBuilder[Proxy, StreamModule] = + val compose: URLayer[Proxy, StreamModule] = ZIO .service[Proxy] .flatMap { proxy => @@ -24,5 +24,5 @@ object StreamModuleMock extends Mock[StreamModule] { } } } - .toServiceBuilder + .toLayer } diff --git a/test/shared/src/main/scala-2/zio/test/SpecLayerMacros.scala b/test/shared/src/main/scala-2/zio/test/SpecLayerMacros.scala new file mode 100644 index 000000000000..6a6cd91b0642 --- /dev/null +++ b/test/shared/src/main/scala-2/zio/test/SpecLayerMacros.scala @@ -0,0 +1,23 @@ +package zio.test + +import zio._ +import zio.internal.macros.LayerMacroUtils + +import scala.reflect.macros.blackbox + +class SpecLayerMacros(val c: blackbox.Context) extends LayerMacroUtils { + def injectSharedImpl[R: c.WeakTypeTag, E, A]( + layer: c.Expr[ZLayer[_, E, _]]* + ): c.Expr[Spec[Any, E, A]] = + injectBaseImpl[Spec, Any, R, E, A](layer, "provideShared") + + def injectCustomSharedImpl[R: c.WeakTypeTag, E, A]( + layer: c.Expr[ZLayer[_, E, _]]* + ): c.Expr[Spec[TestEnvironment, E, A]] = + injectBaseImpl[Spec, TestEnvironment, R, E, A](layer, "provideShared") + + def injectSomeSharedImpl[R0: c.WeakTypeTag, R: c.WeakTypeTag, E, A]( + layer: c.Expr[ZLayer[_, E, _]]* + ): c.Expr[Spec[R0, E, A]] = + injectBaseImpl[Spec, R0, R, E, A](layer, "provideShared") +} diff --git a/test/shared/src/main/scala-2/zio/test/SpecServiceBuilderMacros.scala b/test/shared/src/main/scala-2/zio/test/SpecServiceBuilderMacros.scala deleted file mode 100644 index 017c8d351a94..000000000000 --- a/test/shared/src/main/scala-2/zio/test/SpecServiceBuilderMacros.scala +++ /dev/null @@ -1,23 +0,0 @@ -package zio.test - -import zio._ -import zio.internal.macros.ServiceBuilderMacroUtils - -import scala.reflect.macros.blackbox - -class SpecServiceBuilderMacros(val c: blackbox.Context) extends ServiceBuilderMacroUtils { - def injectSharedImpl[R: c.WeakTypeTag, E, A]( - serviceBuilder: c.Expr[ZServiceBuilder[_, E, _]]* - ): c.Expr[Spec[Any, E, A]] = - injectBaseImpl[Spec, Any, R, E, A](serviceBuilder, "provideShared") - - def injectCustomSharedImpl[R: c.WeakTypeTag, E, A]( - serviceBuilder: c.Expr[ZServiceBuilder[_, E, _]]* - ): c.Expr[Spec[TestEnvironment, E, A]] = - injectBaseImpl[Spec, TestEnvironment, R, E, A](serviceBuilder, "provideShared") - - def injectSomeSharedImpl[R0: c.WeakTypeTag, R: c.WeakTypeTag, E, A]( - serviceBuilder: c.Expr[ZServiceBuilder[_, E, _]]* - ): c.Expr[Spec[R0, E, A]] = - injectBaseImpl[Spec, R0, R, E, A](serviceBuilder, "provideShared") -} diff --git a/test/shared/src/main/scala-2/zio/test/SpecVersionSpecific.scala b/test/shared/src/main/scala-2/zio/test/SpecVersionSpecific.scala index 90d8f099eea6..9402662b227d 100644 --- a/test/shared/src/main/scala-2/zio/test/SpecVersionSpecific.scala +++ b/test/shared/src/main/scala-2/zio/test/SpecVersionSpecific.scala @@ -1,16 +1,15 @@ package zio.test -import zio.{NeedsEnv, ZServiceBuilder} -import zio.internal.macros.ServiceBuilderMacros +import zio.{NeedsEnv, ZLayer} +import zio.internal.macros.LayerMacros private[test] trait SpecVersionSpecific[-R, +E, +T] { self: Spec[R, E, T] => /** - * Automatically assembles a service builder for the spec, translating it up a - * level. + * Automatically assembles a layer for the spec, translating it up a level. */ - def inject[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[Any, E1, T] = - macro ServiceBuilderMacros.injectImpl[Spec, R, E1, T] + def inject[E1 >: E](layer: ZLayer[_, E1, _]*): Spec[Any, E1, T] = + macro LayerMacros.injectImpl[Spec, R, E1, T] /** * Automatically constructs the part of the environment that is not part of @@ -21,38 +20,38 @@ private[test] trait SpecVersionSpecific[-R, +E, +T] { self: Spec[R, E, T] => * * {{{ * val spec: ZIO[UserRepo with Console, Nothing, Unit] = ??? - * val userRepoServiceBuilder: ZServiceBuilder[Database, Nothing, UserRepo = ??? - * val databaseServiceBuilder: ZServiceBuilder[Clock, Nothing, Database] = ??? + * val userRepoLayer: ZLayer[Database, Nothing, UserRepo = ??? + * val databaseLayer: ZLayer[Clock, Nothing, Database] = ??? * * // The TestEnvironment you use later will provide Clock to - * // `databaseServiceBuilder` and Console to `spec` + * // `databaseLayer` and Console to `spec` * val spec2 : ZIO[TestEnvironment, Nothing, Unit] = - * spec.injectCustom(userRepoServiceBuilder, databaseServiceBuilder) + * spec.injectCustom(userRepoLayer, databaseLayer) * }}} */ - def injectCustom[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[TestEnvironment, E1, T] = - macro ServiceBuilderMacros.injectSomeImpl[Spec, TestEnvironment, R, E1, T] + def injectCustom[E1 >: E](layer: ZLayer[_, E1, _]*): Spec[TestEnvironment, E1, T] = + macro LayerMacros.injectSomeImpl[Spec, TestEnvironment, R, E1, T] /** * Splits the environment into two parts, providing each test with one part - * using the specified service builder and leaving the remainder `R0`. + * using the specified layer and leaving the remainder `R0`. * * {{{ * val spec: ZSpec[Clock with Random, Nothing] = ??? - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * - * val spec2: ZSpec[Random, Nothing] = spec.injectSome[Random](clockServiceBuilder) + * val spec2: ZSpec[Random, Nothing] = spec.injectSome[Random](clockLayer) * }}} */ def injectSome[R0]: InjectSomePartiallyApplied[R0, R, E, T] = new InjectSomePartiallyApplied[R0, R, E, T](self) /** - * Automatically assembles a service builder for the spec, sharing services - * between all tests. + * Automatically assembles a layer for the spec, sharing services between all + * tests. */ - def injectShared[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[Any, E1, T] = - macro SpecServiceBuilderMacros.injectSharedImpl[R, E1, T] + def injectShared[E1 >: E](layer: ZLayer[_, E1, _]*): Spec[Any, E1, T] = + macro SpecLayerMacros.injectSharedImpl[R, E1, T] /** * Automatically constructs the part of the environment that is not part of @@ -64,28 +63,28 @@ private[test] trait SpecVersionSpecific[-R, +E, +T] { self: Spec[R, E, T] => * * {{{ * val spec: ZIO[UserRepo with Console, Nothing, Unit] = ??? - * val userRepoServiceBuilder: ZServiceBuilder[Database, Nothing, UserRepo = ??? - * val databaseServiceBuilder: ZServiceBuilder[Clock, Nothing, Database] = ??? + * val userRepoLayer: ZLayer[Database, Nothing, UserRepo = ??? + * val databaseLayer: ZLayer[Clock, Nothing, Database] = ??? * * // The TestEnvironment you use later will provide Clock to - * // `databaseServiceBuilder` and Console to `spec` + * // `databaseLayer` and Console to `spec` * val spec2 : ZIO[TestEnvironment, Nothing, Unit] = - * spec.injectCustomShared(userRepoServiceBuilder, databaseServiceBuilder) + * spec.injectCustomShared(userRepoLayer, databaseLayer) * }}} */ - def injectCustomShared[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[TestEnvironment, E1, T] = - macro SpecServiceBuilderMacros.injectCustomSharedImpl[R, E1, T] + def injectCustomShared[E1 >: E](layer: ZLayer[_, E1, _]*): Spec[TestEnvironment, E1, T] = + macro SpecLayerMacros.injectCustomSharedImpl[R, E1, T] /** * Splits the environment into two parts, providing all tests with a shared - * version of one part using the specified service builder and leaving the - * remainder `R0`. + * version of one part using the specified layer and leaving the remainder + * `R0`. * * {{{ * val spec: ZSpec[Int with Random, Nothing] = ??? - * val intServiceBuilder: ZServiceBuilder[Any, Nothing, Int] = ??? + * val intLayer: ZLayer[Any, Nothing, Int] = ??? * - * val spec2 = spec.injectSomeShared[Random](intServiceBuilder) + * val spec2 = spec.injectSomeShared[Random](intLayer) * }}} */ final def injectSomeShared[R0]: InjectSomeSharedPartiallyApplied[R0, R, E, T] = @@ -95,33 +94,33 @@ private[test] trait SpecVersionSpecific[-R, +E, +T] { self: Spec[R, E, T] => private final class InjectSomePartiallyApplied[R0, -R, +E, +T](val self: Spec[R, E, T]) extends AnyVal { def provide[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R]): Spec[R0, E1, T] = - self.provide(serviceBuilder) + self.provide(layer) @deprecated("use provide", "2.0.0") def provideLayer[E1 >: E, R1]( - layer: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R]): Spec[R0, E1, T] = provide(layer) - def apply[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[R0, E1, T] = - macro ServiceBuilderMacros.injectSomeImpl[Spec, R0, R, E1, T] + def apply[E1 >: E](layer: ZLayer[_, E1, _]*): Spec[R0, E1, T] = + macro LayerMacros.injectSomeImpl[Spec, R0, R, E1, T] } private final class InjectSomeSharedPartiallyApplied[R0, -R, +E, +T](val self: Spec[R, E, T]) extends AnyVal { def provideShared[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R]): Spec[R0, E1, T] = - self.provideShared(serviceBuilder) + self.provideShared(layer) @deprecated("use provideShared", "2.0.0") def provideLayerShared[E1 >: E, R1]( - layer: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev1: R1 <:< R, ev2: NeedsEnv[R]): Spec[R0, E1, T] = provideShared(layer) - def apply[E1 >: E](serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[R0, E1, T] = - macro SpecServiceBuilderMacros.injectSomeSharedImpl[R0, R, E1, T] + def apply[E1 >: E](layer: ZLayer[_, E1, _]*): Spec[R0, E1, T] = + macro SpecLayerMacros.injectSomeSharedImpl[R0, R, E1, T] } diff --git a/test/shared/src/main/scala-2/zio/test/mock/MockableMacro.scala b/test/shared/src/main/scala-2/zio/test/mock/MockableMacro.scala index 7efc2102d5fd..1f1dabcb6d20 100644 --- a/test/shared/src/main/scala-2/zio/test/mock/MockableMacro.scala +++ b/test/shared/src/main/scala-2/zio/test/mock/MockableMacro.scala @@ -49,7 +49,7 @@ private[mock] object MockableMacro { val any: Type = definitions.AnyTpe val throwable: Type = c.typecheck(q"(??? : _root_.java.lang.Throwable)").tpe val unit: Type = definitions.UnitTpe - val composeAsc: Tree = tq"_root_.zio.URServiceBuilder[_root_.zio.test.mock.Proxy, $env]" + val composeAsc: Tree = tq"_root_.zio.URLayer[_root_.zio.test.mock.Proxy, $env]" val taggedFcqns = List("izumi.reflect.Tag") def bound(tpe: Type): Tree = @@ -317,7 +317,7 @@ private[mock] object MockableMacro { } new $serviceClassName } - }.toServiceBuilder + }.toLayer ..$body } diff --git a/test/shared/src/main/scala-3/zio/test/SpecProvideServiceAutoMacros.scala b/test/shared/src/main/scala-3/zio/test/SpecProvideServiceAutoMacros.scala index 1b74d8a480e7..14a48850a617 100644 --- a/test/shared/src/main/scala-3/zio/test/SpecProvideServiceAutoMacros.scala +++ b/test/shared/src/main/scala-3/zio/test/SpecProvideServiceAutoMacros.scala @@ -1,20 +1,20 @@ package zio.test -import zio.internal.macros.ServiceBuilderMacroUtils._ +import zio.internal.macros.LayerMacroUtils._ import scala.quoted._ import zio.internal.macros._ import zio._ -object SpecServiceBuilderMacros { +object SpecLayerMacros { def injectImpl[R0: Type, R: Type, E: Type, T: Type] - (spec: Expr[Spec[R, E, T]], serviceBuilder: Expr[Seq[ZServiceBuilder[_,E,_]]])(using Quotes): Expr[Spec[R0, E, T]] = { - val expr = ServiceBuilderMacros.fromAutoImpl[R0, R, E](serviceBuilder).asInstanceOf[Expr[ZServiceBuilder[R0, E, R]]] + (spec: Expr[Spec[R, E, T]], layer: Expr[Seq[ZLayer[_,E,_]]])(using Quotes): Expr[Spec[R0, E, T]] = { + val expr = LayerMacros.fromAutoImpl[R0, R, E](layer).asInstanceOf[Expr[ZLayer[R0, E, R]]] '{$spec.provide($expr)} } def injectSharedImpl[R0: Type, R: Type, E: Type, T: Type] - (spec: Expr[Spec[R,E,T]], serviceBuilder: Expr[Seq[ZServiceBuilder[_,E,_]]])(using Quotes): Expr[Spec[R0,E,T]] = { - val expr = ServiceBuilderMacros.fromAutoImpl[R0, R, E](serviceBuilder) + (spec: Expr[Spec[R,E,T]], layer: Expr[Seq[ZLayer[_,E,_]]])(using Quotes): Expr[Spec[R0,E,T]] = { + val expr = LayerMacros.fromAutoImpl[R0, R, E](layer) '{$spec.provideShared($expr)} } } diff --git a/test/shared/src/main/scala-3/zio/test/SpecVersionSpecific.scala b/test/shared/src/main/scala-3/zio/test/SpecVersionSpecific.scala index 7487f103fd38..a83ce92cebf1 100644 --- a/test/shared/src/main/scala-3/zio/test/SpecVersionSpecific.scala +++ b/test/shared/src/main/scala-3/zio/test/SpecVersionSpecific.scala @@ -1,15 +1,15 @@ package zio.test -import zio.{ZIO, ZServiceBuilder} +import zio.{ZIO, ZLayer} trait SpecVersionSpecific[-R, +E, +T] { self: Spec[R, E, T] => /** - * Automatically assembles a service builder for the spec, translating it + * Automatically assembles a layer for the spec, translating it * up a level. */ - inline def inject[E1 >: E](inline serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[Any, E1, T] = - ${SpecServiceBuilderMacros.injectImpl[Any, R, E1, T]('self, 'serviceBuilder)} + inline def inject[E1 >: E](inline layer: ZLayer[_, E1, _]*): Spec[Any, E1, T] = + ${SpecLayerMacros.injectImpl[Any, R, E1, T]('self, 'layer)} def injectSome[R0 ] = new InjectSomePartiallyApplied[R0, R, E, T](self) @@ -25,24 +25,24 @@ trait SpecVersionSpecific[-R, +E, +T] { self: Spec[R, E, T] => * * {{{ * val zio: ZIO[OldLady with Console, Nothing, Unit] = ??? - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The TestEnvironment you use later will provide both Blocking to flyServiceBuilder and + * // The TestEnvironment you use later will provide both Blocking to flyLayer and * // Console to zio * val zio2 : ZIO[TestEnvironment, Nothing, Unit] = - * zio.injectCustom(oldLadyServiceBuilder, flyServiceBuilder) + * zio.injectCustom(oldLadyLayer, flyLayer) * }}} */ - inline def injectCustom[E1 >: E](inline serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[TestEnvironment, E1, T] = - ${SpecServiceBuilderMacros.injectImpl[TestEnvironment, R, E1, T]('self, 'serviceBuilder)} + inline def injectCustom[E1 >: E](inline layer: ZLayer[_, E1, _]*): Spec[TestEnvironment, E1, T] = + ${SpecLayerMacros.injectImpl[TestEnvironment, R, E1, T]('self, 'layer)} /** - * Automatically assembles a service builder for the spec, sharing + * Automatically assembles a layer for the spec, sharing * services between all tests. */ - inline def injectShared[E1 >: E](inline serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[Any, E1, T] = - ${SpecServiceBuilderMacros.injectSharedImpl[Any, R, E1, T]('self, 'serviceBuilder)} + inline def injectShared[E1 >: E](inline layer: ZLayer[_, E1, _]*): Spec[Any, E1, T] = + ${SpecLayerMacros.injectSharedImpl[Any, R, E1, T]('self, 'layer)} /** * Automatically constructs the part of the environment that is not part of the @@ -54,25 +54,25 @@ trait SpecVersionSpecific[-R, +E, +T] { self: Spec[R, E, T] => * * {{{ * val zio: ZIO[OldLady with Console, Nothing, Unit] = ??? - * val oldLadyServiceBuilder: ZServiceBuilder[Fly, Nothing, OldLady] = ??? - * val flyServiceBuilder: ZServiceBuilder[Blocking, Nothing, Fly] = ??? + * val oldLadyLayer: ZLayer[Fly, Nothing, OldLady] = ??? + * val flyLayer: ZLayer[Blocking, Nothing, Fly] = ??? * - * // The TestEnvironment you use later will provide both Blocking to flyServiceBuilder and + * // The TestEnvironment you use later will provide both Blocking to flyLayer and * // Console to zio * val zio2 : ZIO[TestEnvironment, Nothing, Unit] = - * zio.injectCustom(oldLadyServiceBuilder, flyServiceBuilder) + * zio.injectCustom(oldLadyLayer, flyLayer) * }}} */ - inline def injectCustomShared[E1 >: E](inline serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[TestEnvironment, E1, T] = - ${SpecServiceBuilderMacros.injectSharedImpl[TestEnvironment, R, E1, T]('self, 'serviceBuilder)} + inline def injectCustomShared[E1 >: E](inline layer: ZLayer[_, E1, _]*): Spec[TestEnvironment, E1, T] = + ${SpecLayerMacros.injectSharedImpl[TestEnvironment, R, E1, T]('self, 'layer)} } private final class InjectSomePartiallyApplied[R0, -R, +E, +T](val self: Spec[R, E, T]) extends AnyVal { - inline def apply[E1 >: E](inline serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[R0, E1, T] = - ${SpecServiceBuilderMacros.injectImpl[R0, R, E1, T]('self, 'serviceBuilder)} + inline def apply[E1 >: E](inline layer: ZLayer[_, E1, _]*): Spec[R0, E1, T] = + ${SpecLayerMacros.injectImpl[R0, R, E1, T]('self, 'layer)} } private final class InjectSomeSharedPartiallyApplied[R0, -R, +E, +T](val self: Spec[R, E, T]) extends AnyVal { - inline def apply[E1 >: E](inline serviceBuilder: ZServiceBuilder[_, E1, _]*): Spec[R0, E1, T] = - ${SpecServiceBuilderMacros.injectSharedImpl[R0, R, E1, T]('self, 'serviceBuilder)} + inline def apply[E1 >: E](inline layer: ZLayer[_, E1, _]*): Spec[R0, E1, T] = + ${SpecLayerMacros.injectSharedImpl[R0, R, E1, T]('self, 'layer)} } diff --git a/test/shared/src/main/scala/zio/test/Annotations.scala b/test/shared/src/main/scala/zio/test/Annotations.scala index 3eae55024ac0..4da2cb49de7d 100644 --- a/test/shared/src/main/scala/zio/test/Annotations.scala +++ b/test/shared/src/main/scala/zio/test/Annotations.scala @@ -48,9 +48,9 @@ object Annotations { /** * Constructs a new `Annotations` service. */ - val live: UServiceBuilder[Annotations] = { + val live: ULayer[Annotations] = { implicit val trace = Tracer.newTrace - ZServiceBuilder.fromZIO(FiberRef.make(TestAnnotationMap.empty).map { fiberRef => + ZLayer.fromZIO(FiberRef.make(TestAnnotationMap.empty).map { fiberRef => new Annotations { def annotate[V](key: TestAnnotation[V], value: V)(implicit trace: ZTraceElement): UIO[Unit] = fiberRef.update(_.annotate(key, value)) diff --git a/test/shared/src/main/scala/zio/test/DefaultMutableRunnableSpec.scala b/test/shared/src/main/scala/zio/test/DefaultMutableRunnableSpec.scala index 26aa6c3b87b1..f6e9eea2670d 100644 --- a/test/shared/src/main/scala/zio/test/DefaultMutableRunnableSpec.scala +++ b/test/shared/src/main/scala/zio/test/DefaultMutableRunnableSpec.scala @@ -16,7 +16,7 @@ package zio.test -import zio.{Tag, IsNotIntersection, ZServiceBuilder} +import zio.{Tag, IsNotIntersection, ZLayer} import zio.internal.stacktracer.Tracer import zio.stacktracer.TracingImplicits.disableAutoTrace @@ -39,6 +39,6 @@ import zio.stacktracer.TracingImplicits.disableAutoTrace @deprecated("use DefaultRunnableSpec", "2.0.0") class DefaultMutableRunnableSpec extends MutableRunnableSpec[Any]( - ZServiceBuilder.succeed[Any](())(Tag[Any], IsNotIntersection[Any], Tracer.newTrace), + ZLayer.succeed[Any](())(Tag[Any], IsNotIntersection[Any], Tracer.newTrace), TestAspect.identity ) diff --git a/test/shared/src/main/scala/zio/test/Live.scala b/test/shared/src/main/scala/zio/test/Live.scala index 1104704e0b99..eb2e0ef23036 100644 --- a/test/shared/src/main/scala/zio/test/Live.scala +++ b/test/shared/src/main/scala/zio/test/Live.scala @@ -1,6 +1,6 @@ package zio.test -import zio.{IO, ZEnv, ZIO, ZServiceBuilder, ZManaged, ZTraceElement} +import zio.{IO, ZEnv, ZIO, ZLayer, ZManaged, ZTraceElement} import zio.internal.stacktracer.Tracer import zio.stacktracer.TracingImplicits.disableAutoTrace @@ -36,7 +36,7 @@ object Live { * live versions of all the standard ZIO environment types but could be useful * if you are mixing in interfaces to create your own environment type. */ - def default: ZServiceBuilder[ZEnv, Nothing, Live] = { + def default: ZLayer[ZEnv, Nothing, Live] = { implicit val trace = Tracer.newTrace ZManaged .access[ZEnv] { zenv => @@ -45,7 +45,7 @@ object Live { zio.provideEnvironment(zenv) } } - .toServiceBuilder + .toLayer } /** diff --git a/test/shared/src/main/scala/zio/test/MutableRunnableSpec.scala b/test/shared/src/main/scala/zio/test/MutableRunnableSpec.scala index 7259ed09e04b..8825b7712642 100644 --- a/test/shared/src/main/scala/zio/test/MutableRunnableSpec.scala +++ b/test/shared/src/main/scala/zio/test/MutableRunnableSpec.scala @@ -26,7 +26,7 @@ import scala.util.control.NoStackTrace /** * Syntax for writing test like * {{{ - * object MySpec extends MutableRunnableSpec(serviceBuilder, aspect) { + * object MySpec extends MutableRunnableSpec(layer, aspect) { * suite("foo") { * test("name") { * } @@ ignore @@ -41,7 +41,7 @@ import scala.util.control.NoStackTrace */ @deprecated("use RunnableSpec", "2.0.0") class MutableRunnableSpec[R: Tag]( - serviceBuilder: ZServiceBuilder[TestEnvironment, Throwable, R], + layer: ZLayer[TestEnvironment, Throwable, R], aspect: TestAspect.WithOut[ R with TestEnvironment, R with TestEnvironment, @@ -178,7 +178,7 @@ class MutableRunnableSpec[R: Tag]( final override def spec: ZSpec[Environment, Failure] = { implicit val trace = Tracer.newTrace specBuilt = true - (stack.head @@ aspect).toSpec.provideCustomShared(serviceBuilder.mapError(TestFailure.fail)) + (stack.head @@ aspect).toSpec.provideCustomShared(layer.mapError(TestFailure.fail)) } override def aspects: List[TestAspect.WithOut[ diff --git a/test/shared/src/main/scala/zio/test/Sized.scala b/test/shared/src/main/scala/zio/test/Sized.scala index 24898876e657..5392b327f777 100644 --- a/test/shared/src/main/scala/zio/test/Sized.scala +++ b/test/shared/src/main/scala/zio/test/Sized.scala @@ -1,6 +1,6 @@ package zio.test -import zio.{ServiceBuilder, FiberRef, UIO, URIO, ZIO, ZServiceBuilder, ZTraceElement} +import zio.{Layer, FiberRef, UIO, URIO, ZIO, ZLayer, ZTraceElement} import zio.stream.ZStream import zio.stacktracer.TracingImplicits.disableAutoTrace @@ -12,11 +12,11 @@ trait Sized extends Serializable { object Sized { - val default: ZServiceBuilder[Any, Nothing, Sized] = + val default: ZLayer[Any, Nothing, Sized] = live(100)(ZTraceElement.empty) - def live(size: Int)(implicit trace: ZTraceElement): ServiceBuilder[Nothing, Sized] = - ZServiceBuilder.fromZIO(FiberRef.make(size).map { fiberRef => + def live(size: Int)(implicit trace: ZTraceElement): Layer[Nothing, Sized] = + ZLayer.fromZIO(FiberRef.make(size).map { fiberRef => new Sized { def size(implicit trace: ZTraceElement): UIO[Int] = fiberRef.get diff --git a/test/shared/src/main/scala/zio/test/Spec.scala b/test/shared/src/main/scala/zio/test/Spec.scala index d194987702a1..c0a3f11a2002 100644 --- a/test/shared/src/main/scala/zio/test/Spec.scala +++ b/test/shared/src/main/scala/zio/test/Spec.scala @@ -342,17 +342,17 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e } /** - * Provides a service builder to the spec, translating it up a level. + * Provides a layer to the spec, translating it up a level. */ final def provide[E1 >: E, R0, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): Spec[R0, E1, T] = transform[R0, E1, T] { case ExecCase(exec, spec) => ExecCase(exec, spec) case LabeledCase(label, spec) => LabeledCase(label, spec) - case ManagedCase(managed) => ManagedCase(managed.provide(serviceBuilder)) + case ManagedCase(managed) => ManagedCase(managed.provide(layer)) case MultipleCase(specs) => MultipleCase(specs) - case TestCase(test, annotations) => TestCase(test.provide(serviceBuilder), annotations) + case TestCase(test, annotations) => TestCase(test.provide(layer), annotations) } /** @@ -361,19 +361,19 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e * `TestEnvironment`. * * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? * - * val spec2 = spec.provideCustom(loggingServiceBuilder) + * val spec2 = spec.provideCustom(loggingLayer) * }}} */ - def provideCustom[E1 >: E, R1](serviceBuilder: ZServiceBuilder[TestEnvironment, E1, R1])(implicit + def provideCustom[E1 >: E, R1](layer: ZLayer[TestEnvironment, E1, R1])(implicit ev: TestEnvironment with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement ): Spec[TestEnvironment, E1, T] = - provideSome[TestEnvironment](serviceBuilder) + provideSome[TestEnvironment](layer) /** * Provides each test with the part of the environment that is not part of the @@ -381,7 +381,7 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e * `TestEnvironment`. * * {{{ - * val loggingLayer: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? * @@ -389,7 +389,7 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e * }}} */ @deprecated("use provideCustom", "2.0.0") - def provideCustomLayer[E1 >: E, R1](layer: ZServiceBuilder[TestEnvironment, E1, R1])(implicit + def provideCustomLayer[E1 >: E, R1](layer: ZLayer[TestEnvironment, E1, R1])(implicit ev: TestEnvironment with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement @@ -402,7 +402,7 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e * on the `TestEnvironment`. * * {{{ - * val loggingLayer: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? * @@ -410,74 +410,32 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e * }}} */ @deprecated("use provideCustomShared", "2.0.0") - def provideCustomLayerShared[E1 >: E, R1](layer: ZServiceBuilder[TestEnvironment, E1, R1])(implicit + def provideCustomLayerShared[E1 >: E, R1](layer: ZLayer[TestEnvironment, E1, R1])(implicit ev: TestEnvironment with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement ): Spec[TestEnvironment, E1, T] = provideSomeShared(layer) - /** - * Provides each test with the part of the environment that is not part of the - * `TestEnvironment`, leaving a spec that only depends on the - * `TestEnvironment`. - * - * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? - * - * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? - * - * val spec2 = spec.provideCustomServices(loggingServiceBuilder) - * }}} - */ - @deprecated("use provideCustom", "2.0.0") - def provideCustomServices[E1 >: E, R1](serviceBuilder: ZServiceBuilder[TestEnvironment, E1, R1])(implicit - ev: TestEnvironment with R1 <:< R, - tagged: Tag[R1], - trace: ZTraceElement - ): Spec[TestEnvironment, E1, T] = - provideCustom(serviceBuilder) - /** * Provides all tests with a shared version of the part of the environment * that is not part of the `TestEnvironment`, leaving a spec that only depends * on the `TestEnvironment`. * * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? * - * val spec2 = spec.provideCustomServicesShared(loggingServiceBuilder) + * val spec2 = spec.provideCustomShared(loggingLayer) * }}} */ - @deprecated("use provideCustomShared", "2.0.0") - def provideCustomServicesShared[E1 >: E, R1](serviceBuilder: ZServiceBuilder[TestEnvironment, E1, R1])(implicit - ev: TestEnvironment with R1 <:< R, - tagged: Tag[R1], - trace: ZTraceElement - ): Spec[TestEnvironment, E1, T] = - provideSomeServicesShared(serviceBuilder) - - /** - * Provides all tests with a shared version of the part of the environment - * that is not part of the `TestEnvironment`, leaving a spec that only depends - * on the `TestEnvironment`. - * - * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? - * - * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? - * - * val spec2 = spec.provideCustomShared(loggingServiceBuilder) - * }}} - */ - def provideCustomShared[E1 >: E, R1](serviceBuilder: ZServiceBuilder[TestEnvironment, E1, R1])(implicit + def provideCustomShared[E1 >: E, R1](layer: ZLayer[TestEnvironment, E1, R1])(implicit ev: TestEnvironment with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement ): Spec[TestEnvironment, E1, T] = - provideSomeShared[TestEnvironment](serviceBuilder) + provideSomeShared[TestEnvironment](layer) /** * Provides each test in this spec with its required environment @@ -490,7 +448,7 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e */ @deprecated("use provide", "2.0.0") final def provideLayer[E1 >: E, R0, R1]( - layer: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): Spec[R0, E1, T] = provide(layer) @@ -499,60 +457,40 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e */ @deprecated("use provideShared", "2.0.0") final def provideLayerShared[E1 >: E, R0, R1]( - layer: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): Spec[R0, E1, T] = provideShared(layer) /** - * Provides a service builder to the spec, translating it up a level. - */ - @deprecated("use provide", "2.0.0") - final def provideServices[E1 >: E, R0, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] - )(implicit ev: R1 <:< R, trace: ZTraceElement): Spec[R0, E1, T] = - provide(serviceBuilder) - - /** - * Provides a service builder to the spec, sharing services between all tests. - */ - @deprecated("use provideShared", "2.0.0") - final def provideServicesShared[E1 >: E, R0, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] - )(implicit ev: R1 <:< R, trace: ZTraceElement): Spec[R0, E1, T] = - provideShared(serviceBuilder) - - /** - * Provides a service builder to the spec, sharing services between all tests. + * Provides a layer to the spec, sharing services between all tests. */ final def provideShared[E1 >: E, R0, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev: R1 <:< R, trace: ZTraceElement): Spec[R0, E1, T] = caseValue match { - case ExecCase(exec, spec) => Spec.exec(exec, spec.provideShared(serviceBuilder)) - case LabeledCase(label, spec) => Spec.labeled(label, spec.provideShared(serviceBuilder)) + case ExecCase(exec, spec) => Spec.exec(exec, spec.provideShared(layer)) + case LabeledCase(label, spec) => Spec.labeled(label, spec.provideShared(layer)) case ManagedCase(managed) => Spec.managed( - serviceBuilder.build.flatMap(r => - managed.map(_.provideEnvironment(r.upcast(ev))).provideEnvironment(r.upcast(ev)) - ) + layer.build.flatMap(r => managed.map(_.provideEnvironment(r.upcast(ev))).provideEnvironment(r.upcast(ev))) ) case MultipleCase(specs) => Spec.managed( - serviceBuilder.build.map(r => Spec.multiple(specs.map(_.provideEnvironment(r.upcast(ev))))) + layer.build.map(r => Spec.multiple(specs.map(_.provideEnvironment(r.upcast(ev))))) ) - case TestCase(test, annotations) => Spec.test(test.provide(serviceBuilder), annotations) + case TestCase(test, annotations) => Spec.test(test.provide(layer), annotations) } /** * Splits the environment into two parts, providing each test with one part - * using the specified service builder and leaving the remainder `R0`. + * using the specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val spec: ZSpec[Clock with Random, Nothing] = ??? * - * val spec2 = spec.provideSome[Random](clockServiceBuilder) + * val spec2 = spec.provideSome[Random](clockLayer) * }}} */ final def provideSome[R0]: Spec.ProvideSome[R0, R, E, T] = @@ -563,7 +501,7 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e * using the specified layer and leaving the remainder `R0`. * * {{{ - * val clockLayer: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val spec: ZSpec[Clock with Random, Nothing] = ??? * @@ -580,7 +518,7 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e * `R0`. * * {{{ - * val clockLayer: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val spec: ZSpec[Clock with Random, Nothing] = ??? * @@ -591,50 +529,17 @@ final case class Spec[-R, +E, +T](caseValue: SpecCase[R, E, T, Spec[R, E, T]]) e final def provideSomeLayerShared[R0]: Spec.ProvideSomeShared[R0, R, E, T] = new Spec.ProvideSomeShared[R0, R, E, T](self) - /** - * Splits the environment into two parts, providing each test with one part - * using the specified service builder and leaving the remainder `R0`. - * - * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? - * - * val spec: ZSpec[Clock with Random, Nothing] = ??? - * - * val spec2 = spec.provideSomeServices[Random](clockServiceBuilder) - * }}} - */ - @deprecated("use provideSome", "2.0.0") - final def provideSomeServices[R0]: Spec.ProvideSome[R0, R, E, T] = - provideSome - - /** - * Splits the environment into two parts, providing all tests with a shared - * version of one part using the specified service builder and leaving the - * remainder `R0`. - * - * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? - * - * val spec: ZSpec[Clock with Random, Nothing] = ??? - * - * val spec2 = spec.provideSomeServicesShared[Random](clockServiceBuilder) - * }}} - */ - @deprecated("use provideSomeShared", "2.0.0") - final def provideSomeServicesShared[R0]: Spec.ProvideSomeShared[R0, R, E, T] = - provideSomeShared - /** * Splits the environment into two parts, providing all tests with a shared - * version of one part using the specified service builder and leaving the - * remainder `R0`. + * version of one part using the specified layer and leaving the remainder + * `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val spec: ZSpec[Clock with Random, Nothing] = ??? * - * val spec2 = spec.provideSomeShared[Random](clockServiceBuilder) + * val spec2 = spec.provideSomeShared[Random](clockLayer) * }}} */ final def provideSomeShared[R0]: Spec.ProvideSomeShared[R0, R, E, T] = @@ -807,32 +712,32 @@ object Spec extends SpecLowPriority { final class ProvideSome[R0, -R, +E, +T](private val self: Spec[R, E, T]) extends AnyVal { def apply[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev: R0 with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement): Spec[R0, E1, T] = - self.provide[E1, R0, R0 with R1](ZServiceBuilder.environment[R0] ++ serviceBuilder) + self.provide[E1, R0, R0 with R1](ZLayer.environment[R0] ++ layer) } final class ProvideSomeShared[R0, -R, +E, +T](private val self: Spec[R, E, T]) extends AnyVal { def apply[E1 >: E, R1]( - serviceBuilder: ZServiceBuilder[R0, E1, R1] + layer: ZLayer[R0, E1, R1] )(implicit ev: R0 with R1 <:< R, tagged: Tag[R1], trace: ZTraceElement): Spec[R0, E1, T] = self.caseValue match { - case ExecCase(exec, spec) => Spec.exec(exec, spec.provideSomeShared(serviceBuilder)) - case LabeledCase(label, spec) => Spec.labeled(label, spec.provideSomeShared(serviceBuilder)) + case ExecCase(exec, spec) => Spec.exec(exec, spec.provideSomeShared(layer)) + case LabeledCase(label, spec) => Spec.labeled(label, spec.provideSomeShared(layer)) case ManagedCase(managed) => Spec.managed( - serviceBuilder.build.flatMap { r => + layer.build.flatMap { r => managed - .map(_.provideSome[R0](ZServiceBuilder.succeedMany(r))) - .provideSome[R0](ZServiceBuilder.succeedMany(r)) + .map(_.provideSome[R0](ZLayer.succeedMany(r))) + .provideSome[R0](ZLayer.succeedMany(r)) } ) case MultipleCase(specs) => Spec.managed( - serviceBuilder.build.map(r => Spec.multiple(specs.map(_.provideSome[R0](ZServiceBuilder.succeedMany(r))))) + layer.build.map(r => Spec.multiple(specs.map(_.provideSome[R0](ZLayer.succeedMany(r))))) ) case TestCase(test, annotations) => - Spec.test(test.provideSome(serviceBuilder), annotations) + Spec.test(test.provideSome(layer), annotations) } } diff --git a/test/shared/src/main/scala/zio/test/TestAspect.scala b/test/shared/src/main/scala/zio/test/TestAspect.scala index 6a0f8df90426..dbfc614cbb12 100644 --- a/test/shared/src/main/scala/zio/test/TestAspect.scala +++ b/test/shared/src/main/scala/zio/test/TestAspect.scala @@ -1003,17 +1003,16 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant executionStrategy(ExecutionStrategy.ParallelN(n)) /** - * An aspect that provides a service builder to the spec, translating it up a - * level. + * An aspect that provides a layer to the spec, translating it up a level. */ final def provide[R0, E1, R1]( - serviceBuilder: ZServiceBuilder[R0, TestFailure[E1], R1] + layer: ZLayer[R0, TestFailure[E1], R1] ): TestAspect.WithOut[R1, Any, E1, Any, ({ type OutEnv[Env] = R0 })#OutEnv, ({ type OutErr[Err] = Err })#OutErr] = new TestAspect[R1, Any, E1, Any] { type OutEnv[Env] = R0 type OutErr[Err] = Err def apply[R >: R1, E >: E1](spec: ZSpec[R, E])(implicit trace: ZTraceElement): ZSpec[R0, E] = - spec.provide(serviceBuilder) + spec.provide(layer) } /** @@ -1022,14 +1021,14 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant * `TestEnvironment`. * * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? * - * val spec2 = spec.provideCustom(loggingServiceBuilder) + * val spec2 = spec.provideCustom(loggingLayer) * }}} */ - def provideCustom[E, R](serviceBuilder: ZServiceBuilder[TestEnvironment, TestFailure[E], R])(implicit + def provideCustom[E, R](layer: ZLayer[TestEnvironment, TestFailure[E], R])(implicit tagged: Tag[R], trace: ZTraceElement ): TestAspect.WithOut[ @@ -1040,7 +1039,7 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant ({ type OutEnv[Env] = TestEnvironment })#OutEnv, ({ type OutErr[Err] = Err })#OutErr ] = - provideSome[TestEnvironment][E, R](serviceBuilder) + provideSome[TestEnvironment][E, R](layer) /** * Provides each test with the part of the environment that is not part of the @@ -1048,15 +1047,14 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant * `TestEnvironment`. * * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? + * val loggingLayer: ZLayer[Any, Nothing, Logging] = ??? * * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? * - * val spec2 = spec.provideCustomServices(loggingServiceBuilder) + * val spec2 = spec.provideCustom(loggingLayer) * }}} */ - @deprecated("use provideCustom", "2.0.0") - def provideCustomServices[E, R](serviceBuilder: ZServiceBuilder[TestEnvironment, TestFailure[E], R])(implicit + def provideCustomShared[E, R](layer: ZLayer[TestEnvironment, TestFailure[E], R])(implicit tagged: Tag[R], trace: ZTraceElement ): TestAspect.WithOut[ @@ -1067,60 +1065,7 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant ({ type OutEnv[Env] = TestEnvironment })#OutEnv, ({ type OutErr[Err] = Err })#OutErr ] = - provideCustom[E, R](serviceBuilder) - - /** - * Provides each test with the part of the environment that is not part of the - * `TestEnvironment`, leaving a spec that only depends on the - * `TestEnvironment`. - * - * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? - * - * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? - * - * val spec2 = spec.provideCustomServices(loggingServiceBuilder) - * }}} - */ - @deprecated("use provideCustomShared", "2.0.0") - def provideCustomServicesShared[E, R](serviceBuilder: ZServiceBuilder[TestEnvironment, TestFailure[E], R])(implicit - tagged: Tag[R], - trace: ZTraceElement - ): TestAspect.WithOut[ - TestEnvironment with R, - Any, - E, - Any, - ({ type OutEnv[Env] = TestEnvironment })#OutEnv, - ({ type OutErr[Err] = Err })#OutErr - ] = - provideCustomShared[E, R](serviceBuilder) - - /** - * Provides each test with the part of the environment that is not part of the - * `TestEnvironment`, leaving a spec that only depends on the - * `TestEnvironment`. - * - * {{{ - * val loggingServiceBuilder: ZServiceBuilder[Any, Nothing, Logging] = ??? - * - * val spec: ZSpec[TestEnvironment with Logging, Nothing] = ??? - * - * val spec2 = spec.provideCustom(loggingServiceBuilder) - * }}} - */ - def provideCustomShared[E, R](serviceBuilder: ZServiceBuilder[TestEnvironment, TestFailure[E], R])(implicit - tagged: Tag[R], - trace: ZTraceElement - ): TestAspect.WithOut[ - TestEnvironment with R, - Any, - E, - Any, - ({ type OutEnv[Env] = TestEnvironment })#OutEnv, - ({ type OutErr[Err] = Err })#OutErr - ] = - provideSomeShared[TestEnvironment][E, R](serviceBuilder) + provideSomeShared[TestEnvironment][E, R](layer) /** * An aspect that provides each test in the spec with its required @@ -1143,42 +1088,31 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant /** * Splits the environment into two parts, providing each test with one part - * using the specified service builder and leaving the remainder `R0`. + * using the specified layer and leaving the remainder `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val spec: ZSpec[Clock with Random, Nothing] = ??? * - * val spec2 = spec @@ provideSomeServices[Random](clockServiceBuilder) + * val spec2 = spec @@ provideSomeLayer[Random](clockLayer) * }}} */ @deprecated("Use provideSome", "2.0.0") - final def provideSomeServices[R0]: TestAspect.ProvideSomeServices[R0] = + final def provideSomeLayer[R0]: TestAspect.ProvideSomeLayer[R0] = provideSome /** - * An aspect that provides a service builder to the spec, translating it up a - * level. - */ - @deprecated("use provideShared", "2.0.0") - final def provideServicesShared[R0, E1, R1]( - serviceBuilder: ZServiceBuilder[R0, TestFailure[E1], R1] - ): TestAspect.WithOut[R1, Any, E1, Any, ({ type OutEnv[Env] = R0 })#OutEnv, ({ type OutErr[Err] = Err })#OutErr] = - provideShared(serviceBuilder) - - /** - * An aspect that provides a service builder to the spec, translating it up a - * level. + * An aspect that provides a layer to the spec, translating it up a level. */ final def provideShared[R0, E1, R1]( - serviceBuilder: ZServiceBuilder[R0, TestFailure[E1], R1] + layer: ZLayer[R0, TestFailure[E1], R1] ): TestAspect.WithOut[R1, Any, E1, Any, ({ type OutEnv[Env] = R0 })#OutEnv, ({ type OutErr[Err] = Err })#OutErr] = new TestAspect[R1, Any, E1, Any] { type OutEnv[Env] = R0 type OutErr[Err] = Err def apply[R >: R1, E >: E1](spec: ZSpec[R, E])(implicit trace: ZTraceElement): ZSpec[R0, E] = - spec.provideShared(serviceBuilder) + spec.provideShared(layer) } /** @@ -1193,8 +1127,8 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant * val spec2 = spec @@ provideSome[Random](clockServiceBuilder) * }}} */ - final def provideSome[R0]: TestAspect.ProvideSomeServices[R0] = - new TestAspect.ProvideSomeServices[R0] + final def provideSome[R0]: TestAspect.ProvideSomeLayer[R0] = + new TestAspect.ProvideSomeLayer[R0] /** * Transforms the environment being provided to this spec with the specified @@ -1217,36 +1151,36 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant /** * Splits the environment into two parts, providing all tests with a shared - * version of one part using the specified service builder and leaving the - * remainder `R0`. + * version of one part using the specified layer and leaving the remainder + * `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val spec: ZSpec[Clock with Random, Nothing] = ??? * - * val spec2 = spec.provideSomeServicesShared[Random](clockServiceBuilder) + * val spec2 = spec.provideSomeLayerShared[Random](clockLayer) * }}} */ @deprecated("use provideSomeShared", "2.0.0") - final def provideSomeServicesShared[R0]: TestAspect.ProvideSomeServicesShared[R0] = + final def provideSomeLayerShared[R0]: TestAspect.ProvideSomeLayerShared[R0] = provideSomeShared /** * Splits the environment into two parts, providing all tests with a shared - * version of one part using the specified service builder and leaving the - * remainder `R0`. + * version of one part using the specified layer and leaving the remainder + * `R0`. * * {{{ - * val clockServiceBuilder: ZServiceBuilder[Any, Nothing, Clock] = ??? + * val clockLayer: ZLayer[Any, Nothing, Clock] = ??? * * val spec: ZSpec[Clock with Random, Nothing] = ??? * - * val spec2 = spec.provideSomeShared[Random](clockServiceBuilder) + * val spec2 = spec.provideSomeShared[Random](clockLayer) * }}} */ - final def provideSomeShared[R0]: TestAspect.ProvideSomeServicesShared[R0] = - new TestAspect.ProvideSomeServicesShared[R0] + final def provideSomeShared[R0]: TestAspect.ProvideSomeLayerShared[R0] = + new TestAspect.ProvideSomeLayerShared[R0] /** * An aspect that repeats successful tests according to a schedule. @@ -1890,9 +1824,9 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant } } - final class ProvideSomeServices[R0](private val dummy: Boolean = true) extends AnyVal { + final class ProvideSomeLayer[R0](private val dummy: Boolean = true) extends AnyVal { def apply[E1, R1]( - serviceBuilder: ZServiceBuilder[R0, TestFailure[E1], R1] + layer: ZLayer[R0, TestFailure[E1], R1] )(implicit tagged: Tag[R1], trace: ZTraceElement @@ -1910,13 +1844,13 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant def apply[R >: R0 with R1, E >: E1]( spec: Spec[R, TestFailure[E], TestSuccess] )(implicit trace: ZTraceElement): Spec[R0, TestFailure[E], TestSuccess] = - spec.provide[TestFailure[E], R0, R0 with R1](ZServiceBuilder.environment[R0] ++ serviceBuilder) + spec.provide[TestFailure[E], R0, R0 with R1](ZLayer.environment[R0] ++ layer) } } - final class ProvideSomeServicesShared[R0](private val dummy: Boolean = true) extends AnyVal { + final class ProvideSomeLayerShared[R0](private val dummy: Boolean = true) extends AnyVal { def apply[E1, R1]( - serviceBuilder: ZServiceBuilder[R0, TestFailure[E1], R1] + layer: ZLayer[R0, TestFailure[E1], R1] )(implicit tagged: Tag[R1], trace: ZTraceElement @@ -1934,7 +1868,7 @@ object TestAspect extends TestAspectCompanionVersionSpecific with TimeoutVariant def apply[R >: R0 with R1, E >: E1]( spec: Spec[R, TestFailure[E], TestSuccess] )(implicit trace: ZTraceElement): Spec[R0, TestFailure[E], TestSuccess] = - spec.provideShared[TestFailure[E], R0, R0 with R1](ZServiceBuilder.environment[R0] ++ serviceBuilder) + spec.provideShared[TestFailure[E], R0, R0 with R1](ZLayer.environment[R0] ++ layer) } } } diff --git a/test/shared/src/main/scala/zio/test/TestClock.scala b/test/shared/src/main/scala/zio/test/TestClock.scala index a65a393fbd1c..4d07c024415d 100644 --- a/test/shared/src/main/scala/zio/test/TestClock.scala +++ b/test/shared/src/main/scala/zio/test/TestClock.scala @@ -367,8 +367,8 @@ object TestClock extends Serializable { data: Data )(implicit trace: ZTraceElement - ): ZServiceBuilder[Annotations with Live, Nothing, TestClock] = - ZServiceBuilder { + ): ZLayer[Annotations with Live, Nothing, TestClock] = + ZLayer { for { live <- ZManaged.service[Live] annotations <- ZManaged.service[Annotations] @@ -383,10 +383,10 @@ object TestClock extends Serializable { } yield test } - val any: ZServiceBuilder[TestClock, Nothing, TestClock] = - ZServiceBuilder.environment[TestClock](Tracer.newTrace) + val any: ZLayer[TestClock, Nothing, TestClock] = + ZLayer.environment[TestClock](Tracer.newTrace) - val default: ZServiceBuilder[Live with Annotations, Nothing, TestClock] = + val default: ZLayer[Live with Annotations, Nothing, TestClock] = live(Data(Duration.Zero, Nil, ZoneId.of("UTC")))(Tracer.newTrace) /** diff --git a/test/shared/src/main/scala/zio/test/TestConfig.scala b/test/shared/src/main/scala/zio/test/TestConfig.scala index 5c9bd43c41db..3158a5242a62 100644 --- a/test/shared/src/main/scala/zio/test/TestConfig.scala +++ b/test/shared/src/main/scala/zio/test/TestConfig.scala @@ -16,7 +16,7 @@ package zio.test -import zio.{URIO, ZIO, ZServiceBuilder} +import zio.{URIO, ZIO, ZLayer} import zio.stacktracer.TracingImplicits.disableAutoTrace import zio.ZTraceElement @@ -55,7 +55,7 @@ object TestConfig { /** * Constructs a new `TestConfig` with the default settings. */ - val default: ZServiceBuilder[Any, Nothing, TestConfig] = + val default: ZLayer[Any, Nothing, TestConfig] = live(100, 100, 200, 1000)(ZTraceElement.empty) /** @@ -63,8 +63,8 @@ object TestConfig { */ def live(repeats0: Int, retries0: Int, samples0: Int, shrinks0: Int)(implicit trace: ZTraceElement - ): ZServiceBuilder[Any, Nothing, TestConfig] = - ZServiceBuilder.succeed { + ): ZLayer[Any, Nothing, TestConfig] = + ZLayer.succeed { new TestConfig { val repeats = repeats0 val retries = retries0 diff --git a/test/shared/src/main/scala/zio/test/TestConsole.scala b/test/shared/src/main/scala/zio/test/TestConsole.scala index 585bff5071dc..885ab6e513cb 100644 --- a/test/shared/src/main/scala/zio/test/TestConsole.scala +++ b/test/shared/src/main/scala/zio/test/TestConsole.scala @@ -16,7 +16,7 @@ package zio.test -import zio.{Console, FiberRef, IO, Ref, UIO, URIO, ZIO, ZServiceBuilder, ZTraceElement} +import zio.{Console, FiberRef, IO, Ref, UIO, URIO, ZIO, ZLayer, ZTraceElement} import zio.internal.stacktracer.Tracer import zio.stacktracer.TracingImplicits.disableAutoTrace @@ -193,8 +193,8 @@ object TestConsole extends Serializable { */ def make(data: Data, debug: Boolean = true)(implicit trace: ZTraceElement - ): ZServiceBuilder[Live, Nothing, TestConsole] = - ZServiceBuilder { + ): ZLayer[Live, Nothing, TestConsole] = + ZLayer { for { live <- ZIO.service[Live] ref <- Ref.make(data) @@ -203,13 +203,13 @@ object TestConsole extends Serializable { } yield test } - val any: ZServiceBuilder[TestConsole, Nothing, TestConsole] = - ZServiceBuilder.environment[TestConsole](Tracer.newTrace) + val any: ZLayer[TestConsole, Nothing, TestConsole] = + ZLayer.environment[TestConsole](Tracer.newTrace) - val debug: ZServiceBuilder[Live, Nothing, TestConsole] = + val debug: ZLayer[Live, Nothing, TestConsole] = make(Data(Nil, Vector()), true)(Tracer.newTrace) - val silent: ZServiceBuilder[Live, Nothing, TestConsole] = + val silent: ZLayer[Live, Nothing, TestConsole] = make(Data(Nil, Vector()), false)(Tracer.newTrace) /** diff --git a/test/shared/src/main/scala/zio/test/TestExecutor.scala b/test/shared/src/main/scala/zio/test/TestExecutor.scala index f449a2d311fa..651dd1397222 100644 --- a/test/shared/src/main/scala/zio/test/TestExecutor.scala +++ b/test/shared/src/main/scala/zio/test/TestExecutor.scala @@ -16,7 +16,7 @@ package zio.test -import zio.{ExecutionStrategy, ServiceBuilder, UIO, ZIO, ZManaged, ZTraceElement} +import zio.{ExecutionStrategy, Layer, UIO, ZIO, ZManaged, ZTraceElement} import zio.stacktracer.TracingImplicits.disableAutoTrace /** @@ -25,12 +25,12 @@ import zio.stacktracer.TracingImplicits.disableAutoTrace */ abstract class TestExecutor[+R, E] { def run(spec: ZSpec[R, E], defExec: ExecutionStrategy)(implicit trace: ZTraceElement): UIO[ExecutedSpec[E]] - def environment: ServiceBuilder[Nothing, R] + def environment: Layer[Nothing, R] } object TestExecutor { def default[R <: Annotations, E]( - env: ServiceBuilder[Nothing, R] + env: Layer[Nothing, R] ): TestExecutor[R, E] = new TestExecutor[R, E] { def run(spec: ZSpec[R, E], defExec: ExecutionStrategy)(implicit trace: ZTraceElement): UIO[ExecutedSpec[E]] = spec.annotated diff --git a/test/shared/src/main/scala/zio/test/TestLogger.scala b/test/shared/src/main/scala/zio/test/TestLogger.scala index 73c9de7427af..d9fe39044ba2 100644 --- a/test/shared/src/main/scala/zio/test/TestLogger.scala +++ b/test/shared/src/main/scala/zio/test/TestLogger.scala @@ -16,7 +16,7 @@ package zio.test -import zio.{Console, UIO, URIO, ZIO, ZServiceBuilder, ZTraceElement} +import zio.{Console, UIO, URIO, ZIO, ZLayer, ZTraceElement} import zio.stacktracer.TracingImplicits.disableAutoTrace trait TestLogger extends Serializable { @@ -25,7 +25,7 @@ trait TestLogger extends Serializable { object TestLogger { - def fromConsole(implicit trace: ZTraceElement): ZServiceBuilder[Console, Nothing, TestLogger] = + def fromConsole(implicit trace: ZTraceElement): ZLayer[Console, Nothing, TestLogger] = ZIO .service[Console] .map { console => @@ -33,7 +33,7 @@ object TestLogger { def logLine(line: String)(implicit trace: ZTraceElement): UIO[Unit] = console.printLine(line).orDie } } - .toServiceBuilder + .toLayer def logLine(line: String)(implicit trace: ZTraceElement): URIO[TestLogger, Unit] = ZIO.serviceWithZIO(_.logLine(line)) diff --git a/test/shared/src/main/scala/zio/test/TestRandom.scala b/test/shared/src/main/scala/zio/test/TestRandom.scala index 859771b74a3e..b9d6a8be867f 100644 --- a/test/shared/src/main/scala/zio/test/TestRandom.scala +++ b/test/shared/src/main/scala/zio/test/TestRandom.scala @@ -717,9 +717,9 @@ object TestRandom extends Serializable { * useful for providing the required environment to an effect that requires a * `Random`, such as with `ZIO#provide`. */ - def make(data: Data): ServiceBuilder[Nothing, TestRandom] = { + def make(data: Data): Layer[Nothing, TestRandom] = { implicit val trace = Tracer.newTrace - ZServiceBuilder { + ZLayer { for { data <- Ref.make(data) buffer <- Ref.make(Buffer()) @@ -728,15 +728,15 @@ object TestRandom extends Serializable { } } - val any: ZServiceBuilder[TestRandom, Nothing, TestRandom] = - ZServiceBuilder.environment[TestRandom](Tracer.newTrace) + val any: ZLayer[TestRandom, Nothing, TestRandom] = + ZLayer.environment[TestRandom](Tracer.newTrace) - val deterministic: ServiceBuilder[Nothing, TestRandom] = + val deterministic: Layer[Nothing, TestRandom] = make(DefaultData) - val random: ZServiceBuilder[Clock, Nothing, TestRandom] = { + val random: ZLayer[Clock, Nothing, TestRandom] = { implicit val trace = Tracer.newTrace - (ZServiceBuilder.service[Clock] ++ deterministic) >>> ZServiceBuilder { + (ZLayer.service[Clock] ++ deterministic) >>> ZLayer { for { random <- ZIO.service[Random] testRandom <- ZIO.service[TestRandom] diff --git a/test/shared/src/main/scala/zio/test/TestRunner.scala b/test/shared/src/main/scala/zio/test/TestRunner.scala index c971471caf18..c0e3766a4f35 100644 --- a/test/shared/src/main/scala/zio/test/TestRunner.scala +++ b/test/shared/src/main/scala/zio/test/TestRunner.scala @@ -31,7 +31,7 @@ final case class TestRunner[R, E]( runtimeConfig: RuntimeConfig = RuntimeConfig.makeDefault(), reporter: TestReporter[E] = DefaultTestReporter(TestRenderer.default, TestAnnotationRenderer.default)(ZTraceElement.empty), - bootstrap: ServiceBuilder[Nothing, TestLogger with Clock] = + bootstrap: Layer[Nothing, TestLogger with Clock] = (Console.live.to(TestLogger.fromConsole(ZTraceElement.empty))(ZTraceElement.empty)) ++ Clock.live ) { self => diff --git a/test/shared/src/main/scala/zio/test/TestSystem.scala b/test/shared/src/main/scala/zio/test/TestSystem.scala index 94018d1e1695..d399b0c491ed 100644 --- a/test/shared/src/main/scala/zio/test/TestSystem.scala +++ b/test/shared/src/main/scala/zio/test/TestSystem.scala @@ -16,7 +16,7 @@ package zio.test -import zio.{IO, ServiceBuilder, Ref, System, UIO, URIO, ZIO, ZServiceBuilder, ZTraceElement} +import zio.{IO, Layer, Ref, System, UIO, URIO, ZIO, ZLayer, ZTraceElement} import zio.internal.stacktracer.Tracer import zio.stacktracer.TracingImplicits.disableAutoTrace import zio.ZTrace @@ -161,15 +161,15 @@ object TestSystem extends Serializable { * useful for providing the required environment to an effect that requires a * `Console`, such as with `ZIO#provide`. */ - def live(data: Data): ServiceBuilder[Nothing, TestSystem] = { + def live(data: Data): Layer[Nothing, TestSystem] = { implicit val trace: ZTraceElement = Tracer.newTrace - Ref.make(data).map(Test).toServiceBuilder + Ref.make(data).map(Test).toLayer } - val any: ZServiceBuilder[TestSystem, Nothing, TestSystem] = - ZServiceBuilder.environment[TestSystem](Tracer.newTrace) + val any: ZLayer[TestSystem, Nothing, TestSystem] = + ZLayer.environment[TestSystem](Tracer.newTrace) - val default: ServiceBuilder[Nothing, TestSystem] = + val default: Layer[Nothing, TestSystem] = live(DefaultData) /** diff --git a/test/shared/src/main/scala/zio/test/ZIOSpecAbstract.scala b/test/shared/src/main/scala/zio/test/ZIOSpecAbstract.scala index c1f6c472034e..c4e500f141e8 100644 --- a/test/shared/src/main/scala/zio/test/ZIOSpecAbstract.scala +++ b/test/shared/src/main/scala/zio/test/ZIOSpecAbstract.scala @@ -39,14 +39,14 @@ abstract class ZIOSpecAbstract extends ZIOApp { self => final def run: ZIO[ZEnv with ZIOAppArgs, Any, Any] = { implicit val trace = Tracer.newTrace - runSpec.provideSome[ZEnv with ZIOAppArgs](TestEnvironment.live ++ serviceBuilder) + runSpec.provideSome[ZEnv with ZIOAppArgs](TestEnvironment.live ++ layer) } final def <>(that: ZIOSpecAbstract)(implicit trace: ZTraceElement): ZIOSpecAbstract = new ZIOSpecAbstract { type Environment = self.Environment with that.Environment - def serviceBuilder: ZServiceBuilder[ZIOAppArgs, Any, Environment] = - self.serviceBuilder +!+ that.serviceBuilder + def layer: ZLayer[ZIOAppArgs, Any, Environment] = + self.layer +!+ that.layer override def runSpec: ZIO[Environment with TestEnvironment with ZIOAppArgs, Any, Any] = self.runSpec.zipPar(that.runSpec) def spec: ZSpec[Environment with TestEnvironment with ZIOAppArgs, Any] = @@ -104,7 +104,7 @@ abstract class ZIOSpecAbstract extends ZIOApp { self => runner = TestRunner( TestExecutor.default[Environment with TestEnvironment with ZIOAppArgs, Any]( - ZServiceBuilder.succeedMany(env) + ZLayer.succeedMany(env) ) ) testReporter = testArgs.testRenderer.fold(runner.reporter)(createTestReporter) diff --git a/test/shared/src/main/scala/zio/test/ZIOSpecDefault.scala b/test/shared/src/main/scala/zio/test/ZIOSpecDefault.scala index e83ed35b4253..92bdb9900be6 100644 --- a/test/shared/src/main/scala/zio/test/ZIOSpecDefault.scala +++ b/test/shared/src/main/scala/zio/test/ZIOSpecDefault.scala @@ -6,8 +6,8 @@ import zio.stacktracer.TracingImplicits.disableAutoTrace abstract class ZIOSpecDefault extends ZIOSpec[TestEnvironment] { - final val testServiceBuilder: ZServiceBuilder[TestEnvironment, Any, TestEnvironment] = - ZServiceBuilder.environment(Tracer.newTrace) + final val testLayer: ZLayer[TestEnvironment, Any, TestEnvironment] = + ZLayer.environment(Tracer.newTrace) def spec: ZSpec[TestEnvironment, Any] } diff --git a/test/shared/src/main/scala/zio/test/mock/Expectation.scala b/test/shared/src/main/scala/zio/test/mock/Expectation.scala index d47e3d31a7cf..bebf3c69e874 100644 --- a/test/shared/src/main/scala/zio/test/mock/Expectation.scala +++ b/test/shared/src/main/scala/zio/test/mock/Expectation.scala @@ -21,7 +21,7 @@ import zio.test.Assertion import zio.test.mock.Expectation.{And, Chain, Exactly, Or, Repeated} import zio.test.mock.Result.{Fail, Succeed} import zio.test.mock.internal.{ExpectationState, MockException, MockState, ProxyFactory} -import zio.{IO, Managed, Tag, UServiceBuilder, URServiceBuilder, ZServiceBuilder, ZTraceElement} +import zio.{IO, Managed, Tag, ULayer, URLayer, ZLayer, ZTraceElement} import scala.language.implicitConversions @@ -159,15 +159,9 @@ sealed abstract class Expectation[R: Tag] { self => Repeated(self, range) /** - * Converts this expectation to ZServiceBuilder. + * Converts this expectation to ZLayer. */ - def toServiceBuilder(implicit trace: ZTraceElement): UServiceBuilder[R] = Expectation.toServiceBuilder(self) - - /** - * Converts this expectation to ZServiceBuilder. - */ - @deprecated("use toServiceBuilder", "2.0.0") - def toLayer(implicit trace: ZTraceElement): UServiceBuilder[R] = toServiceBuilder + def toLayer(implicit trace: ZTraceElement): ULayer[R] = Expectation.toLayer(self) /** * Invocations log. @@ -203,7 +197,7 @@ object Expectation { private[test] object And { - def apply[R: Tag](compose: URServiceBuilder[Proxy, R])(children: List[Expectation[_]]): And[R] = + def apply[R: Tag](compose: URLayer[Proxy, R])(children: List[Expectation[_]]): And[R] = And( children.asInstanceOf[List[Expectation[R]]], if (children.exists(_.state.isFailed)) Unsatisfied else Satisfied, @@ -254,7 +248,7 @@ object Expectation { private[test] object Chain { - def apply[R: Tag](compose: URServiceBuilder[Proxy, R])(children: List[Expectation[_]]): Chain[R] = + def apply[R: Tag](compose: URLayer[Proxy, R])(children: List[Expectation[_]]): Chain[R] = Chain( children.asInstanceOf[List[Expectation[R]]], if (children.exists(_.state.isFailed)) Unsatisfied else Satisfied, @@ -291,7 +285,7 @@ object Expectation { private[test] object Or { - def apply[R: Tag](compose: URServiceBuilder[Proxy, R])(children: List[Expectation[_]]): Or[R] = + def apply[R: Tag](compose: URLayer[Proxy, R])(children: List[Expectation[_]]): Or[R] = Or( children.asInstanceOf[List[Expectation[R]]], if (children.exists(_.state == Satisfied)) Satisfied else Unsatisfied, @@ -389,12 +383,12 @@ object Expectation { def valueM[I, A](f: I => IO[Nothing, A]): Succeed[I, A] = Succeed(f) /** - * Implicitly converts Expectation to ZServiceBuilder mock environment. + * Implicitly converts Expectation to ZLayer mock environment. */ - implicit def toServiceBuilder[R: Tag]( + implicit def toLayer[R: Tag]( trunk: Expectation[R] - )(implicit trace: ZTraceElement): UServiceBuilder[R] = - ZServiceBuilder.fromManagedEnvironment( + )(implicit trace: ZTraceElement): ULayer[R] = + ZLayer.fromManagedEnvironment( for { state <- Managed.acquireReleaseWith(MockState.make(trunk))(MockState.checkUnmetExpectations) env <- (ProxyFactory.mockProxy(state) >>> trunk.mock.compose).build diff --git a/test/shared/src/main/scala/zio/test/mock/Mock.scala b/test/shared/src/main/scala/zio/test/mock/Mock.scala index 06d748686782..2219e00f4e41 100644 --- a/test/shared/src/main/scala/zio/test/mock/Mock.scala +++ b/test/shared/src/main/scala/zio/test/mock/Mock.scala @@ -19,16 +19,16 @@ package zio.test.mock import zio.stacktracer.TracingImplicits.disableAutoTrace import zio.stream.{ZSink, ZStream} import zio.test.TestPlatform -import zio.{Executor, Runtime, Tag, UServiceBuilder, URIO, URServiceBuilder, ZIO, ZTraceElement} +import zio.{Executor, Runtime, Tag, ULayer, URIO, URLayer, ZIO, ZTraceElement} /** * A `Mock[R]` represents a mockable environment `R`. */ abstract class Mock[R: Tag] { self => - protected[test] val compose: URServiceBuilder[Proxy, R] + protected[test] val compose: URLayer[Proxy, R] - def empty(implicit trace: ZTraceElement): UServiceBuilder[R] = Expectation.NoCalls(self) + def empty(implicit trace: ZTraceElement): ULayer[R] = Expectation.NoCalls(self) /** * Replaces Runtime on JS platform to one with unyielding executor. @@ -75,5 +75,5 @@ abstract class Mock[R: Tag] { self => object Mock { - private[mock] case class Composed[R: Tag](compose: URServiceBuilder[Proxy, R]) extends Mock[R] + private[mock] case class Composed[R: Tag](compose: URLayer[Proxy, R]) extends Mock[R] } diff --git a/test/shared/src/main/scala/zio/test/mock/MockClock.scala b/test/shared/src/main/scala/zio/test/mock/MockClock.scala index 2862fbbf2488..c50ea8e9949f 100644 --- a/test/shared/src/main/scala/zio/test/mock/MockClock.scala +++ b/test/shared/src/main/scala/zio/test/mock/MockClock.scala @@ -33,7 +33,7 @@ object MockClock extends Mock[Clock] { object Scheduler extends Effect[Unit, Nothing, Scheduler] object Sleep extends Effect[Duration, Nothing, Unit] - val compose: URServiceBuilder[Proxy, Clock] = { + val compose: URLayer[Proxy, Clock] = { implicit val trace = Tracer.newTrace ZIO .service[Proxy] @@ -48,6 +48,6 @@ object MockClock extends Mock[Clock] { def localDateTime(implicit trace: ZTraceElement): zio.UIO[java.time.LocalDateTime] = proxy(LocalDateTime) } } - .toServiceBuilder + .toLayer } } diff --git a/test/shared/src/main/scala/zio/test/mock/MockConsole.scala b/test/shared/src/main/scala/zio/test/mock/MockConsole.scala index 6eb09b3eaf87..1870558f400c 100644 --- a/test/shared/src/main/scala/zio/test/mock/MockConsole.scala +++ b/test/shared/src/main/scala/zio/test/mock/MockConsole.scala @@ -16,7 +16,7 @@ package zio.test.mock -import zio.{Console, IO, URServiceBuilder, ZIO, ZTraceElement} +import zio.{Console, IO, URLayer, ZIO, ZTraceElement} import zio.internal.stacktracer.Tracer import zio.stacktracer.TracingImplicits.disableAutoTrace @@ -30,7 +30,7 @@ object MockConsole extends Mock[Console] { object PrintLineError extends Effect[Any, IOException, Unit] object ReadLine extends Effect[Unit, IOException, String] - val compose: URServiceBuilder[Proxy, Console] = { + val compose: URLayer[Proxy, Console] = { implicit val trace = Tracer.newTrace ZIO .service[Proxy] @@ -44,6 +44,6 @@ object MockConsole extends Mock[Console] { def readLine(implicit trace: ZTraceElement): IO[IOException, String] = proxy(ReadLine) } ) - .toServiceBuilder + .toLayer } } diff --git a/test/shared/src/main/scala/zio/test/mock/MockRandom.scala b/test/shared/src/main/scala/zio/test/mock/MockRandom.scala index acb8bec8c418..8c264338fb8b 100644 --- a/test/shared/src/main/scala/zio/test/mock/MockRandom.scala +++ b/test/shared/src/main/scala/zio/test/mock/MockRandom.scala @@ -16,7 +16,7 @@ package zio.test.mock -import zio.{Chunk, Random, UIO, URServiceBuilder, ZIO, ZTraceElement} +import zio.{Chunk, Random, UIO, URLayer, ZIO, ZTraceElement} import zio.internal.stacktracer.Tracer import zio.stacktracer.TracingImplicits.disableAutoTrace @@ -43,7 +43,7 @@ object MockRandom extends Mock[Random] { object SetSeed extends Effect[Long, Nothing, Unit] object Shuffle extends Effect[Iterable[Any], Nothing, Iterable[Any]] - val compose: URServiceBuilder[Proxy, Random] = { + val compose: URLayer[Proxy, Random] = { implicit val trace = Tracer.newTrace ZIO .service[Proxy] @@ -80,6 +80,6 @@ object MockRandom extends Mock[Random] { proxy(Shuffle, collection).asInstanceOf[UIO[Collection[A]]] } ) - .toServiceBuilder + .toLayer } } diff --git a/test/shared/src/main/scala/zio/test/mock/MockSystem.scala b/test/shared/src/main/scala/zio/test/mock/MockSystem.scala index 386b0bd3308e..96e7fd35c185 100644 --- a/test/shared/src/main/scala/zio/test/mock/MockSystem.scala +++ b/test/shared/src/main/scala/zio/test/mock/MockSystem.scala @@ -16,7 +16,7 @@ package zio.test.mock -import zio.{IO, System, UIO, URServiceBuilder, ZIO, ZTraceElement} +import zio.{IO, System, UIO, URLayer, ZIO, ZTraceElement} import zio.internal.stacktracer.Tracer import zio.stacktracer.TracingImplicits.disableAutoTrace @@ -32,7 +32,7 @@ object MockSystem extends Mock[System] { object PropertyOrOption extends Effect[(String, Option[String]), Throwable, Option[String]] object LineSeparator extends Effect[Unit, Nothing, String] - val compose: URServiceBuilder[Proxy, System] = { + val compose: URLayer[Proxy, System] = { implicit val trace = Tracer.newTrace ZIO .service[Proxy] @@ -65,6 +65,6 @@ object MockSystem extends Mock[System] { } ) - .toServiceBuilder + .toLayer } } diff --git a/test/shared/src/main/scala/zio/test/mock/internal/ProxyFactory.scala b/test/shared/src/main/scala/zio/test/mock/internal/ProxyFactory.scala index d0b70aa83ae5..e7704bb06137 100644 --- a/test/shared/src/main/scala/zio/test/mock/internal/ProxyFactory.scala +++ b/test/shared/src/main/scala/zio/test/mock/internal/ProxyFactory.scala @@ -19,7 +19,7 @@ package zio.test.mock.internal import zio.stacktracer.TracingImplicits.disableAutoTrace import zio.test.Assertion import zio.test.mock.{Capability, Expectation, Proxy} -import zio.{IO, Tag, UServiceBuilder, ZIO, ZServiceBuilder, ZTraceElement} +import zio.{IO, Tag, ULayer, ZIO, ZLayer, ZTraceElement} import scala.annotation.tailrec import scala.util.Try @@ -35,8 +35,8 @@ object ProxyFactory { /** * Given initial `MockState[R]`, constructs a `Proxy` running that state. */ - def mockProxy[R: Tag](state: MockState[R])(implicit trace: ZTraceElement): UServiceBuilder[Proxy] = - ZServiceBuilder.succeed(new Proxy { + def mockProxy[R: Tag](state: MockState[R])(implicit trace: ZTraceElement): ULayer[Proxy] = + ZLayer.succeed(new Proxy { def invoke[RIn, ROut, I, E, A](invoked: Capability[RIn, I, E, A], args: I): ZIO[ROut, E, A] = { sealed trait MatchResult object MatchResult { diff --git a/test/shared/src/main/scala/zio/test/package.scala b/test/shared/src/main/scala/zio/test/package.scala index 65ef1ed7060d..b6ef92bbbf9d 100644 --- a/test/shared/src/main/scala/zio/test/package.scala +++ b/test/shared/src/main/scala/zio/test/package.scala @@ -66,9 +66,9 @@ package object test extends CompileVariants { with ZEnv object TestEnvironment { - val any: ZServiceBuilder[TestEnvironment, Nothing, TestEnvironment] = - ZServiceBuilder.environment[TestEnvironment](Tracer.newTrace) - val live: ZServiceBuilder[ZEnv, Nothing, TestEnvironment] = { + val any: ZLayer[TestEnvironment, Nothing, TestEnvironment] = + ZLayer.environment[TestEnvironment](Tracer.newTrace) + val live: ZLayer[ZEnv, Nothing, TestEnvironment] = { implicit val trace = Tracer.newTrace Annotations.live ++ Live.default ++ @@ -81,9 +81,9 @@ package object test extends CompileVariants { } } - val liveEnvironment: ServiceBuilder[Nothing, ZEnv] = ZEnv.live + val liveEnvironment: Layer[Nothing, ZEnv] = ZEnv.live - val testEnvironment: ServiceBuilder[Nothing, TestEnvironment] = { + val testEnvironment: Layer[Nothing, TestEnvironment] = { implicit val trace = Tracer.newTrace ZEnv.live >>> TestEnvironment.live } diff --git a/website/sidebars.js b/website/sidebars.js index 142991c75900..b5fa47bb4710 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -42,12 +42,12 @@ module.exports = { type: "category", label: "ZIO Dependencies", items: [ - "datatypes/contextual/zservicebuilder", - "datatypes/contextual/rservicebuilder", - "datatypes/contextual/uservicebuilder", - "datatypes/contextual/servicebuilder", - "datatypes/contextual/urservicebuilder", - "datatypes/contextual/taskservicebuilder" + "datatypes/contextual/zlayer", + "datatypes/contextual/rlayer", + "datatypes/contextual/ulayer", + "datatypes/contextual/layer", + "datatypes/contextual/urlayer", + "datatypes/contextual/tasklayer" ] }, { diff --git a/website/sidebars.json b/website/sidebars.json index 96685eec58ec..1e7816c92624 100644 --- a/website/sidebars.json +++ b/website/sidebars.json @@ -33,12 +33,12 @@ "Contextual Types": [ "datatypes/contextual/index", "datatypes/contextual/has", - "datatypes/contextual/zservicebuilder", - "datatypes/contextual/rservicebuilder", - "datatypes/contextual/uservicebuilder", - "datatypes/contextual/servicebuilder", - "datatypes/contextual/urservicebuilder", - "datatypes/contextual/taskservicebuilder" + "datatypes/contextual/zlayer", + "datatypes/contextual/rlayer", + "datatypes/contextual/ulayer", + "datatypes/contextual/layer", + "datatypes/contextual/urlayer", + "datatypes/contextual/tasklayer" ], "Fiber Primitives": [ "datatypes/fiber/index",