Created
August 7, 2024 03:40
-
-
Save vanhtuan0409/d60e2cab06cfef4ec591e915e97e66eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//> using dep dev.zio::zio::2.1.7 | |
//> using dep dev.zio::zio-logging::2.3.0 | |
import zio._ | |
object Program extends ZIOAppDefault { | |
override val bootstrap: ZLayer[ZIOAppArgs, Any, Any] = { | |
Runtime.removeDefaultLoggers >>> zio.logging.consoleLogger() | |
} | |
def debugInterrupt(name: String) = (fibers: Set[FiberId]) => { | |
for { | |
fn <- ZIO.fiberId.map(_.threadName) | |
_ <- ZIO.logInfo( | |
s"The $fn fiber which is the underlying fiber of the $name task " + | |
s"interrupted by ${fibers.map(_.threadName).mkString(", ")}" | |
) | |
} yield () | |
} | |
def task[R, E, A](name: String)(effect: ZIO[R, E, A]): ZIO[R, E, A] = { | |
val task = for { | |
_ <- ZIO.logInfo(s"Starting task $name") | |
res <- effect.onInterrupt(debugInterrupt(name)) | |
} yield res | |
task.ensuring(ZIO.logInfo(s"Stopping task $name")) | |
} | |
override def run: IO[Throwable, Unit] = { | |
val daemonFibs = Seq( | |
task("server") { | |
val task = for { | |
_ <- ZIO.logInfo("running 1 server task") | |
// _ <- ZIO.fail("unexpected error") | |
} yield () | |
val sched = Schedule.spaced(Duration.fromSeconds(1)) | |
task | |
.catchAllCause(ZIO.logErrorCause("safe guard protection", _)) | |
.repeat(sched) | |
.unit | |
}, | |
task("temporal") { | |
for { | |
_ <- ZIO.sleep(Duration.fromSeconds(5)) | |
_ <- ZIO.interrupt | |
} yield () | |
} | |
).map { fib => | |
fib.catchAllCause { err => | |
ZIO.logErrorCause(s"Failed to handle error:", err) | |
} | |
} | |
val blockingFibs = Seq( | |
task("blocking task") { | |
ZIO.attemptBlockingInterrupt { | |
while (true) { | |
Thread.sleep(1000) | |
println("!!! doing 1 blocking task") | |
} | |
} | |
} | |
) | |
val allRunningFibs = daemonFibs ++ blockingFibs | |
task("main") { | |
ZIO.raceFirst(allRunningFibs.head, allRunningFibs.tail) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment