MCPcopy Create free account
hub / github.com/Effect-TS/effect / run

Function run

packages/platform/node/src/NodeWorkerRunner.ts:51–125  ·  view source on GitHub ↗
(
        handler: (portId: number, message: I) => Effect.Effect<A, E, R> | void
      )

Source from the content-addressed store, hash-verified

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

Callers 2

withHandlerFunction · 0.50
withStaticFilesFunction · 0.50

Calls 6

sendRawFunction · 0.85
contextMethod · 0.80
addFinalizerMethod · 0.80
onMethod · 0.65
awaitMethod · 0.65
syncMethod · 0.45

Tested by 2

withHandlerFunction · 0.40
withStaticFilesFunction · 0.40