@systemfsoftware/effect-daemon-process 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Copyright (c) 2026 Ryan Lee (systemfsoftware)
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright 2026 Ryan Lee (systemfsoftware)
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # @systemfsoftware/effect-daemon-process
2
+
3
+ The `@systemfsoftware/effect-daemon-spec` medium over operating-system child processes: a
4
+ supervised command spec spawned through a `ChildProcessSpawner`, its exit status and terminating
5
+ signal reported as observed, and its shutdown mapped onto SIGTERM and SIGKILL.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pnpm add @systemfsoftware/effect-daemon-process
11
+ ```
12
+
13
+ ## Features
14
+
15
+ - **A command is the child.** The program is a `ChildProcess.Command` — argv, environment, cwd,
16
+ inherited descriptors — and the medium spawns it once per incarnation through whichever
17
+ `ChildProcessSpawner` the composition root provides.
18
+ - **Readiness read from standard output.** `readyLine` names the line that counts as ready; without
19
+ it a child is ready as soon as it is spawned. Readiness is raced against the supervisor's start
20
+ deadline like any other medium signal, and a child that never writes its line misses the deadline.
21
+ - **Exit status and signal reported as received.** A non-zero exit code and a signal death each
22
+ become an `ExitReport`; a clean exit is `Normal`. Nothing claims a `Cause`, because a process does
23
+ not hand one over.
24
+ - **The operating system's own signals.** `Brutal` sends SIGKILL at once, `Graceful` sends SIGTERM
25
+ and lets the mode's window elapse before the force, and `Infinity` sends SIGTERM and waits for the
26
+ child to end.
27
+ - **Proven against a real oracle.** `ProcessMedium.conformanceDriver` proves the medium against the
28
+ fibre reference on the whole `Conformance.Scenarios` catalogue, with a Node fixture program whose
29
+ control channel scripts the child's own stdin.
30
+
31
+ ## Usage
32
+
33
+ ```ts
34
+ import { NodeChildProcessSpawner, NodeFileSystem, NodePath } from '@effect/platform-node-shared'
35
+ import { ProcessMedium } from '@systemfsoftware/effect-daemon-process'
36
+ import { Supervisor } from '@systemfsoftware/effect-daemon-spec'
37
+ import { Effect, Layer } from 'effect'
38
+ import { ChildProcess } from 'effect/unstable/process'
39
+
40
+ const program = ChildProcess.make('node', ['server.js'], { env: { PORT: '8080' } })
41
+
42
+ const supervisor = Supervisor.make('api').pipe(
43
+ Supervisor.children([
44
+ Supervisor.ChildSpecs.on(ProcessMedium.port)('api', program, {
45
+ restartType: 'transient',
46
+ shutdown: { _tag: 'Graceful', millis: 5_000 },
47
+ startTimeoutMillis: 2_000,
48
+ }),
49
+ ]),
50
+ )
51
+
52
+ const Api = Layer.provide(
53
+ supervisor.layer,
54
+ Layer.merge(
55
+ ProcessMedium.layer({ readyLine: 'listening' }),
56
+ NodeChildProcessSpawner.layer.pipe(Layer.provide(Layer.merge(NodeFileSystem.layer, NodePath.layer))),
57
+ ),
58
+ )
59
+ ```
60
+
61
+ `ProcessMedium.layer(options)` binds the port to a medium; the spawner stays the composition root's
62
+ choice, so the same supervisor runs on any platform that provides one. The medium reads `stdout` for
63
+ the readiness line, so a program that needs it should write it there.
64
+
65
+ ## What an abnormal termination carries
66
+
67
+ The medium declares `{ reporting: 'exit', groupStop: 'atomic' }`, so every failure it reports is an
68
+ `ExitReport`:
69
+
70
+ | Child outcome | `code` | `signal` |
71
+ | ------------------------------------ | ------------- | ------------------------------------------------------- |
72
+ | A clean exit (`0`) | — | — (reported as `Normal`) |
73
+ | Any other exit code | the exit code | empty — no signal ended it |
74
+ | Killed by a signal | `0` | the signal the platform names, e.g. `SIGKILL` |
75
+ | Stopped by the supervisor | — | — (reported as `Shutdown`) |
76
+ | A spawn failure, e.g. a missing file | — | — (the start fails with the platform's `PlatformError`) |
77
+
78
+ ## Stopping a child
79
+
80
+ `stop(evidence, mode)` latches the child's report as `Shutdown` before any signal goes out — the
81
+ ordering the fibre medium gives an interrupted fibre — and then sends the mode's signal. The stop
82
+ returns only once the platform's `kill` has awaited the process group's exit, which is what the
83
+ `atomic` declaration promises: no child is left running once the group stop returns.
84
+
85
+ ## Proving the medium
86
+
87
+ ```ts
88
+ const proof = Effect.gen(function*() {
89
+ const report = yield* Conformance.prove(ProcessMedium.conformanceDriver({ fixturePath: './child-script.mjs' }))
90
+ return Conformance.isConforming(report) // every scripted lifecycle matched the fibre reference
91
+ })
92
+ ```
93
+
94
+ The driver launches `node <fixturePath>` once per incarnation, each with its own stdin channel.
95
+ `control.advance(step, generation)` writes the step to exactly that generation's child. A step
96
+ for an incarnation that has not started yet is held until it starts, so a child that is still
97
+ stopping can never take a step meant for its successor. `ProcessMedium.fixtureReadyLine`
98
+ (`READY`) is the line the fixture writes when a `BecomeReady` step reaches it, which is what a
99
+ medium under proof reads as readiness.
100
+
101
+ ## Verification
102
+
103
+ ```bash
104
+ pnpm --filter @systemfsoftware/effect-daemon-process typecheck
105
+ pnpm --filter @systemfsoftware/effect-daemon-process lint
106
+ pnpm --filter @systemfsoftware/effect-daemon-process test
107
+ pnpm --filter @systemfsoftware/effect-daemon-process test:contract
108
+ pnpm --filter @systemfsoftware/effect-daemon-process build
109
+ ```
110
+
111
+ ## License
112
+
113
+ Apache-2.0
package/dist/mod.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { Layer, Scope } from "effect";
2
+ import * as PlatformError from "effect/PlatformError";
3
+ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
4
+ import { Supervisor } from "@systemfsoftware/effect-daemon-spec";
5
+ import { Conformance } from "@systemfsoftware/effect-daemon-conformance";
6
+ //#region src/ProcessMedium/conformance-driver.d.ts
7
+ declare const fixtureReadyLine = "READY";
8
+ interface ProcessConformanceDriverOptions {
9
+ readonly fixturePath: string;
10
+ readonly nodePath?: string | undefined;
11
+ readonly fixtureArgs?: ReadonlyArray<string> | undefined;
12
+ }
13
+ declare const conformanceDriver: (options: ProcessConformanceDriverOptions) => Conformance.ConformanceDriver<ChildProcess.Command, PlatformError.PlatformError, ChildProcessSpawner.ChildProcessSpawner>;
14
+ //#endregion
15
+ //#region src/ProcessMedium/medium.d.ts
16
+ /** What a process medium can say and honour (R16): the exit status and signal it observed, and a group stop that leaves nothing running. */
17
+ declare const declaration: Supervisor.Medium.MediumDeclaration;
18
+ /** How a process medium reads a child's readiness (R10, KTD17). */
19
+ interface ProcessMediumOptions {
20
+ /**
21
+ * The line the child writes to standard output when it is ready. Absent, a child counts
22
+ * as ready as soon as it is spawned — the process analogue of readiness-on-start.
23
+ */
24
+ readonly readyLine?: string | undefined;
25
+ }
26
+ /** The port a process child is declared against (KTD9): the command spec is the program. */
27
+ declare const port: import("effect/Context").Service<Supervisor.Medium.MediumPortShape<ChildProcess.Command, PlatformError.PlatformError, ChildProcessSpawner.ChildProcessSpawner | Scope.Scope>, Supervisor.Medium.MediumPortShape<ChildProcess.Command, PlatformError.PlatformError, ChildProcessSpawner.ChildProcessSpawner | Scope.Scope>>;
28
+ /**
29
+ * The port bound to a process medium (KTD9): the composition root provides it beside the
30
+ * `ChildProcessSpawner` of the platform it chose, so this package depends on the port and
31
+ * never on an implementation.
32
+ */
33
+ declare const layer: (options?: ProcessMediumOptions) => Layer.Layer<Supervisor.Medium.MediumPortShape<ChildProcess.Command, PlatformError.PlatformError, Scope.Scope | ChildProcessSpawner.ChildProcessSpawner>>;
34
+ declare namespace mod_d_exports {
35
+ export { ProcessConformanceDriverOptions, ProcessMediumOptions, conformanceDriver, declaration, fixtureReadyLine, layer, port };
36
+ }
37
+ //#endregion
38
+ export { mod_d_exports as ProcessMedium };
package/dist/mod.mjs ADDED
@@ -0,0 +1,169 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { Deferred, Duration, Effect, HashMap, Layer, Match, Option, Queue, Ref, Stream } from "effect";
3
+ import "effect/PlatformError";
4
+ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
5
+ import { Supervisor } from "@systemfsoftware/effect-daemon-spec";
6
+ //#region src/ProcessMedium/medium.ts
7
+ /**
8
+ * The `effect-daemon-spec` medium over operating-system child processes (R20, KTD17): a
9
+ * child's program is a command spec, spawned through the `ChildProcessSpawner` its
10
+ * composition root chose, and every signal it sends is the operating system's own — SIGTERM
11
+ * for a graceful stop, and SIGKILL when the stop is brutal or its window elapses.
12
+ *
13
+ * @since 0.1.0
14
+ */
15
+ /** What a process medium can say and honour (R16): the exit status and signal it observed, and a group stop that leaves nothing running. */
16
+ const declaration = {
17
+ reporting: "exit",
18
+ groupStop: "atomic"
19
+ };
20
+ /** The port a process child is declared against (KTD9): the command spec is the program. */
21
+ const port = Supervisor.Medium.MediumPort("ProcessMedium");
22
+ const ProcessStartedTypeId = Symbol.for("@systemfsoftware/effect-daemon-process/ProcessMedium/Started");
23
+ const NO_EXIT_CODE = 0;
24
+ /** The platform's own wording for a signal death, `Process interrupted due to receipt of signal: 'SIGKILL'`. */
25
+ const SIGNAL_IN_DETAIL = /signal: '([A-Z0-9]+)'/;
26
+ const NORMAL = { _tag: "Normal" };
27
+ const SHUTDOWN = { _tag: "Shutdown" };
28
+ const signalNameIn = (detail) => Option.getOrElse(Option.flatMap(Option.fromNullishOr(SIGNAL_IN_DETAIL.exec(detail)), (found) => Option.fromNullishOr(found[1])), () => "");
29
+ const abnormalExitOf = (code, signal) => ({
30
+ _tag: "Abnormal",
31
+ report: {
32
+ _tag: "ExitReport",
33
+ code,
34
+ signal
35
+ }
36
+ });
37
+ const exitedOf = (code) => Match.value(code).pipe(Match.when(0, () => NORMAL), Match.orElse(() => abnormalExitOf(code, "")));
38
+ const terminationOf = (exit) => Match.value(exit).pipe(Match.tag("Exited", (exited) => exitedOf(exited.code)), Match.tag("Signaled", (signaled) => abnormalExitOf(NO_EXIT_CODE, signalNameIn(signaled.detail))), Match.exhaustive);
39
+ const processStartedOf = (handle, ready, stopping) => ({
40
+ [Supervisor.Medium.StartedTypeId]: Supervisor.Medium.StartedTypeId,
41
+ [ProcessStartedTypeId]: ProcessStartedTypeId,
42
+ ready,
43
+ handle,
44
+ stopping
45
+ });
46
+ const isProcessStarted = (evidence) => ProcessStartedTypeId in evidence;
47
+ const processOf = (evidence) => Option.liftPredicate(evidence, isProcessStarted);
48
+ /**
49
+ * A signal name reaches the medium only through the failure `exitCode` raises, so the
50
+ * platform's own words are the detail this observation carries.
51
+ */
52
+ const platformDetailOf = (error) => error.reason.cause instanceof globalThis.Error ? error.reason.cause.message : error.message;
53
+ const observationOf = (handle) => Effect.match(handle.exitCode, {
54
+ onSuccess: (code) => ({
55
+ _tag: "Exited",
56
+ code
57
+ }),
58
+ onFailure: (error) => ({
59
+ _tag: "Signaled",
60
+ detail: platformDetailOf(error)
61
+ })
62
+ });
63
+ const readyLineSeen = (handle, readyLine, ready) => Effect.ignore(Stream.runForEach(Stream.splitLines(Stream.decodeText(handle.stdout)), (line) => line === readyLine ? Deferred.succeed(ready, void 0) : Effect.void));
64
+ const watchReady = (handle, ready, options) => Option.match(Option.fromNullishOr(options.readyLine), {
65
+ onNone: () => Effect.asVoid(Deferred.succeed(ready, void 0)),
66
+ onSome: (line) => Effect.asVoid(Effect.forkScoped(readyLineSeen(handle, line, ready)))
67
+ });
68
+ /** R4's modes in the operating system's signals: brutal forces at once, a graceful stop forces when its window elapses, infinity never forces. */
69
+ const killOptionsOf = (mode) => Match.value(mode).pipe(Match.tag("Brutal", () => ({ killSignal: "SIGKILL" })), Match.tag("Graceful", (graceful) => ({
70
+ killSignal: "SIGTERM",
71
+ forceKillAfter: Duration.millis(graceful.millis)
72
+ })), Match.tag("Infinity", () => ({ killSignal: "SIGTERM" })), Match.exhaustive);
73
+ /**
74
+ * Owned shutdown (R4, R15): the stop latch answers the report as a `Shutdown` before any
75
+ * signal goes out — the ordering the fiber medium gives an interrupted fiber — and the
76
+ * kill's own await is what makes the stop atomic, because the platform's `kill` returns
77
+ * only once the process group has gone.
78
+ */
79
+ const stopOf = (self, mode) => Effect.andThen(Deferred.succeed(self.stopping, void 0), Effect.ignore(self.handle.kill(killOptionsOf(mode))));
80
+ const spawnIn = (command, options) => Effect.gen(function* () {
81
+ const handle = yield* (yield* ChildProcessSpawner.ChildProcessSpawner).spawn(command);
82
+ const ready = yield* Deferred.make();
83
+ const stopping = yield* Deferred.make();
84
+ yield* watchReady(handle, ready, options);
85
+ return processStartedOf(handle, Deferred.await(ready), stopping);
86
+ });
87
+ const mediumOf = (options) => Supervisor.Medium.make({
88
+ declaration,
89
+ start: (command) => spawnIn(command, options),
90
+ report: (evidence) => Option.match(processOf(evidence), {
91
+ onNone: () => Effect.succeed(SHUTDOWN),
92
+ onSome: (self) => Effect.raceFirst(Effect.as(Deferred.await(self.stopping), SHUTDOWN), Effect.map(observationOf(self.handle), terminationOf))
93
+ }),
94
+ probe: (evidence) => Option.match(processOf(evidence), {
95
+ onNone: () => Effect.succeed(false),
96
+ onSome: (self) => Effect.orElseSucceed(self.handle.isRunning, () => true)
97
+ }),
98
+ stop: (evidence, mode) => Option.match(processOf(evidence), {
99
+ onNone: () => Effect.succeed(Supervisor.Medium.stopped),
100
+ onSome: (self) => Effect.as(stopOf(self, mode), Supervisor.Medium.stopped)
101
+ })
102
+ });
103
+ /**
104
+ * The port bound to a process medium (KTD9): the composition root provides it beside the
105
+ * `ChildProcessSpawner` of the platform it chose, so this package depends on the port and
106
+ * never on an implementation.
107
+ */
108
+ const layer = (options) => Layer.succeed(port, { medium: mediumOf(options ?? {}) });
109
+ //#endregion
110
+ //#region src/ProcessMedium/conformance-driver.ts
111
+ const fixtureReadyLine = "READY";
112
+ const TEARDOWN_FORCE_KILL = "1 second";
113
+ const encoder = new TextEncoder();
114
+ const commandLineOf = (options) => [options.fixturePath, ...options.fixtureArgs ?? []];
115
+ const heldFor = (buffered, generation) => Option.getOrElse(HashMap.get(buffered, generation), () => []);
116
+ const takeHeld = (channels, generation) => Effect.map(Ref.modify(channels.waiting, (buffered) => [heldFor(buffered, generation), HashMap.remove(buffered, generation)]), (held) => held);
117
+ const claimChannel = (channels) => Effect.gen(function* () {
118
+ const generation = yield* Ref.modify(channels.launched, (count) => [count, count + 1]);
119
+ const steps = yield* Queue.unbounded();
120
+ yield* Queue.offerAll(steps, yield* takeHeld(channels, generation));
121
+ yield* Ref.update(channels.open, (open) => HashMap.set(open, generation, steps));
122
+ return steps;
123
+ });
124
+ const stdinFor = (channels) => Stream.unwrap(Effect.map(claimChannel(channels), Stream.fromQueue));
125
+ const programOf = (options, channels) => ChildProcess.make(options.nodePath ?? process.execPath, commandLineOf(options), {
126
+ stdin: stdinFor(channels),
127
+ forceKillAfter: TEARDOWN_FORCE_KILL
128
+ });
129
+ const offerTo = (channels) => (step, generation) => Effect.gen(function* () {
130
+ const item = encoder.encode(`${step._tag}\n`);
131
+ const open = yield* Ref.get(channels.open);
132
+ yield* Option.match(HashMap.get(open, generation), {
133
+ onSome: (steps) => Effect.asVoid(Queue.offer(steps, item)),
134
+ onNone: () => Ref.update(channels.waiting, (buffered) => HashMap.set(buffered, generation, [...heldFor(buffered, generation), item]))
135
+ });
136
+ });
137
+ const launchOf = (options) => Effect.gen(function* () {
138
+ const channels = {
139
+ launched: yield* Ref.make(0),
140
+ open: yield* Ref.make(HashMap.empty()),
141
+ waiting: yield* Ref.make(HashMap.empty())
142
+ };
143
+ return {
144
+ program: programOf(options, channels),
145
+ control: { advance: offerTo(channels) }
146
+ };
147
+ });
148
+ const conformanceDriver = (options) => ({
149
+ name: "process",
150
+ declaration,
151
+ scenario: {
152
+ millis: 3e4,
153
+ startTimeoutMillis: 3e3,
154
+ livenessTickMillis: 3e4
155
+ },
156
+ port,
157
+ launch: () => launchOf(options)
158
+ });
159
+ //#endregion
160
+ //#region src/ProcessMedium/mod.ts
161
+ var ProcessMedium_exports = /* @__PURE__ */ __exportAll({
162
+ conformanceDriver: () => conformanceDriver,
163
+ declaration: () => declaration,
164
+ fixtureReadyLine: () => fixtureReadyLine,
165
+ layer: () => layer,
166
+ port: () => port
167
+ });
168
+ //#endregion
169
+ export { ProcessMedium_exports as ProcessMedium };
@@ -0,0 +1,13 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ //#endregion
13
+ export { __exportAll as t };
package/package.json ADDED
@@ -0,0 +1,89 @@
1
+ {
2
+ "name": "@systemfsoftware/effect-daemon-process",
3
+ "license": "Apache-2.0",
4
+ "version": "0.1.0",
5
+ "author": "Ryan Lee <drdgvhbh@gmail.com>",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/systemfsoftware/systemfsoftware.git",
9
+ "directory": "packages/effect-daemon-process"
10
+ },
11
+ "homepage": "https://github.com/systemfsoftware/systemfsoftware/tree/main/packages/effect-daemon-process#readme",
12
+ "bugs": "https://github.com/systemfsoftware/systemfsoftware/issues",
13
+ "description": "The effect-daemon-spec medium over operating-system child processes — a command spec spawned through ChildProcessSpawner, its exit code and terminating signal reported as observed, and its shutdown mapped to SIGTERM and SIGKILL.",
14
+ "keywords": [
15
+ "effect",
16
+ "effect-ts",
17
+ "supervision",
18
+ "supervisor",
19
+ "daemon",
20
+ "process",
21
+ "child-process"
22
+ ],
23
+ "type": "module",
24
+ "files": [
25
+ "dist",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/mod.d.ts",
32
+ "default": "./dist/mod.mjs"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "dependencies": {
37
+ "@systemfsoftware/effect-cell-types": "^10.2.0",
38
+ "@systemfsoftware/effect-daemon-conformance": "^0.1.0",
39
+ "@systemfsoftware/effect-daemon-spec": "^4.2.0"
40
+ },
41
+ "devDependencies": {
42
+ "@effect/platform-node-shared": "4.0.0-rc.117",
43
+ "@microsoft/api-extractor": "^7.59.1",
44
+ "@systemfsoftware/arethetypeswrong-cli": "^4.2.0",
45
+ "@systemfsoftware/conformance-spec": "^0.1.0",
46
+ "@systemfsoftware/effect-gherkin-spec": "^5.0.0",
47
+ "@systemfsoftware/effect-schema-law": "^3.0.0",
48
+ "@systemfsoftware/effect-schema-vite": "^2.2.5",
49
+ "@systemfsoftware/oxlint-config-recommended": "^3.1.0",
50
+ "@systemfsoftware/stryker-config": "^0.1.0",
51
+ "@systemfsoftware/stryker-ignorer-effect-schema-declarations": "^0.1.1",
52
+ "@systemfsoftware/stryker-ignorer-in-source-vitest-block": "^0.1.1",
53
+ "@systemfsoftware/stryker-js": "^10.1.1",
54
+ "@systemfsoftware/stryker-js-typescript-checker": "^7.0.5",
55
+ "@systemfsoftware/stryker-js-vitest-runner": "^7.1.1",
56
+ "@systemfsoftware/stryker-test-contribution": "^3.0.3",
57
+ "@systemfsoftware/tsconfig": "^2.0.1",
58
+ "@systemfsoftware/tsdown-config": "^0.1.0",
59
+ "@systemfsoftware/vitest": "^0.1.0",
60
+ "@systemfsoftware/vitest-config": "^0.1.0",
61
+ "@types/node": "^26",
62
+ "effect": "4.0.0-rc.117",
63
+ "fast-check": "^4",
64
+ "oxlint": "~1.82.0",
65
+ "rimraf": "^6.1.3",
66
+ "tsdown": "^0.23.0",
67
+ "typescript": "^7",
68
+ "vitest": "^5"
69
+ },
70
+ "peerDependencies": {
71
+ "effect": "4.0.0-rc.117",
72
+ "typescript": ">=7.0.0"
73
+ },
74
+ "publishConfig": {
75
+ "provenance": true
76
+ },
77
+ "scripts": {
78
+ "clean": "rimraf dist",
79
+ "build": "tsdown -l warn && pnpm api:check",
80
+ "typecheck": "tsc -b",
81
+ "test": "vitest run --project unit --project conformance",
82
+ "test:contract": "vitest run --project contract",
83
+ "mutation": "stryker run",
84
+ "lint": "f=${OXLINT_FORMAT:-${AGENT:+agent}}; oxlint . --format=${f:-default}",
85
+ "attw": "attw --pack .",
86
+ "api:check": "api-extractor-quiet run",
87
+ "api:update": "api-extractor run --local"
88
+ }
89
+ }