-
-
Notifications
You must be signed in to change notification settings - Fork 225
/
worker.ts
65 lines (61 loc) · 1.91 KB
/
worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import * as Worker from "@effect/platform/Worker"
import { WorkerError } from "@effect/platform/WorkerError"
import * as Deferred from "effect/Deferred"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as Layer from "effect/Layer"
import * as Scope from "effect/Scope"
import type * as WorkerThreads from "node:worker_threads"
const platformWorkerImpl = Worker.makePlatform<WorkerThreads.Worker>()({
setup({ scope, worker }) {
return Effect.flatMap(Deferred.make<void>(), (exitDeferred) => {
worker.on("exit", () => {
Deferred.unsafeDone(exitDeferred, Exit.void)
})
return Effect.as(
Scope.addFinalizer(
scope,
Effect.suspend(() => {
worker.postMessage([1])
return Deferred.await(exitDeferred)
}).pipe(
Effect.timeout(5000),
Effect.catchAllCause(() => Effect.sync(() => worker.terminate()))
)
),
worker
)
})
},
listen({ deferred, emit, port }) {
port.on("message", (message) => {
emit(message)
})
port.on("messageerror", (cause) => {
Deferred.unsafeDone(
deferred,
new WorkerError({ reason: "decode", cause })
)
})
port.on("error", (cause) => {
Deferred.unsafeDone(deferred, new WorkerError({ reason: "unknown", cause }))
})
port.on("exit", (code) => {
Deferred.unsafeDone(
deferred,
new WorkerError({ reason: "unknown", cause: new Error(`exited with code ${code}`) })
)
})
return Effect.void
}
})
/** @internal */
export const layerWorker = Layer.succeed(Worker.PlatformWorker, platformWorkerImpl)
/** @internal */
export const layerManager = Layer.provide(Worker.layerManager, layerWorker)
/** @internal */
export const layer = (spawn: (id: number) => WorkerThreads.Worker) =>
Layer.merge(
layerManager,
Worker.layerSpawner(spawn)
)