Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Daemon fiber doesn't cleanup on program exit #7907

@guersam

Description

@guersam

Usecase

I have a background process (fiber) that can be stopped between deployments. To track the status of the process, I'd like log its termination.

Sample code

//> using scala "2.13.10"
//> using dep "dev.zio::zio:2.0.10"

import zio._

object Main extends ZIOAppDefault {

  def track[R, E, A](tag: String)(zio: ZIO[R, E, A]): ZIO[R with Scope, E, A] =
    zio
      .onInterrupt(ZIO.debug(s"$tag Interrupt"))
      .onExit(exit => ZIO.debug((s"$tag Exit", exit)))
      .tapErrorCause(cause => ZIO.debug((s"$tag Error", cause)))
      // .withFinalizer(_ => ZIO.debug(s"$tag Finalizer")) // Adding this makes scala-cli hang

  val task =
    ZIO.debug("Running...")
      .repeat(Schedule.fixed(1.seconds) && Schedule.recurs(5))

  val run =
    track("Outer") {
      for {
        _ <- track("Inner")(task).fork
        _ <- track("Daemon")(task).forkDaemon
        _ <- ZIO.never
      } yield ()
    }
}

Steps to reproduce

  1. $ scala-cli https://gist.github.com/guersam/96f51168a7bc1581c67094c5e2651264
  2. Stop the process using Ctrl + C within 10 seconds

Expected result

"Inner", "Outer", "Daemon" fibers log some combinations of "Interrupt", "Exit", "Error", "Finalizer"

Actual result

"Inner" and "Outer" tasks log about interrupt, but "Daemon" doesn't.

Running...
Running...
Running...
^COuter Interrupt
Inner Interrupt
(Inner Exit,Failure(Then(Then(Interrupt(Runtime(4,1678276602161,),Stack trace for thread "zio-fiber-":
),Interrupt(Runtime(4,1678276602161,),Stack trace for thread "zio-fiber-":
)),Interrupt(Runtime(4,1678276602161,),Stack trace for thread "zio-fiber-":
))))
(Outer Exit,Failure(Then(Interrupt(Runtime(3,1678276602159,),Stack trace for thread "zio-fiber-3":
),Interrupt(Runtime(3,1678276602159,),Stack trace for thread "zio-fiber-3":
))))

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions