1
import { requireLogin } from 'src/effects/require-auth';
2
import { reportFailure } from 'src/effects/report-failure';
3
+import { eventCount, finishAcceptedEvents, makeSinkFailures } from '../sink-failures';
4
import { Command, Flag } from 'effect/cli';
5
import * as FileSystem from 'effect/FileSystem';
6
import * as Path from 'effect/Path';
6
-import { Deferred, Effect, Option } from 'effect';
7
+import { Deferred, Effect, FiberSet, Option } from 'effect';
8
import { APP_CONFIG } from 'src/config';
9
import { CommandSurface, resolveSurfaceProject } from 'src/commands/surface';
10
import { TerminalUI } from 'src/services/terminal-ui';
68
Flag.optional
69
);
70
71
+const failFast = Flag.Boolean('fail-fast').pipe(
72
+ Flag.withDescription(
73
+ 'Stop at the first event that fails to forward or to append to --out, and exit 1'
74
+ ),
75
+ Flag.withDefault(false)
76
+);
77
+
78
+/** Runs one event's callback on a fiber the listener interrupts when it stops. */
79
+type RunEvent = (effect: Effect.Effect<void>) => unknown;
80
+
81
const randomUUID = () => crypto.randomUUID();
82
83
const signWebhookPayload = async ({
159
maxEvents,
160
forward,
161
out,
162
+ failFast,
163
},
164
({
165
toolkits,
171
maxEvents,
172
forward,
173
out,
174
+ failFast,
175
}) =>
176
Effect.gen(function* () {
177
const surface = yield* CommandSurface;
181
const fs = yield* FileSystem.FileSystem;
182
const path = yield* Path.Path;
183
const realtime = yield* TriggersRealtime;
171
- const services = yield* Effect.context<never>();
184
const forwardUrl = Option.getOrUndefined(forward);
185
const generatedWebhookSecret = `composio-forward-secret-${randomUUID()}`;
186
const configuredWebhookSecret = yield* APP_CONFIG.WEBHOOK_SECRET;
204
};
205
206
const maxEventsLimit = Option.getOrUndefined(maxEvents);
195
- const stopWhenDone = yield* Deferred.make<void>();
207
+ const stopWhenDone = yield* Deferred.make<'max-events' | 'failed'>();
208
let matchingEvents = 0;
197
- // Per-event failures are recovered so one bad event never stops the listener; they are
198
- // counted here and summed up on plain stderr on every stop — including Ctrl+C and
199
- // SIGTERM, which runMain turns into a fiber interruption — since a piped caller sees
200
- // none of the `ui.log.warn` decoration.
201
- let outputWriteFailures = 0;
202
- let forwardFailures = 0;
209
+ // Its own signal, so a --fail-fast failure also ends finishAcceptedEvents' wait.
210
+ const failed = yield* Deferred.make<void>();
211
+ const stopOnFailure = Effect.andThen(
212
+ Deferred.succeed(failed, undefined),
213
+ Deferred.succeed(stopWhenDone, 'failed')
214
+ ).pipe(Effect.asVoid);
215
+ const forwardFailures = makeSinkFailures({
216
+ ui,
217
+ failFast,
218
+ stop: stopOnFailure,
219
+ summary: count =>
220
+ `${eventCount(count)} failed to forward to ${forwardUrl} while listening.`,
221
+ });
222
+ const outputWriteFailures = makeSinkFailures({
223
+ ui,
224
+ failFast,
225
+ stop: stopOnFailure,
226
+ summary: count =>
227
+ `${eventCount(count)} failed to append to ${outputFilePath} while listening.`,
228
+ });
229
let tableHeaderPrinted = false;
230
231
yield* ui.intro('composio dev triggers listen');
254
yield* ui.log.info(`Auto-stop after ${maxEventsLimit} matching events.`);
255
}
256
231
- const onEvent = (eventData: Record<string, unknown>) => {
232
- Effect.runForkWith(services)(
257
+ const onEvent = (runEvent: RunEvent) => (eventData: Record<string, unknown>) => {
258
+ runEvent(
259
Effect.gen(function* () {
260
const parsed = parseTriggerListenEvent(eventData);
261
if (!matchesTriggerListenFilters(filters, parsed)) {
292
const logLine = `${payloadForForwarding}\n`;
293
294
if (outputFilePath) {
269
- yield* fs.writeFileString(outputFilePath, logLine, { flag: 'a' }).pipe(
270
- Effect.catch(error =>
271
- Effect.gen(function* () {
272
- outputWriteFailures += 1;
273
- yield* ui.log.warn(String(error));
274
- })
275
- )
276
- );
295
+ yield* fs
296
+ .writeFileString(outputFilePath, logLine, { flag: 'a' })
297
+ .pipe(Effect.catch(error => outputWriteFailures.record(String(error))));
298
}
299
300
if (forwardUrl && webhookSecret) {
336
catch: error =>
337
new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
338
});
318
- }).pipe(
319
- Effect.catch(error =>
320
- Effect.gen(function* () {
321
- forwardFailures += 1;
322
- yield* ui.log.warn(String(error));
323
- })
324
- )
325
- );
339
+ }).pipe(Effect.catch(error => forwardFailures.record(String(error))));
340
}
341
342
if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
329
- yield* Deferred.succeed(stopWhenDone, undefined).pipe(Effect.ignore);
343
+ yield* Deferred.succeed(stopWhenDone, 'max-events').pipe(Effect.ignore);
344
}
345
})
346
);
347
};
348
349
// The default credentials serve the configured project; a named one needs its own.
336
- const listenEffect = (
337
- Option.isSome(surface.projectName)
350
+ const listenEffect = (runEvent: RunEvent) =>
351
+ (Option.isSome(surface.projectName)
352
? realtime.listenInProject(
353
{ orgId: project.orgId, projectId: project.projectId },
340
- onEvent
354
+ onEvent(runEvent)
355
)
342
- : realtime.listen(onEvent)
343
- ).pipe(
344
- Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
345
- );
346
-
347
- // The summary runs in an onExit finalizer, so it fires on every stop — including the
348
- // interruption of an unlimited wait, where the code after this block would not run.
349
- const reportSinkFailures = () =>
350
- Effect.gen(function* () {
351
- if (forwardFailures > 0) {
352
- yield* ui.error(
353
- `${forwardFailures} event${forwardFailures === 1 ? '' : 's'} failed to forward to ${forwardUrl} while listening.`
354
- );
355
- }
356
- if (outputWriteFailures > 0) {
357
- yield* ui.error(
358
- `${outputWriteFailures} event${outputWriteFailures === 1 ? '' : 's'} failed to append to ${outputFilePath} while listening.`
359
- );
360
- }
361
- });
356
+ : realtime.listen(onEvent(runEvent))
357
+ ).pipe(
358
+ Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
359
+ );
360
361
yield* Effect.gen(function* () {
364
- if (maxEventsLimit === undefined) {
365
- return yield* listenEffect;
362
+ // Scoped below: a stop other than --max-events interrupts the event callbacks still
363
+ // running before the summaries print.
364
+ const events = yield* FiberSet.make();
365
+ const runEvent = yield* FiberSet.runtime(events)();
366
+ // Without --max-events or --fail-fast nothing resolves stopWhenDone, so this waits on
367
+ // the listener until it is interrupted.
368
+ const stopReason = yield* Effect.raceFirst(
369
+ listenEffect(runEvent),
370
+ Deferred.await(stopWhenDone)
371
+ );
372
+ if (stopReason === 'max-events') {
373
+ yield* finishAcceptedEvents(events, failed);
374
+ yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
375
}
367
-
368
- yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
369
- yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
376
}).pipe(
371
- Effect.onExit(() => reportSinkFailures()),
377
+ Effect.scoped,
378
+ // An onExit finalizer, so the summaries print on every stop — including the
379
+ // interruption by Ctrl+C or SIGTERM, where the code after this block would not run.
380
+ Effect.onExit(() => Effect.andThen(forwardFailures.report, outputWriteFailures.report)),
381
Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
382
reportFailure(
383
ui,