@devries-cameron20 / composio-1 / commits / 04cd5c48d
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.

fix(core): close the trigger connection on `unsubscribe()` and contain handler rejections (#4903)

This PR: - supersedes https://github.com/ComposioHQ/composio/pull/4814 and https://github.com/ComposioHQ/composio/pull/4813, combining both into one coherent subscription lifecycle and callback error boundary - closes https://github.com/ComposioHQ/composio/issues/4812 - fixes the TypeScript half of https://github.com/ComposioHQ/composio/issues/4810 (the Python half stays open; see Limitations) - gives each subscription period (first `subscribe()` → next `unsubscribe()`) its own pusher-js client: concurrent `subscribe()` calls share one connection attempt, and `unsubscribe()` aborts setup still in flight, unbinds the SDK's handlers and disconnects - routes trigger handlers and `onSubscriptionError` through one `invokeUserCallback()` boundary that contains synchronous throws and rejected promises and logs a printable description (`describeThrown()`) - keeps the containment of async `pusher:subscription_error` failures from https://github.com/ComposioHQ/composio/pull/4448, and also closes a remaining gap there: a rejection whose value `String()` cannot convert used to throw inside the `.catch` and escape again - adds a patch changeset for `@composio/core` / `@composio/slim` Designated PR reviewer: [@jkomyno](mailto:alberto@composio.dev). ## Root causes These are two independent defects. **Connection never closed (https://github.com/ComposioHQ/composio/issues/4812).** `PusherService.unsubscribe()` unsubscribed the channel but nothing called `disconnect()`, so the pusher-js websocket kept Node's event loop alive. It also called `getPusherClient()`, so an `unsubscribe()` before any `subscribe()` fetched credentials and opened a connection. `getPusherClient()` checked `this.pusherClient` before two awaits (credentials, `import('pusher-js')`), so concurrent first `subscribe()` calls each created a client and the last assignment orphaned the others, which `unsubscribe()` could never reach. Reusing one client across periods (the alternative discussed in https://github.com/ComposioHQ/composio/issues/4812) is unsafe with pusher-js 8.6.0: - `disconnect()` keeps every channel in the client's table, with its bound handlers, and the next `connect()` resubscribes all of them (`subscribeAll()`). - `unsubscribe()` on a channel whose auth is still pending only sets `subscriptionCancelled`; the channel stays, and a later `subscribe()` of the same name reinstates it with the old handlers. The harness below shows this on `next`: a handler removed by `unsubscribe()` still received the next event. - A channel-auth reply requested for the old socket can arrive after a reconnect and be sent on the new socket. A fresh client per period isolates all three: late replies and cancelled channels belong to a disconnected client whose `send_event` is a no-op, and its handlers are unbound. **Async handler rejections (https://github.com/ComposioHQ/composio/issues/4810).** `Triggers.subscribe()` and `PusherService`'s `safeCallback` called the handler inside a synchronous `try/catch`. An `async` handler returns a promise, so its rejection skipped the `catch`, nothing handled it, and Node's default `unhandledRejection` behavior ended the process. Separately, the logger `JSON.stringify`s object arguments, so a thrown `Error` was logged as `{}`. ## Ownership and cancellation model - `PusherService` holds at most one `attempt` (an `AbortController` plus the shared `ready` promise) and, once created, the `connection` (client, channel, channel name). Both are cleared together by `unsubscribe()`. - `openConnection()` checks `signal.aborted` after its last await; the client creation and channel subscription after it are synchronous, so `unsubscribe()` cannot interleave with them. - A `subscribe()` whose attempt was aborted resolves without subscribing, including when the aborted setup later fails (for example, the credentials request rejects). A `subscribe()` that resumes after the client was created but after `unsubscribe()` ran installs no handlers. - A failed (not aborted) attempt is forgotten, so the next `subscribe()` retries. - `unsubscribe()` ends every subscription of the `Triggers` instance, as documented ("Unsubscribe from all the triggers"), so it always closes the connection; there is no other channel on that client to keep it open. ## Verification Focused regression tests (`ts/packages/core/test/services/pusher.test.ts`, `ts/packages/core/test/models/triggers.test.ts`), using a fake pusher-js that keeps its binding semantics. 15 of them fail on `next` source and pass with this change: - disconnects and unbinds on unsubscribe; unsubscribe first creates no client and fetches no credentials - concurrent subscribes share one client and credentials request - unsubscribe while credentials are pending, and when that pending request then fails - unsubscribe after the client exists but before the waiting `subscribe()` resumes - unsubscribe interleaved with pending setup keeps only the later subscription - resubscribe after cleanup uses a new client; late events and auth errors on the old client reach nothing - five cycles leave every client disconnected and unbound; retry after a credentials failure - sync throw and async rejection from trigger handlers, non-`Error` and unprintable rejection values, and an unprintable rejection from `onSubscriptionError` Built SDK against unmodified `pusher-js` 8.6.0 and a local Pusher-protocol (v7) server over TLS, which validates channel signatures against the socket they arrive on. A preload only redirects the TLS connection for the fake cluster host to localhost. Node 24.17.0, one process per scenario; "exits" means the process ended on its own after the scenario finished: | Scenario | `next` | This PR | | --- | --- | --- | | subscribe → event → unsubscribe | still running, socket open (killed after 5 s) | exits in ~6 ms, 0 open sockets | | unsubscribe before subscribe | 1 credentials request, 1 client, still running | 0 requests, 0 clients, exits | | unsubscribe → resubscribe → event | both receive, still running | both receive on separate connections, exits | | two concurrent subscribes | 2 credentials requests, 2 sockets, both left open | 1 request, 1 socket, each handler once, exits | | unsubscribe during initialization | event delivered after unsubscribe, 2 sockets open | no socket opened, nothing delivered, exits | | async handler rejects | process exits with code 1 (unhandled rejection) | logs `❌ Error in trigger callback: <message>`, keeps running, exits 0 | | auth reply delayed past unsubscribe → resubscribe | unsubscribed handler still receives the event | unsubscribed handler receives nothing, 0 stale or invalid subscribes, exits | | 100 subscribe/unsubscribe cycles | 1 client, never exits | 100 clients created, 0 connected, 0 open sockets, exits | Commands: - `pnpm --filter @composio/core test`: 73 files, 1842 passed, 2 expected failures - `pnpm --filter @composio/core typecheck` - `oxlint` on the changed files: no new warnings (one existing warning in `Triggers.ts`) - `pnpm validate:changesets` ## Limitations - pusher-js 8.6.0 never releases a client: the constructor pushes it onto the static `Pusher.instances` array, and its `ConnectionManager` binds `online`/`offline` listeners on the module-level `Network` object that `disconnect()` does not remove, so each disconnected client stays reachable. Neither has a documented release API, and the listeners can't be told apart from other clients' listeners. With pusher-js alone, each connect/subscribe/disconnect cycle retained about 14 KB. Through the SDK, the per-cycle growth was about 14.6 KB over 300 cycles, which is mostly that client. The SDK unbinds its own handlers, so retained clients don't keep user callbacks alive. A script that subscribes once is unaffected; an app that cycles subscribe/unsubscribe many times keeps one disconnected client per cycle. - Each subscription period fetches realtime credentials again. - Python is unchanged. `TriggerSubscription.stop()` already disconnects, and https://github.com/ComposioHQ/composio/pull/4829 covered the connection-thread lifecycle. The Python half of https://github.com/ComposioHQ/composio/issues/4810 (an `async def` handler is never awaited) is a separate defect that needs a decision between rejecting async handlers and running them, so this PR doesn't close that issue. - `triggers.subscribe()` keeps its `(data) => void` handler type; it already accepts async functions, and widening the return type would reject handlers that return other values. ## Credits Thanks to @Hugo-DDT for https://github.com/ComposioHQ/composio/pull/4814 and to @TanishGudise for https://github.com/ComposioHQ/composio/pull/4813 and the investigation in https://github.com/ComposioHQ/composio/issues/4812 and https://github.com/ComposioHQ/composio/issues/4810. Both are co-authors of the commit. - From https://github.com/ComposioHQ/composio/pull/4814: disconnecting on unsubscribe, the no-client-on-bare-unsubscribe rule, shared initialization for concurrent subscribers, and treating setup errors after cancellation as cancellation. This PR replaces the generation counter and `allChannels()` check with an aborted attempt per period and a fresh client per period, which also covers a `subscribe()` that resumes after `unsubscribe()` and the cancelled-channel and late-auth cases. - From https://github.com/ComposioHQ/composio/pull/4813: the `Promise.resolve(...).catch(...)` containment and the failure-description fallbacks, now shared by both callback paths as `describeThrown()`. Its regression tests are included unchanged. - The issue analysis, especially the `Pusher.instances` and `Network` retention finding and the late-auth concern, shaped the design and the harness above. Thanks also to @VANDRANKI for the community reviews. Co-authored-by: DDT <141296842+Hugo-DDT@users.noreply.github.com> Co-authored-by: Tanish Gudise <174986239+TanishGudise@users.noreply.github.com>

Alberto Schiabel committed Oct 16, 2026 at 00:06 UTC 04cd5c48d005cb9a3723d62b4c0924a309dab1a6
7 files changed +633 -172
.changeset/trigger-subscription-lifecycle.md new
+11
@@ -0,0 +1,11 @@
1 +---
2 +'@composio/core': patch
3 +'@composio/slim': patch
4 +---
5 +
6 +Fix the trigger subscription lifecycle and contain errors from trigger handlers.
7 +
8 +- `triggers.unsubscribe()` now closes the realtime connection, so a Node process can exit once it has unsubscribed. A later `triggers.subscribe()` opens a new connection.
9 +- `triggers.unsubscribe()` before any `subscribe()` no longer fetches realtime credentials or creates a client.
10 +- Concurrent `subscribe()` calls share one connection, and `unsubscribe()` cancels a subscription that is still connecting, so it never opens a connection or delivers events afterwards.
11 +- A rejected promise from an `async` trigger handler is logged like a synchronous throw instead of escaping as an unhandled rejection that ends the process. Handler failures log the error's message rather than `{}`.
ts/packages/core/src/models/Triggers.ts
+8 -6
@@ -60,6 +60,7 @@ import { hmacSha256Base64, timingSafeEqual } from '../utils/crypto';
60 import { CONFIG_DEFAULTS } from '../utils/config-defaults';
61 import { ComposioRequestOptions } from '../types/requestOptions.types';
62 import { withCancellation } from '../utils/cancellation';
63 +import { invokeUserCallback } from '../utils/userCallback';
64
65 /**
66 * Safely converts a value to a string, returning the default if the value is null, undefined, or empty.
@@ -525,7 +526,8 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
526 /**
527 * Subscribe to all the triggers
528 *
528 - * @param fn - The function to call when a trigger is received
529 + * @param fn - The function to call when a trigger is received. It may be `async`. Errors
530 + * thrown from — or promises rejected by — the function are contained and logged.
531 * @param filters - The filters to apply to the triggers
532 * @param onSubscriptionError - Optional callback invoked with the raw Pusher payload when
533 * the underlying subscription fails (for example on auth or permission rejection). The
@@ -563,11 +565,7 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
565 const parsedData = this.parsePusherPayload(_data);
566
567 if (this.shouldSendTriggerAfterFilters(parsedFilters.data, parsedData)) {
566 - try {
567 - fn(parsedData);
568 - } catch (error) {
569 - logger.error('❌ Error in trigger callback:', error);
570 - }
568 + invokeUserCallback('❌ Error in trigger callback:', () => fn(parsedData));
569 } else {
570 logger.debug('Trigger does not match filters', JSON.stringify(parsedFilters.data, null, 2));
571 }
@@ -700,6 +698,10 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
698 /**
699 * Unsubscribe from all the triggers
700 *
701 + * Ends every subscription made with {@link subscribe} on this instance, including one that is
702 + * still connecting, and closes the realtime connection so that a script can exit. A later
703 + * `subscribe()` opens a new connection.
704 + *
705 * @returns {Promise<void>}
706 *
707 * @example
ts/packages/core/src/services/pusher/Pusher.ts
+159 -88
@@ -1,5 +1,5 @@
1 import ComposioClient from '@composio/client';
2 -import { PusherClient, TChunkedTriggerData } from '../../types/pusher.types';
2 +import { PusherChannel, PusherClient, TChunkedTriggerData } from '../../types/pusher.types';
3 import { InternalService } from '../internal/InternalService';
4 import { SDKRealtimeCredentialsResponse } from '../internal/InternalService.types';
5 import {
@@ -8,6 +8,7 @@ import {
8 ComposioFailedToSubscribeToPusherChannelError,
9 } from '../../errors/TriggerErrors';
10 import logger from '../../utils/logger';
11 +import { invokeUserCallback } from '../../utils/userCallback';
12 import { telemetry } from '../../telemetry/Telemetry';
13 import { resolveCredentialHeaders } from '../../utils/sdk';
14 import type { ComposioRequestHeaders } from '../../types/composio.types';
@@ -17,17 +18,41 @@ export type PusherServiceOptions = {
18 defaultHeaders?: ComposioRequestHeaders;
19 };
20
21 +/** A pusher-js client and the triggers channel it subscribed to. */
22 +type TriggerConnection = {
23 + client: PusherClient;
24 + channel: PusherChannel;
25 + channelName: string;
26 +};
27 +
28 +/**
29 + * Setup of the connection for one subscription period, which runs from the first `subscribe()`
30 + * to the next `unsubscribe()`. Concurrent `subscribe()` calls share `ready`; `unsubscribe()`
31 + * aborts `controller` so that setup still in flight neither connects nor installs handlers.
32 + */
33 +type ConnectionAttempt = {
34 + controller: AbortController;
35 + ready: Promise<TriggerConnection>;
36 +};
37 +
38 +/**
39 + * Owns the realtime connection that delivers trigger events.
40 + *
41 + * Each subscription period gets its own pusher-js client, which `unsubscribe()` disconnects.
42 + * Reusing one client across periods is unsafe: pusher-js keeps a channel, its bound handlers and
43 + * its cancellation flag through `disconnect()` and resubscribes every kept channel on the next
44 + * `connect()`, and a channel-auth reply requested on the old socket can arrive after a reconnect
45 + * and be sent on the new one.
46 + */
47 export class PusherService {
21 - // these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint
22 - private clientId!: string;
23 - private pusherKey!: string;
24 - private pusherCluster!: string;
25 - private pusherChannel!: string;
48 // these details are set via the client SDK
49 private pusherBaseURL!: string;
50 private authHeaders!: Record<string, string>;
29 - private pusherClient!: PusherClient;
51 private composioClient!: ComposioClient;
52 + private attempt?: ConnectionAttempt;
53 + // Set as soon as the current attempt creates its client, so that `unsubscribe()` can close it
54 + // before the `subscribe()` calls waiting on `attempt.ready` resume.
55 + private connection?: TriggerConnection;
56
57 constructor(client: ComposioClient, options: PusherServiceOptions = {}) {
58 this.composioClient = client;
@@ -43,54 +68,86 @@ export class PusherService {
68 }
69
70 /**
46 - * Creates a Pusher client
47 - *
48 - * This method is called when the Pusher client is first used.
49 - * It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.
71 + * Returns the connection attempt of the current subscription period, starting one if needed.
72 + * A failed attempt is forgotten, so the next `subscribe()` retries.
73 */
51 - private async getPusherClient() {
52 - if (!this.pusherClient) {
53 - const internalService = new InternalService(this.composioClient);
54 - let sdkRealtimeCredentials: SDKRealtimeCredentialsResponse;
55 - try {
56 - sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
57 - } catch (error) {
58 - throw new ComposioFailedToGetSDKRealtimeCredentialsError(
59 - 'Failed to get SDK realtime credentials',
60 - {
61 - cause: error,
62 - }
63 - );
64 - }
74 + private connect(): ConnectionAttempt {
75 + if (this.attempt) return this.attempt;
76
66 - this.clientId = sdkRealtimeCredentials.projectId;
67 - this.pusherKey = sdkRealtimeCredentials.pusherKey;
68 - this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
69 - this.pusherChannel = `private-${this.clientId}_triggers`;
77 + const controller = new AbortController();
78 + const ready = this.openConnection(controller.signal);
79 + const attempt = { controller, ready };
80 + this.attempt = attempt;
81 + ready.catch(() => {
82 + if (this.attempt === attempt) this.attempt = undefined;
83 + });
84 + return attempt;
85 + }
86
71 - logger.debug(
72 - `[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`
87 + /**
88 + * Fetches the SDK realtime credentials from the Apollo API, creates a Pusher client and
89 + * subscribes it to the triggers channel.
90 + */
91 + private async openConnection(signal: AbortSignal): Promise<TriggerConnection> {
92 + const internalService = new InternalService(this.composioClient);
93 + let sdkRealtimeCredentials: SDKRealtimeCredentialsResponse;
94 + try {
95 + sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
96 + } catch (error) {
97 + throw new ComposioFailedToGetSDKRealtimeCredentialsError(
98 + 'Failed to get SDK realtime credentials',
99 + {
100 + cause: error,
101 + }
102 );
103 + }
104
75 - // create the Pusher client
76 - try {
77 - const { default: Pusher } = await import('pusher-js');
78 - this.pusherClient = new Pusher(this.pusherKey, {
79 - cluster: this.pusherCluster,
80 - channelAuthorization: {
81 - endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
82 - headers: { ...this.authHeaders },
83 - transport: 'ajax',
84 - },
85 - });
86 - } catch (error) {
87 - throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {
88 - cause: error,
89 - });
90 - }
105 + const { projectId, pusherKey, pusherCluster } = sdkRealtimeCredentials;
106 + const channelName = `private-${projectId}_triggers`;
107 +
108 + let Pusher: (typeof import('pusher-js'))['default'];
109 + try {
110 + ({ default: Pusher } = await import('pusher-js'));
111 + } catch (error) {
112 + throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {
113 + cause: error,
114 + });
115 + }
116 +
117 + // unsubscribe() ran while the credentials or pusher-js were loading. Everything below is
118 + // synchronous, so this is the last point at which it can cancel the attempt.
119 + if (signal.aborted) {
120 + throw new Error('Connection attempt cancelled by unsubscribe()');
121 }
122
93 - return this.pusherClient;
123 + logger.debug(
124 + `[PusherService] Creating Pusher client for client ID: ${projectId} in cluster ${pusherCluster}`
125 + );
126 +
127 + let client: PusherClient;
128 + try {
129 + client = new Pusher(pusherKey, {
130 + cluster: pusherCluster,
131 + channelAuthorization: {
132 + endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
133 + headers: { ...this.authHeaders },
134 + transport: 'ajax',
135 + },
136 + });
137 + } catch (error) {
138 + throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {
139 + cause: error,
140 + });
141 + }
142 +
143 + logger.debug(`[PusherService] Subscribing to channel: ${channelName}`);
144 + try {
145 + this.connection = { client, channel: client.subscribe(channelName), channelName };
146 + } catch (error) {
147 + client.disconnect();
148 + throw error;
149 + }
150 + return this.connection;
151 }
152
153 /**
@@ -102,7 +159,7 @@ export class PusherService {
159 * @param callback - The function to call when the event is received
160 */
161 private bindWithChunking(
105 - channel: PusherClient,
162 + channel: PusherChannel,
163 event: string,
164 callback: (data: Record<string, unknown>) => void
165 ): void {
@@ -167,11 +224,10 @@ export class PusherService {
224 /**
225 * Subscribes to pusher to receive events from the server
226 *
170 - * This method is used to subscribe to a Pusher channel.
171 - * It will create a Pusher client if it doesn't exist.
227 + * The first call of a subscription period creates the Pusher client; concurrent calls share
228 + * it. A call still waiting for the client when `unsubscribe()` runs resolves without
229 + * subscribing.
230 *
173 - * @param channelName - The name of the Pusher channel to subscribe to
174 - * @param event - The event to subscribe to
231 * @param fn - The function to call when the event is received
232 * @param onSubscriptionError - Optional callback invoked with the raw payload when the
233 * Pusher subscription fails (for example on auth or permission rejection). Errors thrown
@@ -181,30 +237,38 @@ export class PusherService {
237 fn: (data: Record<string, unknown>) => void,
238 onSubscriptionError?: (data: Record<string, unknown>) => void
239 ) {
240 + const attempt = this.connect();
241 + let connection: TriggerConnection;
242 try {
185 - logger.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
186 - const pusherClient = await this.getPusherClient();
187 - const channel = await pusherClient.subscribe(this.pusherChannel);
243 + connection = await attempt.ready;
244 + } catch (error) {
245 + if (attempt.controller.signal.aborted) {
246 + logger.debug('[PusherService] Subscribe cancelled by unsubscribe() before it connected');
247 + return;
248 + }
249 + throw new ComposioFailedToSubscribeToPusherChannelError(
250 + 'Failed to subscribe to Pusher channel',
251 + {
252 + cause: error,
253 + }
254 + );
255 + }
256 + // unsubscribe() ran after the client was created but before this call resumed.
257 + if (attempt.controller.signal.aborted) {
258 + logger.debug('[PusherService] Subscribe cancelled by unsubscribe() before it connected');
259 + return;
260 + }
261
189 - // add subscription error handling
190 - const logCallbackFailure = (callbackError: unknown) => {
191 - const errorMessage =
192 - callbackError instanceof Error ? callbackError.message : String(callbackError);
193 - logger.error('❌ Error in subscription error callback:', errorMessage);
194 - };
262 + try {
263 + const { channel } = connection;
264 channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
265 logger.error('Trigger subscription error:', data);
266
267 // surface the failure to the caller without letting a faulty
268 // handler crash the host (same containment as the trigger callback).
200 - // A handler may be async: contain rejected promises too, or the
201 - // rejection escapes as an unhandled rejection after subscribe()
202 - // already resolved.
203 - try {
204 - Promise.resolve(onSubscriptionError?.(data)).catch(logCallbackFailure);
205 - } catch (callbackError: unknown) {
206 - logCallbackFailure(callbackError);
207 - }
269 + invokeUserCallback('❌ Error in subscription error callback:', () =>
270 + onSubscriptionError?.(data)
271 + );
272 });
273
274 // log success only when Pusher itself confirms the subscription
@@ -212,18 +276,12 @@ export class PusherService {
276 logger.info(`✅ Subscribed to triggers. You should start receiving events now.`);
277 });
278
215 - // wrap the callback to handle errors
279 + // don't let a failing callback break the subscription
280 const safeCallback = (data: Record<string, unknown>) => {
217 - try {
218 - fn(data);
219 - } catch (error: unknown) {
220 - const errorMessage = error instanceof Error ? error.message : String(error);
221 - logger.error('❌ Error in trigger callback:', errorMessage);
222 - // don't throw here to prevent breaking the subscription
223 - }
281 + invokeUserCallback('❌ Error in trigger callback:', () => fn(data));
282 };
283
226 - this.bindWithChunking(channel as PusherClient, 'trigger_to_client', safeCallback);
284 + this.bindWithChunking(channel, 'trigger_to_client', safeCallback);
285 } catch (error) {
286 throw new ComposioFailedToSubscribeToPusherChannelError(
287 'Failed to subscribe to Pusher channel',
@@ -235,19 +293,29 @@ export class PusherService {
293 }
294
295 /**
238 - * Unsubscribes from a Pusher channel
239 - *
240 - * This method is used to unsubscribe from a Pusher channel.
241 - * It will create a Pusher client if it doesn't exist.
296 + * Unsubscribes from the triggers channel and closes the connection
297 *
243 - * @param channelName - The name of the Pusher channel to unsubscribe from
298 + * This ends the subscription period: setup still in flight is cancelled, the handlers bound by
299 + * every `subscribe()` call are removed, and the Pusher client is disconnected. Without a prior
300 + * `subscribe()` this does nothing; it never creates a client or fetches credentials.
301 */
302 async unsubscribe() {
303 + const { attempt, connection } = this;
304 + this.attempt = undefined;
305 + this.connection = undefined;
306 + attempt?.controller.abort();
307 +
308 + if (!connection) {
309 + logger.debug('[PusherService] No open connection to unsubscribe from');
310 + return;
311 + }
312 +
313 + logger.debug(`[PusherService] Unsubscribing from channel: ${connection.channelName}`);
314 try {
247 - logger.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
248 - const pusherClient = await this.getPusherClient();
249 - await pusherClient.unsubscribe(this.pusherChannel);
250 - logger.info(`✅ Unsubscribed from triggers.`);
315 + // pusher-js keeps a reference to every client it creates, so release the handlers this
316 + // service bound and the user callbacks they hold.
317 + connection.channel.unbind_all();
318 + connection.client.unsubscribe(connection.channelName);
319 } catch (error) {
320 throw new ComposioFailedToSubscribeToPusherChannelError(
321 'Failed to unsubscribe from Pusher channel',
@@ -255,6 +323,9 @@ export class PusherService {
323 cause: error,
324 }
325 );
326 + } finally {
327 + connection.client.disconnect();
328 }
329 + logger.info(`✅ Unsubscribed from triggers.`);
330 }
331 }
ts/packages/core/src/types/pusher.types.ts
+2
@@ -2,12 +2,14 @@ export interface PusherClient {
2 subscribe: (channelName: string) => PusherChannel;
3 unsubscribe: (channelName: string) => void;
4 bind: (event: string, callback: (data: Record<string, unknown>) => void) => void;
5 + disconnect: () => void;
6 }
7
8 export interface PusherChannel {
9 subscribe: (channelName: string) => unknown;
10 unsubscribe: (channelName: string) => void;
11 bind: (event: string, callback: (data: Record<string, unknown>) => void) => void;
12 + unbind_all: () => void;
13 }
14
15 export type TChunkedTriggerData = {
ts/packages/core/src/utils/userCallback.ts new
+41
@@ -0,0 +1,41 @@
1 +import logger from './logger';
2 +
3 +/**
4 + * Describes a thrown or rejected value for a log line without ever throwing.
5 + *
6 + * The logger serializes object arguments with `JSON.stringify`, which turns an `Error` into `{}`
7 + * and throws on a circular value, so callers log this string instead of the raw value.
8 + * `JSON.stringify` and `String()` can both throw (a circular value, an object without a
9 + * prototype), so each is tried in turn.
10 + */
11 +export function describeThrown(value: unknown): string {
12 + try {
13 + if (value instanceof Error) return value.message;
14 + if (typeof value === 'object' && value !== null) return JSON.stringify(value) ?? String(value);
15 + return String(value);
16 + } catch {
17 + try {
18 + return String(value);
19 + } catch {
20 + return '[unprintable value]';
21 + }
22 + }
23 +}
24 +
25 +/**
26 + * Calls a user-supplied event callback so that neither a synchronous throw nor a rejected promise
27 + * escapes into the event emitter that invoked it. Failures are logged after `label`.
28 + *
29 + * pusher-js does not catch listener exceptions, and nothing awaits the promise an `async`
30 + * listener returns, so an escaped failure would end a Node process.
31 + */
32 +export function invokeUserCallback(label: string, callback: () => unknown): void {
33 + const logFailure = (error: unknown) => {
34 + logger.error(label, describeThrown(error));
35 + };
36 + try {
37 + Promise.resolve(callback()).catch(logFailure);
38 + } catch (error) {
39 + logFailure(error);
40 + }
41 +}
ts/packages/core/test/models/triggers.test.ts
+108 -1
@@ -1103,9 +1103,116 @@ describe('Triggers', () => {
1103 expect(errorCallback).toHaveBeenCalledTimes(1);
1104 expect(logger.error).toHaveBeenCalledWith(
1105 '❌ Error in trigger callback:',
1106 - Error('Error in user callback')
1106 + 'Error in user callback'
1107 );
1108 });
1109 +
1110 + it('should contain rejections from async user callbacks', async () => {
1111 + const unhandledRejection = vi.fn();
1112 + process.on('unhandledRejection', unhandledRejection);
1113 + try {
1114 + // A plain async function: a vi.fn() spy would attach its own handlers
1115 + // to the returned promise and hide an unhandled rejection.
1116 + let calls = 0;
1117 + const asyncErrorCallback = async () => {
1118 + calls++;
1119 + throw new Error('Async error in user callback');
1120 + };
1121 +
1122 + await triggers.subscribe(asyncErrorCallback);
1123 +
1124 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1125 + const filterCallback = subscribeCall[0];
1126 +
1127 + expect(() => filterCallback(mockTriggerData)).not.toThrow();
1128 +
1129 + // let the rejected promise settle and the containment log run
1130 + await new Promise<void>(resolve => {
1131 + setImmediate(resolve);
1132 + });
1133 +
1134 + expect(calls).toBe(1);
1135 + expect(logger.error).toHaveBeenCalledWith(
1136 + '❌ Error in trigger callback:',
1137 + 'Async error in user callback'
1138 + );
1139 + expect(unhandledRejection).not.toHaveBeenCalled();
1140 + } finally {
1141 + process.off('unhandledRejection', unhandledRejection);
1142 + }
1143 + });
1144 +
1145 + it('should log the details of a thrown non-Error value', async () => {
1146 + vi.mocked(logger.error).mockClear();
1147 + const failure = { message: 'Request failed', code: 429 };
1148 +
1149 + await triggers.subscribe(() => {
1150 + throw failure;
1151 + });
1152 + await triggers.subscribe(async () => {
1153 + throw failure;
1154 + });
1155 +
1156 + for (const [filterCallback] of vi.mocked(mockPusherService.subscribe).mock.calls) {
1157 + filterCallback(mockTriggerData);
1158 + }
1159 + await new Promise<void>(resolve => {
1160 + setImmediate(resolve);
1161 + });
1162 +
1163 + // Once for the synchronous throw, once for the rejection.
1164 + expect(
1165 + vi
1166 + .mocked(logger.error)
1167 + .mock.calls.filter(([prefix]) => prefix === '❌ Error in trigger callback:')
1168 + ).toEqual([
1169 + ['❌ Error in trigger callback:', '{"message":"Request failed","code":429}'],
1170 + ['❌ Error in trigger callback:', '{"message":"Request failed","code":429}'],
1171 + ]);
1172 + });
1173 +
1174 + it('should log rejection values that JSON.stringify or String() cannot handle without letting them escape', async () => {
1175 + // The failure log runs as a rejection handler, so it must not throw for
1176 + // any value, or the rejection escapes again. The logger is mocked here,
1177 + // so these pin the string that is logged: passing a circular value to
1178 + // the real logger would make its own JSON.stringify throw.
1179 + vi.mocked(logger.error).mockClear();
1180 + const unhandledRejection = vi.fn();
1181 + process.on('unhandledRejection', unhandledRejection);
1182 + try {
1183 + const circular: Record<string, unknown> = { code: 429 };
1184 + circular.self = circular;
1185 + // String() throws on an object without a prototype.
1186 + const nullPrototype = Object.assign(Object.create(null), { code: 429 });
1187 + const nullPrototypeCircular = Object.create(null);
1188 + nullPrototypeCircular.self = nullPrototypeCircular;
1189 +
1190 + for (const value of [circular, nullPrototype, nullPrototypeCircular]) {
1191 + await triggers.subscribe(async () => {
1192 + throw value;
1193 + });
1194 + }
1195 + for (const [filterCallback] of vi.mocked(mockPusherService.subscribe).mock.calls) {
1196 + filterCallback(mockTriggerData);
1197 + }
1198 + await new Promise<void>(resolve => {
1199 + setImmediate(resolve);
1200 + });
1201 +
1202 + expect(
1203 + vi
1204 + .mocked(logger.error)
1205 + .mock.calls.filter(([prefix]) => prefix === '❌ Error in trigger callback:')
1206 + ).toEqual([
1207 + ['❌ Error in trigger callback:', '[object Object]'],
1208 + ['❌ Error in trigger callback:', '{"code":429}'],
1209 + ['❌ Error in trigger callback:', '[unprintable value]'],
1210 + ]);
1211 + expect(unhandledRejection).not.toHaveBeenCalled();
1212 + } finally {
1213 + process.off('unhandledRejection', unhandledRejection);
1214 + }
1215 + });
1216 });
1217
1218 describe('parsePusherPayload (V1/V2/V3 format support)', () => {
ts/packages/core/test/services/pusher.test.ts
+304 -77
@@ -1,52 +1,66 @@
1 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2 import { PusherService } from '../../src/services/pusher/Pusher';
3 +import { ComposioFailedToSubscribeToPusherChannelError } from '../../src/errors/TriggerErrors';
4
5 type EventHandler = (data: Record<string, unknown>) => void;
6
7 const {
7 - bindings,
8 - mockChannel,
9 - mockPusherClient,
8 + clients,
9 + createClient,
10 + hooks,
11 mockGetCredentials,
12 mockLoggerError,
13 mockLoggerInfo,
14 pusherConstructorOptions,
15 } = vi.hoisted(() => {
15 - const eventBindings = new Map<string, EventHandler>();
16 - const constructorOptions: Array<Record<string, unknown>> = [];
17 - const channel = {
18 - bind: vi.fn((event: string, callback: EventHandler) => {
19 - eventBindings.set(event, callback);
20 - }),
21 - emit: (event: string, data: Record<string, unknown>) => {
22 - eventBindings.get(event)?.(data);
23 - },
16 + // Keeps pusher-js's binding semantics: several handlers per event, all removed by unbind_all().
17 + class FakeChannel {
18 + private handlers = new Map<string, EventHandler[]>();
19 + bind = vi.fn((event: string, callback: EventHandler) => {
20 + this.handlers.set(event, [...(this.handlers.get(event) ?? []), callback]);
21 + });
22 + unbind_all = vi.fn(() => {
23 + this.handlers.clear();
24 + });
25 + emit(event: string, data: Record<string, unknown>) {
26 + for (const callback of this.handlers.get(event) ?? []) callback(data);
27 + }
28 + }
29 +
30 + class FakeClient {
31 + channel = new FakeChannel();
32 + subscribe = vi.fn(() => this.channel);
33 + unsubscribe = vi.fn();
34 + disconnect = vi.fn();
35 + }
36 +
37 + const createdClients: FakeClient[] = [];
38 + const testHooks = {
39 + // Runs synchronously inside the Pusher constructor.
40 + onClientCreated: () => {},
41 };
42
43 return {
27 - bindings: eventBindings,
28 - mockChannel: channel,
29 - mockPusherClient: {
30 - subscribe: vi.fn().mockReturnValue(channel),
31 - unsubscribe: vi.fn().mockReturnValue(undefined),
44 + clients: createdClients,
45 + createClient: () => {
46 + const client = new FakeClient();
47 + createdClients.push(client);
48 + testHooks.onClientCreated();
49 + return client;
50 },
33 - mockGetCredentials: vi.fn().mockResolvedValue({
34 - projectId: 'project-id',
35 - pusherKey: 'pusher-key',
36 - pusherCluster: 'mt1',
37 - }),
51 + hooks: testHooks,
52 + mockGetCredentials: vi.fn(),
53 mockLoggerError: vi.fn(),
54 mockLoggerInfo: vi.fn(),
40 - pusherConstructorOptions: constructorOptions,
55 + pusherConstructorOptions: [] as Array<Record<string, unknown>>,
56 };
57 });
58
59 vi.mock('pusher-js', () => ({
60 default: class FakePusher {
46 - subscribe = mockPusherClient.subscribe;
47 - unsubscribe = mockPusherClient.unsubscribe;
61 constructor(_key: string, options: Record<string, unknown>) {
62 pusherConstructorOptions.push(options);
63 + return createClient();
64 }
65 },
66 }));
@@ -66,29 +80,47 @@ vi.mock('../../src/utils/logger', () => ({
80 },
81 }));
82
69 -describe('PusherService subscription errors', () => {
70 - beforeEach(() => {
71 - bindings.clear();
72 - mockGetCredentials.mockClear();
73 - mockPusherClient.subscribe.mockClear();
74 - mockLoggerError.mockClear();
75 - mockLoggerInfo.mockClear();
83 +const credentials = { projectId: 'project-id', pusherKey: 'pusher-key', pusherCluster: 'mt1' };
84 +
85 +const createService = () =>
86 + new PusherService({ baseURL: 'https://backend.composio.dev', apiKey: 'api-key' } as never);
87 +
88 +const flushMacrotask = () =>
89 + new Promise<void>(resolve => {
90 + setImmediate(resolve);
91 + });
92 +
93 +const deferred = <T>() => {
94 + let resolve!: (value: T) => void;
95 + let reject!: (reason: unknown) => void;
96 + const promise = new Promise<T>((res, rej) => {
97 + resolve = res;
98 + reject = rej;
99 });
100 + return { promise, resolve, reject };
101 +};
102 +
103 +const triggerEvent = { id: 'evt_1' };
104 +
105 +beforeEach(() => {
106 + clients.length = 0;
107 + pusherConstructorOptions.length = 0;
108 + hooks.onClientCreated = () => {};
109 + mockGetCredentials.mockReset().mockResolvedValue(credentials);
110 + mockLoggerError.mockClear();
111 + mockLoggerInfo.mockClear();
112 +});
113
114 +describe('PusherService subscription errors', () => {
115 it('contains subscription errors emitted after subscribe resolves', async () => {
79 - const service = new PusherService({
80 - baseURL: 'https://backend.composio.dev',
81 - apiKey: 'api-key',
82 - } as never);
116 + const service = createService();
117
118 await service.subscribe(vi.fn());
119
86 - await new Promise<void>(resolve => {
87 - setImmediate(resolve);
88 - });
120 + await flushMacrotask();
121
122 expect(() => {
91 - mockChannel.emit('pusher:subscription_error', {
123 + clients[0].channel.emit('pusher:subscription_error', {
124 type: 'AuthError',
125 error: 'Auth error: 401',
126 status: 401,
@@ -104,58 +136,43 @@ describe('PusherService subscription errors', () => {
136 });
137
138 it('logs success only after pusher confirms the subscription', async () => {
107 - const service = new PusherService({
108 - baseURL: 'https://backend.composio.dev',
109 - apiKey: 'api-key',
110 - } as never);
139 + const service = createService();
140
141 await service.subscribe(vi.fn());
142
114 - await new Promise<void>(resolve => {
115 - setImmediate(resolve);
116 - });
143 + await flushMacrotask();
144
118 - mockChannel.emit('pusher:subscription_succeeded', {});
145 + clients[0].channel.emit('pusher:subscription_succeeded', {});
146
147 expect(mockLoggerInfo).toHaveBeenCalledWith(expect.stringContaining('Subscribed to triggers'));
148 });
149
150 it('invokes the optional subscription error callback with the raw payload', async () => {
124 - const service = new PusherService({
125 - baseURL: 'https://backend.composio.dev',
126 - apiKey: 'api-key',
127 - } as never);
151 + const service = createService();
152 const onSubscriptionError = vi.fn();
153
154 await service.subscribe(vi.fn(), onSubscriptionError);
155
132 - await new Promise<void>(resolve => {
133 - setImmediate(resolve);
134 - });
156 + await flushMacrotask();
157
158 const payload = { type: 'AuthError', error: 'Auth error: 401', status: 401 };
137 - mockChannel.emit('pusher:subscription_error', payload);
159 + clients[0].channel.emit('pusher:subscription_error', payload);
160
161 expect(onSubscriptionError).toHaveBeenCalledWith(payload);
162 });
163
164 it('contains exceptions thrown from the subscription error callback', async () => {
143 - const service = new PusherService({
144 - baseURL: 'https://backend.composio.dev',
145 - apiKey: 'api-key',
146 - } as never);
165 + const service = createService();
166 const onSubscriptionError = vi.fn(() => {
167 throw new Error('handler exploded');
168 });
169
170 await service.subscribe(vi.fn(), onSubscriptionError);
171
153 - await new Promise<void>(resolve => {
154 - setImmediate(resolve);
155 - });
172 + await flushMacrotask();
173
174 expect(() => {
158 - mockChannel.emit('pusher:subscription_error', { error: 401 });
175 + clients[0].channel.emit('pusher:subscription_error', { error: 401 });
176 }).not.toThrow();
177
178 expect(onSubscriptionError).toHaveBeenCalledTimes(1);
@@ -166,26 +183,19 @@ describe('PusherService subscription errors', () => {
183 });
184
185 it('contains rejections from async subscription error callbacks', async () => {
169 - const service = new PusherService({
170 - baseURL: 'https://backend.composio.dev',
171 - apiKey: 'api-key',
172 - } as never);
186 + const service = createService();
187 const onSubscriptionError = vi.fn(async () => {
188 throw new Error('async handler failed');
189 });
190
191 await service.subscribe(vi.fn(), onSubscriptionError);
192
179 - await new Promise<void>(resolve => {
180 - setImmediate(resolve);
181 - });
193 + await flushMacrotask();
194
183 - mockChannel.emit('pusher:subscription_error', { error: 401 });
195 + clients[0].channel.emit('pusher:subscription_error', { error: 401 });
196
197 // let the rejected promise settle and the containment log run
186 - await new Promise<void>(resolve => {
187 - setImmediate(resolve);
188 - });
198 + await flushMacrotask();
199
200 expect(onSubscriptionError).toHaveBeenCalledTimes(1);
201 expect(mockLoggerError).toHaveBeenCalledWith(
@@ -193,6 +203,225 @@ describe('PusherService subscription errors', () => {
203 'async handler failed'
204 );
205 });
206 +
207 + it('contains a rejection whose value String() cannot convert', async () => {
208 + // String() throws on an object without a prototype; the failure log runs as a rejection
209 + // handler, so a throw there would escape as an unhandled rejection.
210 + const unhandledRejection = vi.fn();
211 + process.on('unhandledRejection', unhandledRejection);
212 + const unprintable = Object.create(null);
213 + unprintable.self = unprintable;
214 + const service = createService();
215 +
216 + try {
217 + await service.subscribe(vi.fn(), async () => {
218 + throw unprintable;
219 + });
220 + clients[0].channel.emit('pusher:subscription_error', { error: 401 });
221 + await flushMacrotask();
222 +
223 + expect(mockLoggerError).toHaveBeenCalledWith(
224 + '❌ Error in subscription error callback:',
225 + '[unprintable value]'
226 + );
227 + expect(unhandledRejection).not.toHaveBeenCalled();
228 + } finally {
229 + process.off('unhandledRejection', unhandledRejection);
230 + }
231 + });
232 +});
233 +
234 +describe('PusherService trigger callback errors', () => {
235 + it('contains synchronous throws and async rejections from the trigger callback', async () => {
236 + const unhandledRejection = vi.fn();
237 + process.on('unhandledRejection', unhandledRejection);
238 + const service = createService();
239 +
240 + try {
241 + await service.subscribe(() => {
242 + throw new Error('sync failure');
243 + });
244 + await service.subscribe(async () => {
245 + throw new Error('async failure');
246 + });
247 +
248 + expect(() => clients[0].channel.emit('trigger_to_client', triggerEvent)).not.toThrow();
249 + await flushMacrotask();
250 +
251 + expect(mockLoggerError).toHaveBeenCalledWith('❌ Error in trigger callback:', 'sync failure');
252 + expect(mockLoggerError).toHaveBeenCalledWith(
253 + '❌ Error in trigger callback:',
254 + 'async failure'
255 + );
256 + expect(unhandledRejection).not.toHaveBeenCalled();
257 + } finally {
258 + process.off('unhandledRejection', unhandledRejection);
259 + }
260 + });
261 +});
262 +
263 +describe('PusherService connection lifecycle', () => {
264 + it('disconnects the client and removes its handlers on unsubscribe', async () => {
265 + const service = createService();
266 + const handler = vi.fn();
267 + await service.subscribe(handler);
268 +
269 + await service.unsubscribe();
270 +
271 + const [client] = clients;
272 + expect(client.unsubscribe).toHaveBeenCalledWith('private-project-id_triggers');
273 + expect(client.channel.unbind_all).toHaveBeenCalledTimes(1);
274 + expect(client.disconnect).toHaveBeenCalledTimes(1);
275 + client.channel.emit('trigger_to_client', triggerEvent);
276 + expect(handler).not.toHaveBeenCalled();
277 + });
278 +
279 + it('does not create a client or fetch credentials when unsubscribe comes first', async () => {
280 + const service = createService();
281 +
282 + await service.unsubscribe();
283 + await service.unsubscribe();
284 +
285 + expect(mockGetCredentials).not.toHaveBeenCalled();
286 + expect(clients).toHaveLength(0);
287 + });
288 +
289 + it('shares one client between concurrent subscribe calls', async () => {
290 + const credentialsResponse = deferred<typeof credentials>();
291 + mockGetCredentials.mockReturnValueOnce(credentialsResponse.promise);
292 + const service = createService();
293 + const first = vi.fn();
294 + const second = vi.fn();
295 +
296 + const subscriptions = Promise.all([service.subscribe(first), service.subscribe(second)]);
297 + credentialsResponse.resolve(credentials);
298 + await subscriptions;
299 +
300 + expect(mockGetCredentials).toHaveBeenCalledTimes(1);
301 + expect(clients).toHaveLength(1);
302 + clients[0].channel.emit('trigger_to_client', triggerEvent);
303 + expect(first).toHaveBeenCalledWith(triggerEvent);
304 + expect(second).toHaveBeenCalledWith(triggerEvent);
305 +
306 + await service.unsubscribe();
307 + expect(clients[0].disconnect).toHaveBeenCalledTimes(1);
308 + });
309 +
310 + it('cancels a subscribe that is still waiting for credentials', async () => {
311 + const credentialsResponse = deferred<typeof credentials>();
312 + mockGetCredentials.mockReturnValueOnce(credentialsResponse.promise);
313 + const service = createService();
314 +
315 + const subscription = service.subscribe(vi.fn());
316 + await service.unsubscribe();
317 + credentialsResponse.resolve(credentials);
318 +
319 + await expect(subscription).resolves.toBeUndefined();
320 + expect(clients).toHaveLength(0);
321 + });
322 +
323 + it('does not report a credentials failure for a subscribe cancelled by unsubscribe', async () => {
324 + const credentialsResponse = deferred<typeof credentials>();
325 + mockGetCredentials.mockReturnValueOnce(credentialsResponse.promise);
326 + const service = createService();
327 +
328 + const subscription = service.subscribe(vi.fn());
329 + await service.unsubscribe();
330 + credentialsResponse.reject(new Error('network down'));
331 +
332 + await expect(subscription).resolves.toBeUndefined();
333 + expect(clients).toHaveLength(0);
334 + });
335 +
336 + it('does not install handlers when unsubscribe runs after the client was created', async () => {
337 + const service = createService();
338 + const handler = vi.fn();
339 + // Runs unsubscribe() after the client exists but before the waiting subscribe() resumes.
340 + const created = new Promise<void>(resolve => {
341 + hooks.onClientCreated = resolve;
342 + });
343 +
344 + const subscription = service.subscribe(handler);
345 + await created;
346 + await service.unsubscribe();
347 + await subscription;
348 +
349 + const [client] = clients;
350 + expect(client.disconnect).toHaveBeenCalledTimes(1);
351 + expect(client.channel.bind).not.toHaveBeenCalled();
352 + });
353 +
354 + it('keeps the later subscribe when unsubscribe interleaves with pending setup', async () => {
355 + const staleCredentials = deferred<typeof credentials>();
356 + mockGetCredentials.mockReturnValueOnce(staleCredentials.promise);
357 + const service = createService();
358 + const staleHandler = vi.fn();
359 + const liveHandler = vi.fn();
360 +
361 + const stale = service.subscribe(staleHandler);
362 + await service.unsubscribe();
363 + await service.subscribe(liveHandler);
364 + staleCredentials.resolve(credentials);
365 + await stale;
366 +
367 + expect(clients).toHaveLength(1);
368 + clients[0].channel.emit('trigger_to_client', triggerEvent);
369 + expect(liveHandler).toHaveBeenCalledTimes(1);
370 + expect(staleHandler).not.toHaveBeenCalled();
371 +
372 + await service.unsubscribe();
373 + expect(clients[0].disconnect).toHaveBeenCalledTimes(1);
374 + });
375 +
376 + it('opens a fresh connection for a subscribe after unsubscribe', async () => {
377 + const service = createService();
378 + const firstHandler = vi.fn();
379 + const secondHandler = vi.fn();
380 +
381 + await service.subscribe(firstHandler);
382 + await service.unsubscribe();
383 + await service.subscribe(secondHandler);
384 +
385 + expect(clients).toHaveLength(2);
386 + const [oldClient, newClient] = clients;
387 + // A late event or auth reply on the old client reaches nothing.
388 + oldClient.channel.emit('trigger_to_client', triggerEvent);
389 + oldClient.channel.emit('pusher:subscription_error', { error: 401 });
390 + newClient.channel.emit('trigger_to_client', triggerEvent);
391 + expect(firstHandler).not.toHaveBeenCalled();
392 + expect(secondHandler).toHaveBeenCalledTimes(1);
393 + expect(mockLoggerError).not.toHaveBeenCalled();
394 + expect(newClient.disconnect).not.toHaveBeenCalled();
395 + });
396 +
397 + it('leaves no connected client or bound handler behind after repeated cycles', async () => {
398 + const service = createService();
399 +
400 + for (let cycle = 0; cycle < 5; cycle++) {
401 + await service.subscribe(vi.fn());
402 + await service.unsubscribe();
403 + }
404 +
405 + expect(clients).toHaveLength(5);
406 + for (const client of clients) {
407 + expect(client.channel.bind).toHaveBeenCalled();
408 + expect(client.channel.unbind_all).toHaveBeenCalledTimes(1);
409 + expect(client.disconnect).toHaveBeenCalledTimes(1);
410 + }
411 + });
412 +
413 + it('retries after a credentials failure', async () => {
414 + mockGetCredentials.mockRejectedValueOnce(new Error('network down'));
415 + const service = createService();
416 +
417 + await expect(service.subscribe(vi.fn())).rejects.toBeInstanceOf(
418 + ComposioFailedToSubscribeToPusherChannelError
419 + );
420 + await service.subscribe(vi.fn());
421 +
422 + expect(mockGetCredentials).toHaveBeenCalledTimes(2);
423 + expect(clients).toHaveLength(1);
424 + });
425 });
426
427 describe('PusherService channel authorization credentials', () => {
@@ -206,8 +435,6 @@ describe('PusherService channel authorization credentials', () => {
435 };
436
437 beforeEach(() => {
209 - bindings.clear();
210 - pusherConstructorOptions.length = 0;
438 vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignAmbientKey');
439 });
440