Hyperlinkv0.8.0-beta.28

NodeWorker

Layer.Layer<Worker.WorkerPlatform, never, never>

Provides the Node WorkerPlatform for worker_threads workers and child process workers, wiring messages, errors, and exits into Effect workers and terminating the worker if graceful shutdown times out.

layers
export const layerPlatform: Layer.Layer<Worker.WorkerPlatform> = Layer.succeed(Worker.WorkerPlatform)(
  Worker.makePlatform<WorkerThreads.Worker | ChildProcess.ChildProcess>()({
    setup({ scope, worker }) {
      const exitDeferred = Deferred.makeUnsafe<void, WorkerError>()
      const thing = "postMessage" in worker ?
        {
          postMessage(msg: any, t?: any) {
            worker.postMessage(msg, t)
          },
          kill: () => worker.terminate(),
          worker
        } :
        {
          postMessage(msg: any, _?: any) {
            worker.send(msg)
          },
          kill: () => worker.kill("SIGKILL"),
          worker
        }
      worker.on("exit", () => {
        Deferred.doneUnsafe(exitDeferred, Exit.void)
      })
      return Effect.as(
        Scope.addFinalizer(
          scope,
          Effect.suspend(() => {
            thing.postMessage([1])
            return Deferred.await(exitDeferred)
          }).pipe(
            Effect.timeout(5000),
            Effect.catchCause(() => Effect.sync(() => thing.kill()))
          )
        ),
        thing
      )
    },
    listen({ deferred, emit, port }) {
      port.worker.on("message", (message) => {
        emit(message)
      })
      port.worker.on("messageerror", (cause) => {
        Deferred.doneUnsafe(
          deferred,
          new WorkerError({
            reason: new WorkerReceiveError({
              message: "An messageerror event was emitted",
              cause
            })
          })
        )
      })
      port.worker.on("error", (cause) => {
        Deferred.doneUnsafe(
          deferred,
          new WorkerError({
            reason: new WorkerReceiveError({
              message: "An error event was emitted",
              cause
            })
          })
        )
      })
      port.worker.on("exit", (code) => {
        Deferred.doneUnsafe(
          deferred,
          new WorkerError({
            reason: new WorkerReceiveError({
              message: "The worker has exited with code: " + code
            })
          })
        )
      })
      return Effect.void
    }
  })
)
Referenced by 1 symbols