File size: 8,095 Bytes
31e8457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
 * A module providing a generic service interface for spawning child processes.
 *
 * This module provides the `ChildProcessSpawner` service tag which can be
 * implemented by platform-specific packages (e.g., Node.js).
 *
 * @since 4.0.0
 */
import * as Brand from "../../Brand.ts"
import * as Context from "../../Context.ts"
import * as Effect from "../../Effect.ts"
import * as Inspectable from "../../Inspectable.ts"
import type * as PlatformError from "../../PlatformError.ts"
import type * as Scope from "../../Scope.ts"
import type * as Sink from "../../Sink.ts"
import * as Stream from "../../Stream.ts"
import type { Command, KillOptions } from "./ChildProcess.ts"

/**
 * @since 4.0.0
 * @category Models
 */
export type ExitCode = Brand.Branded<number, "ExitCode">

/**
 * @since 4.0.0
 * @category Constructors
 */
export const ExitCode: Brand.Constructor<ExitCode> = Brand.nominal<ExitCode>()

/**
 * @since 4.0.0
 * @category Models
 */
export type ProcessId = Brand.Branded<number, "ProcessId">

/**
 * @since 4.0.0
 * @category Constructors
 */
export const ProcessId: Brand.Constructor<ProcessId> = Brand.nominal<ProcessId>()

/**
 * An `Effect` that adds an unrefed child process back into the parent
 * process's reference count.
 *
 * This value is returned by `ChildProcessHandle.unref` and can be run later to
 * restore the default behavior where the child process keeps the parent
 * process alive.
 *
 * @since 4.0.0
 * @category Models
 */
export type Reref = Effect.Effect<void, PlatformError.PlatformError>

const HandleTypeId = "~effect/ChildProcessSpawner/ChildProcessHandle"

/**
 * A handle to a running child process.
 *
 * @since 4.0.0
 * @category Models
 */
export interface ChildProcessHandle {
  readonly [HandleTypeId]: typeof HandleTypeId
  /**
   * The child process process identifier.
   */
  readonly pid: ProcessId
  /**
   * Waits for the child process to exit and returns the `ExitCode` of the
   * command that was run.
   */
  readonly exitCode: Effect.Effect<ExitCode, PlatformError.PlatformError>
  /**
   * Returns `true` if the child process is still running, otherwise returns
   * `false`.
   */
  readonly isRunning: Effect.Effect<boolean, PlatformError.PlatformError>
  /**
   * Kills the child process with the provided signal.
   *
   * If no signal option is provided, the signal defaults to `SIGTERM`.
   */
  readonly kill: (options?: KillOptions | undefined) => Effect.Effect<void, PlatformError.PlatformError>
  /**
   * The standard input sink for the child process.
   */
  readonly stdin: Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError>
  /**
   * The standard output stream for the child process.
   *
   * Note: Using alongside `all` may cause interleaving of output and unexpected
   * results.
   */
  readonly stdout: Stream.Stream<Uint8Array, PlatformError.PlatformError>
  /**
   * The standard error stream for the child process.
   *
   * Note: Using alongside `all` may cause interleaving of output and unexpected
   * results.
   */
  readonly stderr: Stream.Stream<Uint8Array, PlatformError.PlatformError>
  /**
   * A stream which combines and interleaves all messages output by the child
   * process `stdout` and `stderr` streams.
   */
  readonly all: Stream.Stream<Uint8Array, PlatformError.PlatformError>
  /**
   * Get an input `Sink` for writing to a file descriptor configured via
   * `ChildProcessOptions.additionalFds`.
   *
   * If a file descriptor is accessed that was not configured, returns a drain
   * `Sink`.
   */
  readonly getInputFd: (fd: number) => Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError>
  /**
   * Get an output `Stream` for reading from a file descriptor configured via
   * `ChildProcessOptions.additionalFds`.
   *
   * If a file descriptor is accessed that was not configured, returns an empty
   * `Stream`.
   */
  readonly getOutputFd: (fd: number) => Stream.Stream<Uint8Array, PlatformError.PlatformError>
  /**
   * Allows the parent process to exit independently of this child process.
   *
   * Running this `Effect` removes this child process from the parent process's
   * reference count, so the parent process is allowed to exit without waiting
   * for the child process to finish.
   *
   * The returned `Reref` effect adds the child process back into the parent
   * process's reference count when run, restoring the default behavior.
   *
   * This is the only supported way to re-reference a child process after it
   * has been unrefed.
   *
   * @example
   * ```ts
   * import { NodeServices } from "@effect/platform-node"
   * import { Effect } from "effect"
   * import { ChildProcess } from "effect/unstable/process"
   *
   * const program = Effect.gen(function*() {
   *   const handle = yield* ChildProcess.make`./server`
   *   const reref = yield* handle.unref
   *
   *   yield* Effect.sleep("1 second")
   *
   *   yield* reref
   *   return yield* handle.exitCode
   * }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))
   * ```
   */
  readonly unref: Effect.Effect<Reref, PlatformError.PlatformError>
}

