| 44 | const send = (_portId: number, message: O, transfers?: ReadonlyArray<unknown>) => |
| 45 | Effect.sync(() => sendUnsafe(_portId, [1, message], transfers as any)) |
| 46 | |
| 47 | const run = <A, E, R>( |
| 48 | handler: (portId: number, message: I) => Effect.Effect<A, E, R> | void |
| 49 | ): Effect.Effect<void, WorkerError, R> => |
| 50 | Effect.scopedWith(Effect.fnUntraced(function*(scope) { |
| 51 | const closeLatch = Deferred.makeUnsafe<void, WorkerError>() |
| 52 | const trackFiber = Fiber.runIn(scope) |
| 53 | const services = yield* Effect.context<R>() |
| 54 | const runFork = Effect.runForkWith(services) |
| 55 | const onExit = (exit: Exit.Exit<any, E>) => { |
| 56 | if (exit._tag === "Failure" && !Cause.hasInterruptsOnly(exit.cause)) { |
| 57 | runFork(Effect.logError("unhandled error in worker", exit.cause)) |
| 58 | } |
| 59 | } |
| 60 | const port = WorkerThreads.parentPort ?? process |
| 61 | function onMessage(message: WorkerRunner.PlatformMessage<I>) { |
| 62 | if (message[0] === 0) { |
| 63 | const result = handler(0, message[1]) |
| 64 | if (Effect.isEffect(result)) { |
| 65 | const fiber = runFork(result) |
| 66 | fiber.addObserver(onExit) |
| 67 | trackFiber(fiber) |
| 68 | } |
| 69 | } else { |
| 70 | if (WorkerThreads.parentPort) { |
| 71 | WorkerThreads.parentPort.close() |
| 72 | } else { |
| 73 | process.channel?.unref() |
| 74 | } |
| 75 | Deferred.doneUnsafe(closeLatch, Exit.void) |
| 76 | } |
| 77 | } |
| 78 | port.on("message", onMessage) |
| 79 | |
| 80 | function onMessageError(cause: unknown) { |
| 81 | Deferred.doneUnsafe( |
| 82 | closeLatch, |
| 83 | new WorkerError({ |
| 84 | reason: new WorkerReceiveError({ |
| 85 | message: "received messageerror event", |
| 86 | cause |
| 87 | }) |
| 88 | }) |
| 89 | ) |
| 90 | } |
| 91 | function onError(cause: unknown) { |
| 92 | Deferred.doneUnsafe( |
| 93 | closeLatch, |
| 94 | new WorkerError({ |
| 95 | reason: new WorkerReceiveError({ |
| 96 | message: "received error event", |
| 97 | cause |
| 98 | }) |
| 99 | }) |
| 100 | ) |
| 101 | } |
| 102 | if (WorkerThreads.parentPort) { |
| 103 | WorkerThreads.parentPort.on("messageerror", onMessageError) |