@devries-cameron20 / composio Mirror · read-only / commits / 1024d1a48
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 12:15 UTC

feat(core): add optional onSubscriptionError callback for trigger subscriptions

- PusherService.subscribe and Triggers.subscribe accept an optional onSubscriptionError callback invoked with the raw pusher pusher:subscription_error payload, giving hosts a programmatic signal for post-resolution subscription failures (previously log-only). - Exceptions thrown from the callback are contained and logged, never rethrown, so a faulty handler cannot crash the host. - The parameter is optional; existing callers are unaffected. - Document the new parameter in the TypeScript triggers reference and the subscribing-to-events guide; bump the changeset to minor for the new API surface. Applies review finding #1 from the PR #4448 review.

jkomyno committed Sep 15, 2026 at 16:33 UTC 1024d1a48c2de1d348c9de9e1ad27bece27b2c9d
7 files changed +100 -7
.changeset/quiet-pumas-recover.md
+3 -3
@@ -1,6 +1,6 @@
1 ---
2 -'@composio/core': patch
3 -'@composio/slim': patch
2 +'@composio/core': minor
3 +'@composio/slim': minor
4 ---
5
6 -Keep TypeScript realtime subscription errors inside the SDK logging boundary so an asynchronous Pusher subscription failure cannot escape as an uncaught exception. The full subscription error payload is now logged, and the success message is logged only once Pusher confirms the subscription.
6 +Keep TypeScript realtime subscription errors inside the SDK logging boundary so an asynchronous Pusher subscription failure cannot escape as an uncaught exception. The full subscription error payload is now logged, the success message is logged only once Pusher confirms the subscription, and `PusherService.subscribe` / `Triggers.subscribe` accept an optional `onSubscriptionError` callback so applications can react to subscription failures programmatically.
docs/content/docs/setting-up-triggers/subscribing-to-events.mdx
+14
@@ -52,6 +52,20 @@ await composio.triggers.subscribe(
52
53 Filter the stream by `triggerId`, `triggerSlug`, `connectedAccountId`, `toolkits`, or `userId`, or pass no filters to receive every trigger event in the project.
54
55 +Subscription failures (for example a rejected auth request) do not reject the `subscribe()` promise — Pusher reports them asynchronously after it resolves. Pass an optional third callback to react to them programmatically:
56 +
57 +```typescript
58 +await composio.triggers.subscribe(
59 + data => {
60 + console.log('Event received:', data);
61 + },
62 + {},
63 + error => {
64 + console.error('Trigger subscription failed:', error);
65 + }
66 +);
67 +```
68 +
69 ### Forward to your local handler with the CLI (recommended)
70
71 The Composio CLI streams realtime events and forwards each one to your local URL, signed exactly like production. No public URL, no tunnel, and it runs your real handler (and [`parse()`](#handling-events)) end to end.
docs/content/reference/sdk-reference/typescript/triggers.mdx
+6 -1
@@ -311,7 +311,11 @@ await composio.triggers.setWebhookSubscription({
311 Subscribe to all the triggers
312
313 ```typescript
314 -async subscribe(fn: (_data: IncomingTriggerPayload) => void, filters: TriggerSubscribeParams): Promise<void>
314 +async subscribe(
315 + fn: (_data: IncomingTriggerPayload) => void,
316 + filters?: TriggerSubscribeParams,
317 + onSubscriptionError?: (data: Record<string, unknown>) => void
318 +): Promise<void>
319 ```
320
321 **Parameters**
@@ -320,6 +324,7 @@ async subscribe(fn: (_data: IncomingTriggerPayload) => void, filters: TriggerSub
324 |------|------|-------------|
325 | `fn` | `(_data: IncomingTriggerPayload) => void` | The function to call when a trigger is received |
326 | `filters` | `TriggerSubscribeParams` | The filters to apply to the triggers |
327 +| `onSubscriptionError` | `(data: Record<string, unknown>) => void` | Optional callback invoked with the raw Pusher payload when the subscription fails (for example on auth or permission rejection). The promise still resolves; this is the only programmatic signal of the failure |
328
329 **Returns**
330
ts/packages/core/src/models/Triggers.ts
+6 -2
@@ -612,6 +612,9 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
612 *
613 * @param fn - The function to call when a trigger is received
614 * @param filters - The filters to apply to the triggers
615 + * @param onSubscriptionError - Optional callback invoked with the raw Pusher payload when
616 + * the underlying subscription fails (for example on auth or permission rejection). The
617 + * subscribe promise still resolves; this is the only programmatic signal of the failure.
618 *
619 * @example
620 * ```ts
@@ -623,7 +626,8 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
626 */
627 async subscribe(
628 fn: (_data: IncomingTriggerPayload) => void,
626 - filters: TriggerSubscribeParams = {}
629 + filters: TriggerSubscribeParams = {},
630 + onSubscriptionError?: (data: Record<string, unknown>) => void
631 ) {
632 if (!fn) throw new Error('Function is required for trigger subscription');
633
@@ -651,7 +655,7 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
655 } else {
656 logger.debug('Trigger does not match filters', JSON.stringify(parsedFilters.data, null, 2));
657 }
654 - });
658 + }, onSubscriptionError);
659 }
660
661 /**
ts/packages/core/src/services/pusher/Pusher.ts
+17 -1
@@ -162,8 +162,14 @@ export class PusherService {
162 * @param channelName - The name of the Pusher channel to subscribe to
163 * @param event - The event to subscribe to
164 * @param fn - The function to call when the event is received
165 + * @param onSubscriptionError - Optional callback invoked with the raw payload when the
166 + * Pusher subscription fails (for example on auth or permission rejection). Errors thrown
167 + * from this callback are contained and logged, never rethrown.
168 */
166 - async subscribe(fn: (data: Record<string, unknown>) => void) {
169 + async subscribe(
170 + fn: (data: Record<string, unknown>) => void,
171 + onSubscriptionError?: (data: Record<string, unknown>) => void
172 + ) {
173 try {
174 logger.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
175 const pusherClient = await this.getPusherClient();
@@ -172,6 +178,16 @@ export class PusherService {
178 // add subscription error handling
179 channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
180 logger.error('Trigger subscription error:', data);
181 +
182 + // surface the failure to the caller without letting a faulty
183 + // handler crash the host (same containment as the trigger callback)
184 + try {
185 + onSubscriptionError?.(data);
186 + } catch (callbackError: unknown) {
187 + const errorMessage =
188 + callbackError instanceof Error ? callbackError.message : String(callbackError);
189 + logger.error('❌ Error in subscription error callback:', errorMessage);
190 + }
191 });
192
193 // log success only when Pusher itself confirms the subscription
ts/packages/core/test/models/triggers.test.ts
+9
@@ -765,6 +765,15 @@ describe('Triggers', () => {
765 expect(logger.debug).toHaveBeenCalledWith('🔄 Subscribing to triggers with filters: ', '{}');
766 });
767
768 + it('should pass the subscription error callback through to the pusher service', async () => {
769 + const onSubscriptionError = vi.fn();
770 +
771 + await triggers.subscribe(mockCallback, {}, onSubscriptionError);
772 +
773 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
774 + expect(subscribeCall[1]).toBe(onSubscriptionError);
775 + });
776 +
777 it('should subscribe to triggers with filters', async () => {
778 const filters: TriggerSubscribeParams = {
779 toolkits: ['github'],
ts/packages/core/test/services/pusher.test.ts
+45
@@ -113,4 +113,49 @@ describe('PusherService subscription errors', () => {
113
114 expect(mockLoggerInfo).toHaveBeenCalledWith(expect.stringContaining('Subscribed to triggers'));
115 });
116 +
117 + it('invokes the optional subscription error callback with the raw payload', async () => {
118 + const service = new PusherService({
119 + baseURL: 'https://backend.composio.dev',
120 + apiKey: 'api-key',
121 + } as never);
122 + const onSubscriptionError = vi.fn();
123 +
124 + await service.subscribe(vi.fn(), onSubscriptionError);
125 +
126 + await new Promise<void>(resolve => {
127 + setImmediate(resolve);
128 + });
129 +
130 + const payload = { type: 'AuthError', error: 'Auth error: 401', status: 401 };
131 + mockChannel.emit('pusher:subscription_error', payload);
132 +
133 + expect(onSubscriptionError).toHaveBeenCalledWith(payload);
134 + });
135 +
136 + it('contains exceptions thrown from the subscription error callback', async () => {
137 + const service = new PusherService({
138 + baseURL: 'https://backend.composio.dev',
139 + apiKey: 'api-key',
140 + } as never);
141 + const onSubscriptionError = vi.fn(() => {
142 + throw new Error('handler exploded');
143 + });
144 +
145 + await service.subscribe(vi.fn(), onSubscriptionError);
146 +
147 + await new Promise<void>(resolve => {
148 + setImmediate(resolve);
149 + });
150 +
151 + expect(() => {
152 + mockChannel.emit('pusher:subscription_error', { error: 401 });
153 + }).not.toThrow();
154 +
155 + expect(onSubscriptionError).toHaveBeenCalledTimes(1);
156 + expect(mockLoggerError).toHaveBeenCalledWith(
157 + '❌ Error in subscription error callback:',
158 + 'handler exploded'
159 + );
160 + });
161 });