const HandleProto = {
  [HandleTypeId]: HandleTypeId,
  ...Inspectable.BaseProto,
  toJSON(this: ChildProcessHandle) {
    return { _id: "ChildProcessHandle", pid: this.pid }
  }
}

/**
 * Constructs a new `ChildProcessHandle`.
 *
 * @since 4.0.0
 * @category Constructors
 */
export const makeHandle = (params: Omit<ChildProcessHandle, typeof HandleTypeId>): ChildProcessHandle =>
  Object.assign(Object.create(HandleProto), params)

/**
 * Create a new `ChildProcessSpawner` service from a `spawn` funciton
 *
 * @since 4.0.0
 * @category Models
 */
export const make = (spawn: ChildProcessSpawner["Service"]["spawn"]): ChildProcessSpawner["Service"] => {
  const streamString: ChildProcessSpawner["Service"]["streamLines"] = (command, options) =>
    spawn(command).pipe(
      Effect.map((handle) =>
        Stream.decodeText(
          options?.includeStderr === true ? handle.all : handle.stdout
        )
      ),
      Stream.unwrap
    )
  const streamLines: ChildProcessSpawner["Service"]["streamLines"] = (command, options) =>
    Stream.splitLines(streamString(command, options))

  return ChildProcessSpawner.of({
    spawn,
    exitCode: (command) => Effect.scoped(Effect.flatMap(spawn(command), (handle) => handle.exitCode)),
    streamString,
    streamLines,
    lines: (command, options) => Stream.runCollect(streamLines(command, options)),
    string: (command, options) => Stream.mkString(streamString(command, options))
  })
}

/**
 * Service tag for child process spawning.
 *
 * @since 4.0.0
 * @category Service
 */
export class ChildProcessSpawner extends Context.Service<ChildProcessSpawner, {
  /**
   * Spawn a command and return a handle for interaction.
   */
  spawn(
    command: Command
  ): Effect.Effect<ChildProcessHandle, PlatformError.PlatformError, Scope.Scope>

  /**
   * Run a command and return its exit code.
   */
  exitCode(
    command: Command
  ): Effect.Effect<ExitCode, PlatformError.PlatformError>

  /**
   * Stream the output of a command as strings. Optionally include stderr output
   * interleaved with stdout.
   */
  streamString(command: Command, options?: {
    readonly includeStderr?: boolean | undefined
  }): Stream.Stream<string, PlatformError.PlatformError>

  /**
   * Stream the output of a command as lines. Optionally include stderr output
   * interleaved with stdout.
   */
  streamLines(command: Command, options?: {
    readonly includeStderr?: boolean | undefined
  }): Stream.Stream<string, PlatformError.PlatformError>

  /**
   * Run a command and return the lines of its output as an array of strings.
   */
  lines(command: Command, options?: {
    readonly includeStderr?: boolean | undefined
  }): Effect.Effect<Array<string>, PlatformError.PlatformError>

  /**
   * Run a command and return its output as a string.
   */
  string(command: Command, options?: {
    readonly includeStderr?: boolean | undefined
  }): Effect.Effect<string, PlatformError.PlatformError>
}>()("effect/process/ChildProcessSpawner") {}