1/**
2 * Worker-side primitives for worker-like runtimes.
3 *
4 * A `WorkerRunner` receives messages tagged by a numeric port id, sends replies
5 * back through the same transport, and can expose disconnect notifications. The
6 * module also defines the small platform message shape and the
7 * `WorkerRunnerPlatform` service that starts a platform-specific runner.
8 *
9 * @stability unstable
10 * @since 4.0.0
11 */
12import * as Context from "../Context.ts"
13import type * as Effect from "../Effect.ts"
14import type * as Queue from "../Queue.ts"
15import type { WorkerError } from "./WorkerError.ts"
16
17/**
18 * Platform-neutral worker runner that receives inbound messages by port ID,
19 * sends outbound messages, and optionally exposes disconnect notifications.
20 *
21 * @stability unstable
22 * @category models
23 * @since 4.0.0
24 */
25export interface WorkerRunner<O = unknown, I = unknown> {
26 readonly run: <A, E, R>(
27 handler: (portId: number, message: I) => Effect.Effect<A, E, R> | void
28 ) => Effect.Effect<void, WorkerError, R>
29 readonly send: (
30 portId: number,
31 message: O,
32 transfers?: ReadonlyArray<unknown>
33 ) => Effect.Effect<void>
34 readonly sendUnsafe: (
35 portId: number,
36 message: O,
37 transfers?: ReadonlyArray<unknown>
38 ) => void
39 readonly disconnects?: Queue.Dequeue<number> | undefined
40}
41
42/**
43 * Wire protocol message used by worker platforms: a request carrying input or a
44 * close signal.
45 *
46 * @stability unstable
47 * @category models
48 * @since 4.0.0
49 */
50export type PlatformMessage<I> = readonly [request: 0, I] | readonly [close: 1]
51
52/**
53 * Context service that starts a platform-specific `WorkerRunner`.
54 *
55 * @stability unstable
56 * @category services
57 * @since 4.0.0
58 */
59export class WorkerRunnerPlatform extends Context.Service<WorkerRunnerPlatform, {
60 readonly start: <O = unknown, I = unknown>() => Effect.Effect<WorkerRunner<O, I>, WorkerError>
61}>()("effect/workers/WorkerRunner/WorkerRunnerPlatform") {}