Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 272 lines 8.88 KB
Raw
1 import { describe, expect, it } from 'vitest';
2 import { Cause, Deferred, Effect, Exit, Option } from 'effect';
3 import { ChildProcessExited, ChildProcessSignaled } from 'src/effects/child-process-exited';
4 import { ReportedFailure } from 'src/effects/report-failure';
5 import { ExitAction, exitActionFor, makeCliRunMain, type RunnerPlatform } from 'src/run-main';
6 import {
7 makeShutdownController,
8 type ShutdownController,
9 type StopSignal,
10 } from 'src/services/shutdown-signal';
11
12 const exitWith = (code: number): ExitAction => ExitAction.ExitWith({ code });
13 const reraiseKill: ExitAction = ExitAction.Reraise({ signal: 'SIGKILL' });
14
15 // Each exit, then the action expected with no signal, SIGINT, SIGTERM and SIGHUP received.
16 const exits = [
17 {
18 kind: 'success',
19 exit: Exit.succeed(undefined),
20 expected: [exitWith(0), exitWith(0), exitWith(0), exitWith(0)],
21 },
22 {
23 kind: 'interrupted',
24 exit: Exit.failCause(Cause.interrupt()),
25 expected: [exitWith(130), exitWith(130), exitWith(143), exitWith(129)],
26 },
27 {
28 kind: 'child exited 7',
29 exit: Exit.fail(new ChildProcessExited({ code: 7 })),
30 expected: [exitWith(7), exitWith(7), exitWith(7), exitWith(7)],
31 },
32 {
33 kind: 'child killed',
34 exit: Exit.fail(new ChildProcessSignaled({ signal: 'SIGKILL' })),
35 expected: [reraiseKill, reraiseKill, reraiseKill, reraiseKill],
36 },
37 {
38 kind: 'reported failure',
39 exit: Exit.fail(new ReportedFailure({ message: 'printed' })),
40 expected: [exitWith(1), exitWith(1), exitWith(1), exitWith(1)],
41 },
42 {
43 kind: 'defect',
44 exit: Exit.die(new Error('boom')),
45 expected: [exitWith(1), exitWith(1), exitWith(1), exitWith(1)],
46 },
47 ] as const;
48
49 const received = [
50 { name: 'no signal', signal: Option.none<StopSignal>() },
51 { name: 'SIGINT', signal: Option.some<StopSignal>('SIGINT') },
52 { name: 'SIGTERM', signal: Option.some<StopSignal>('SIGTERM') },
53 { name: 'SIGHUP', signal: Option.some<StopSignal>('SIGHUP') },
54 ] as const;
55
56 const cases = exits.flatMap(({ kind, exit, expected }) =>
57 received.map(({ name, signal }, index) => ({
58 kind,
59 name,
60 exit: exit as Exit.Exit<unknown, unknown>,
61 signal: signal as Option.Option<StopSignal>,
62 action: expected[index],
63 }))
64 );
65
66 describe('exitActionFor', () => {
67 it.each(cases)(
68 '[Given] $kind after $name [Then] ends as expected',
69 ({ exit, signal, action }) => {
70 expect(exitActionFor(exit, signal)).toEqual(action);
71 }
72 );
73 });
74
75 /** A process stand-in: signals are delivered by hand, timers fire by hand. */
76 const fakePlatform = () => {
77 const listeners = new Map<StopSignal, Set<() => void>>();
78 const timers: Array<() => void> = [];
79 const ended: Array<ExitAction> = [];
80 let onEnd = () => {};
81 const platform: RunnerPlatform = {
82 on: (signal, listener) => {
83 listeners.set(signal, (listeners.get(signal) ?? new Set()).add(listener));
84 },
85 off: (signal, listener) => {
86 listeners.get(signal)?.delete(listener);
87 },
88 exit: code => {
89 ended.push(ExitAction.ExitWith({ code }));
90 onEnd();
91 },
92 raise: signal => {
93 ended.push(ExitAction.Reraise({ signal }));
94 onEnd();
95 },
96 schedule: (_millis, f) => {
97 timers.push(f);
98 return () => timers.splice(timers.indexOf(f), 1);
99 },
100 };
101 return {
102 platform,
103 ended,
104 timers,
105 send: (signal: StopSignal) => [...(listeners.get(signal) ?? [])].forEach(f => f()),
106 listenerCount: () => [...listeners.values()].reduce((sum, set) => sum + set.size, 0),
107 /** Resolves on the first exit or re-raise. */
108 end: new Promise<void>(resolve => {
109 onEnd = resolve;
110 }),
111 };
112 };
113
114 /** Lets the runtime settle a fiber the test cannot await. */
115 const settle = () => new Promise(resolve => setTimeout(resolve, 20));
116
117 const start = (controller: ShutdownController, program: Effect.Effect<unknown, unknown>) => {
118 const fake = fakePlatform();
119 makeCliRunMain(controller, fake.platform)(program, { disableErrorReporting: true });
120 return fake;
121 };
122
123 describe('makeCliRunMain', () => {
124 it.each([
125 { signal: 'SIGINT', code: 130 },
126 { signal: 'SIGTERM', code: 143 },
127 { signal: 'SIGHUP', code: 129 },
128 ] as const)(
129 '[Given] a command that does not cooperate [When] $signal arrives [Then] it is interrupted and exits $code',
130 async ({ signal, code }) => {
131 const fake = start(makeShutdownController(), Effect.never);
132
133 fake.send(signal);
134 await fake.end;
135
136 expect(fake.ended).toEqual([ExitAction.ExitWith({ code })]);
137 expect(fake.listenerCount()).toBe(0);
138 }
139 );
140
141 it('[Given] a command that cooperates [When] SIGTERM arrives [Then] it stops by itself and exits 0', async () => {
142 const controller = makeShutdownController();
143 const stopped = Deferred.makeUnsafe<StopSignal>();
144 const program = Effect.gen(function* () {
145 yield* controller.service.cooperate({ signals: ['SIGINT', 'SIGTERM'] });
146 const signal = yield* controller.service.requested;
147 yield* Deferred.succeed(stopped, signal);
148 }).pipe(Effect.scoped);
149 const fake = start(controller, program);
150 await settle();
151
152 fake.send('SIGTERM');
153 await fake.end;
154
155 expect(Deferred.isDoneUnsafe(stopped)).toBe(true);
156 expect(fake.ended).toEqual([ExitAction.ExitWith({ code: 0 })]);
157 });
158
159 it('[Given] a cooperating command [When] a signal it does not take arrives [Then] it is interrupted', async () => {
160 const controller = makeShutdownController();
161 const program = controller.service
162 .cooperate({ signals: ['SIGINT', 'SIGTERM'] })
163 .pipe(Effect.andThen(Effect.never), Effect.scoped);
164 const fake = start(controller, program);
165 await settle();
166
167 fake.send('SIGHUP');
168 await fake.end;
169
170 expect(fake.ended).toEqual([ExitAction.ExitWith({ code: 129 })]);
171 });
172
173 it.each([
174 { reraiseOnForce: false, ended: ExitAction.ExitWith({ code: 143 }) },
175 { reraiseOnForce: true, ended: ExitAction.Reraise({ signal: 'SIGTERM' }) },
176 ])(
177 '[Given] a stop in progress [When] a second signal arrives (reraise: $reraiseOnForce) [Then] it forces the exit',
178 async ({ reraiseOnForce, ended }) => {
179 const controller = makeShutdownController();
180 const release = Deferred.makeUnsafe<void>();
181 let forced = 0;
182 const program = Effect.gen(function* () {
183 yield* controller.service.cooperate({
184 signals: ['SIGINT', 'SIGTERM'],
185 onForce: () => {
186 forced += 1;
187 },
188 reraiseOnForce,
189 });
190 yield* controller.service.requested;
191 // A stop that never finishes on its own.
192 yield* Deferred.await(release);
193 }).pipe(Effect.scoped);
194 const fake = start(controller, program);
195 await settle();
196
197 fake.send('SIGINT');
198 await settle();
199 expect(fake.ended).toEqual([]);
200 fake.send('SIGTERM');
201 await fake.end;
202
203 expect(forced).toBe(1);
204 expect(fake.ended).toEqual([ended]);
205 Deferred.doneUnsafe(release, Effect.void);
206 }
207 );
208
209 it('[Given] a stop that outlives the deadline [Then] the deadline forces the exit with the first signal', async () => {
210 const controller = makeShutdownController();
211 const release = Deferred.makeUnsafe<void>();
212 const program = controller.service
213 .cooperate({ signals: ['SIGINT'] })
214 .pipe(
215 Effect.andThen(controller.service.requested),
216 Effect.andThen(Deferred.await(release)),
217 Effect.scoped
218 );
219 const fake = start(controller, program);
220 await settle();
221
222 fake.send('SIGINT');
223 expect(fake.timers).toHaveLength(1);
224 fake.timers[0]!();
225 await fake.end;
226
227 expect(fake.ended).toEqual([ExitAction.ExitWith({ code: 130 })]);
228 Deferred.doneUnsafe(release, Effect.void);
229 });
230
231 it('[Given] a stop that finishes in time [Then] the deadline is cancelled', async () => {
232 const controller = makeShutdownController();
233 const program = controller.service
234 .cooperate({ signals: ['SIGINT'] })
235 .pipe(Effect.andThen(controller.service.requested), Effect.scoped);
236 const fake = start(controller, program);
237 await settle();
238
239 fake.send('SIGINT');
240 await fake.end;
241
242 expect(fake.timers).toHaveLength(0);
243 });
244
245 it('[Given] a child a signal ended [Then] the runner re-raises that signal', async () => {
246 const fake = start(
247 makeShutdownController(),
248 Effect.fail(new ChildProcessSignaled({ signal: 'SIGINT' }))
249 );
250
251 await fake.end;
252
253 expect(fake.ended).toEqual([ExitAction.Reraise({ signal: 'SIGINT' })]);
254 });
255
256 it('[Given] a failure without a signal [Then] it exits with the failure code', async () => {
257 const fake = start(makeShutdownController(), Effect.fail(new ChildProcessExited({ code: 3 })));
258
259 await fake.end;
260
261 expect(fake.ended).toEqual([ExitAction.ExitWith({ code: 3 })]);
262 });
263
264 it('[Given] a success nobody signalled [Then] it leaves the exit to the event loop', async () => {
265 const fake = start(makeShutdownController(), Effect.void);
266
267 await settle();
268
269 expect(fake.ended).toEqual([]);
270 expect(fake.listenerCount()).toBe(0);
271 });
272 });