Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NodeRuntime.ts

81 lines2.4 KB

1/**
2 * Node-compatible process runner for Effect programs.
3 *
4 * This module provides the shared `runMain` implementation used by
5 * Node-compatible platform packages. Use it at the outer edge of a CLI, script,
6 * worker, server, or test harness when a single Effect should become the main
7 * fiber for the process while still following Node signal and exit-code
8 * conventions.
9 *
10 * **Mental model**
11 *
12 * `runMain` starts the supplied Effect as the process root. While that fiber is
13 * running, `SIGINT` and `SIGTERM` are translated into fiber interruption so
14 * scoped resources and finalizers get a chance to run. After the fiber exits,
15 * the signal listeners are removed and the configured teardown decides the
16 * process exit code.
17 *
18 * **Common tasks**
19 *
20 * - Launch a command-line program or long-running service from an Effect.
21 * - Share the same main-runner behavior across Node-compatible packages.
22 * - Customize teardown or runtime error reporting with the `runMain` options.
23 *
24 * **Gotchas**
25 *
26 * Clean success lets the Node event loop drain naturally instead of forcing
27 * `process.exit(0)`. Signal-triggered interruption or a non-zero teardown code
28 * calls `process.exit`, so long-lived handles should be acquired in Effect
29 * scopes and released by finalizers.
30 *
31 * @since 4.0.0
32 */
33import type { Effect } from "effect/Effect"
34import * as Runtime from "effect/Runtime"
35​
36/**
37 * Runs an Effect as the Node process main program, interrupting the fiber on
38 * `SIGINT` or `SIGTERM` and invoking the configured teardown to determine the
39 * process exit code.
40 *
41 * @category running
42 * @since 4.0.0
43 */
44export const runMain: {
45 (
46 options?: {
47 readonly disableErrorReporting?: boolean | undefined
48 readonly teardown?: Runtime.Teardown | undefined
49 }
50 ): <E, A>(effect: Effect<A, E>) => void
51 <E, A>(
52 effect: Effect<A, E>,
53 options?: {
54 readonly disableErrorReporting?: boolean | undefined
55 readonly teardown?: Runtime.Teardown | undefined
56 }
57 ): void
58} = Runtime.makeRunMain(({
59 fiber,
60 teardown
61}) => {
62 let receivedSignal = false
63​
64 fiber.addObserver((exit) => {
65 process.removeListener("SIGINT", onSigint)
66 process.removeListener("SIGTERM", onSigint)
67 teardown(exit, (code) => {
68 if (receivedSignal || code !== 0) {
69 process.exit(code)
70 }
71 })
72 })
73​
74 function onSigint() {
75 receivedSignal = true
76 fiber.interruptUnsafe(fiber.id)
77 }
78​
79 process.on("SIGINT", onSigint)
80 process.on("SIGTERM", onSigint)
81})