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

Cleanup pusher

haxzie committed May 28, 2025 at 17:09 UTC 45e0ed0aa354aa9df7a32e2c33b7bc4cc5a3c803
2 files changed +290 -7
packages/core/src/types/triggers.types.ts
-7
@@ -118,13 +118,6 @@ export const IncomingTriggerPayloadSchema = z.object({
118
119 export type IncomingTriggerPayload = z.infer<typeof IncomingTriggerPayloadSchema>;
120
121 -type TChunkedTriggerData = {
122 - id: string;
123 - index: number;
124 - chunk: string;
125 - final: boolean;
126 -};
127 -
121 export type TriggerData = {
122 appName: string;
123 clientId: number;
packages/core/src/utils/pusher.ts new
+290
@@ -0,0 +1,290 @@
1 +import { PusherSubscriptionError } from '../errors/PusherErrors';
2 +import logger from './logger';
3 +
4 +const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || 'ff9f18c208855d77a152';
5 +const PUSHER_CLUSTER = 'mt1';
6 +
7 +type Channel = {
8 + subscribe: (channelName: string) => unknown;
9 + unsubscribe: (channelName: string) => unknown;
10 + bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown;
11 +};
12 +
13 +type PusherClient = {
14 + subscribe: (channelName: string) => Channel;
15 + unsubscribe: (channelName: string) => unknown;
16 + bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown;
17 + connection: {
18 + bind: (event: string, callback: (error: Error) => void) => void;
19 + socket_id?: string;
20 + };
21 +};
22 +
23 +type AuthOptions = {
24 + endpoint: string;
25 + headers: Record<string, string>;
26 + params?: Record<string, string>;
27 +};
28 +
29 +type TChunkedTriggerData = {
30 + id: string;
31 + index: number;
32 + chunk: string;
33 + final: boolean;
34 +};
35 +
36 +export type TriggerData = {
37 + appName: string;
38 + clientId: number;
39 + payload: Record<string, unknown>;
40 + originalPayload: Record<string, unknown>;
41 + metadata: {
42 + id: string;
43 + connectionId: string;
44 + triggerName: string;
45 + triggerData: string;
46 + triggerConfig: Record<string, unknown>;
47 + connection: {
48 + id: string;
49 + integrationId: string;
50 + clientUniqueUserId: string;
51 + status: string;
52 + connectedAccountNanoId: string;
53 + authConfigNanoId: string;
54 + };
55 + };
56 +};
57 +
58 +export class PusherUtils {
59 + static pusherClient: PusherClient;
60 +
61 + static async getPusherClient(baseURL: string, apiKey: string): Promise<PusherClient> {
62 + try {
63 + if (!PusherUtils.pusherClient) {
64 + // Dynamic import not available, using require for now
65 + // TODO: Update to use dynamic import when available
66 + // eslint-disable-next-line @typescript-eslint/no-require-imports
67 + const PusherClient = require('pusher-js');
68 + PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
69 + cluster: PUSHER_CLUSTER,
70 + channelAuthorization: {
71 + endpoint: `${baseURL}/api/v3/internal/sdk/realtime/auth`,
72 + headers: {
73 + 'x-api-key': apiKey,
74 + },
75 + transport: 'ajax',
76 + customHandler: async (authOptions: AuthOptions) => {
77 + try {
78 + const response = await fetch(authOptions.endpoint, {
79 + method: 'POST',
80 + headers: {
81 + ...authOptions.headers,
82 + 'Content-Type': 'application/json',
83 + },
84 + body: JSON.stringify(authOptions.params),
85 + });
86 + const data = await response.text();
87 + logger.debug('Pusher auth response:', data);
88 + try {
89 + return JSON.parse(data);
90 + } catch (e) {
91 + logger.error('Failed to parse auth response:', e);
92 + throw new Error('Invalid auth response format');
93 + }
94 + } catch (error) {
95 + logger.error('Pusher auth request failed:', error);
96 + throw error;
97 + }
98 + },
99 + },
100 + });
101 +
102 + // Add connection error handling
103 + PusherUtils.pusherClient.connection.bind('error', (err: Error) => {
104 + logger.error('Pusher connection error:', err);
105 + throw new Error(`Pusher connection error: ${err.message}`);
106 + });
107 + }
108 + return PusherUtils.pusherClient;
109 + } catch (error: unknown) {
110 + const errorMessage = error instanceof Error ? error.message : String(error);
111 + logger.error('Failed to initialize Pusher client:', error);
112 + throw new Error(`Failed to initialize Pusher client: ${errorMessage}`);
113 + }
114 + }
115 +
116 + /**
117 + * Subscribes to a Pusher channel and binds an event to a callback function.
118 + * @param {string} channelName - The name of the channel to subscribe to.
119 + * @param {string} event - The event to bind to the channel.
120 + * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
121 + * @returns {PusherClient} The Pusher client instance.
122 + */
123 + static async subscribe(
124 + channelName: string,
125 + event: string,
126 + fn: (data: Record<string, unknown>) => void
127 + ): Promise<void> {
128 + try {
129 + await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
130 + } catch (error) {
131 + logger.error(`Error subscribing to ${channelName} with event ${event}: ${error}`);
132 + }
133 + }
134 +
135 + /**
136 + * Unsubscribes from a Pusher channel.
137 + * @param {string} channelName - The name of the channel to unsubscribe from.
138 + * @returns {void}
139 + */
140 + static async unsubscribe(channelName: string): Promise<void> {
141 + PusherUtils.pusherClient.unsubscribe(channelName);
142 + }
143 +
144 + /**
145 + * Binds an event to a channel with support for chunked messages.
146 + * @param {PusherClient} channel - The Pusher channel to bind the event to.
147 + * @param {string} event - The event to bind to the channel.
148 + * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
149 + */
150 + private static bindWithChunking(
151 + channel: PusherClient,
152 + event: string,
153 + callback: (data: Record<string, unknown>) => void
154 + ): void {
155 + try {
156 + // Wrap the callback to handle errors
157 + const safeCallback = (data: Record<string, unknown>) => {
158 + try {
159 + callback(data);
160 + } catch (error: unknown) {
161 + const errorMessage = error instanceof Error ? error.message : String(error);
162 + logger.error('Error in chunked event callback:', errorMessage);
163 + // Don't throw here to prevent breaking the subscription
164 + }
165 + };
166 +
167 + channel.bind(event, safeCallback);
168 +
169 + // Now the chunked variation. Allows arbitrarily long messages.
170 + const events: {
171 + [key: string]: { chunks: string[]; receivedFinal: boolean };
172 + } = {};
173 +
174 + channel.bind('chunked-' + event, data => {
175 + try {
176 + const typedData = data as TChunkedTriggerData;
177 +
178 + // Validate chunked data
179 + if (
180 + !typedData ||
181 + typeof typedData.id !== 'string' ||
182 + typeof typedData.index !== 'number'
183 + ) {
184 + throw new Error('Invalid chunked trigger data format');
185 + }
186 +
187 + if (!events.hasOwnProperty(typedData.id)) {
188 + events[typedData.id] = { chunks: [], receivedFinal: false };
189 + }
190 +
191 + const ev = events[typedData.id];
192 + ev.chunks[typedData.index] = typedData.chunk;
193 +
194 + if (typedData.final) ev.receivedFinal = true;
195 +
196 + if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
197 + try {
198 + const parsedData = JSON.parse(ev.chunks.join(''));
199 + safeCallback(parsedData);
200 + } catch (parseError: unknown) {
201 + const errorMessage =
202 + parseError instanceof Error ? parseError.message : String(parseError);
203 + logger.error('Failed to parse chunked data:', errorMessage);
204 + } finally {
205 + delete events[typedData.id];
206 + }
207 + }
208 + } catch (error: unknown) {
209 + const errorMessage = error instanceof Error ? error.message : String(error);
210 + logger.error('Error processing chunked trigger data:', errorMessage);
211 + // Clean up the event data to prevent memory leaks
212 + if (data && typeof data === 'object' && 'id' in data) {
213 + delete events[data.id as string];
214 + }
215 + }
216 + });
217 + } catch (error: unknown) {
218 + const errorMessage = error instanceof Error ? error.message : String(error);
219 + logger.error('Failed to bind chunked events:', error);
220 + throw new Error(`Failed to bind chunked events: ${errorMessage}`);
221 + }
222 + }
223 +
224 + /**
225 + * Subscribes to a trigger channel for a client and handles chunked data.
226 + * @param {string} clientId - The unique identifier for the client subscribing to the events.
227 + * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
228 + *
229 + * @example
230 + * ```ts
231 + * composio.trigger.subscribe((data) => {
232 + * console.log(data);
233 + * });
234 + * ```
235 + */
236 + static triggerSubscribe(clientId: string, fn: (data: TriggerData) => void): void {
237 + try {
238 + if (!PusherUtils.pusherClient) {
239 + throw new Error('Pusher client not initialized');
240 + }
241 +
242 + const channel = PusherUtils.pusherClient.subscribe(`private-${clientId}_triggers`);
243 +
244 + // Add subscription error handling
245 + channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
246 + const error = data.error ? String(data.error) : 'Unknown subscription error';
247 + throw new PusherSubscriptionError(`Trigger subscription error`, {
248 + cause: error,
249 + });
250 + });
251 +
252 + // Wrap the callback to handle errors
253 + const safeCallback = (data: TriggerData) => {
254 + try {
255 + fn(data);
256 + } catch (error: unknown) {
257 + const errorMessage = error instanceof Error ? error.message : String(error);
258 + logger.error('Error in trigger callback:', errorMessage);
259 + // Don't throw here to prevent breaking the subscription
260 + }
261 + };
262 +
263 + PusherUtils.bindWithChunking(
264 + channel as PusherClient,
265 + 'trigger_to_client',
266 + safeCallback as (data: unknown) => void
267 + );
268 +
269 + logger.info(`Subscribed to triggers. You should start receiving events now.`);
270 + } catch (error: unknown) {
271 + const errorMessage = error instanceof Error ? error.message : String(error);
272 + logger.error('Failed to subscribe to triggers:', error);
273 + throw new Error(`Failed to subscribe to triggers: ${errorMessage}`);
274 + }
275 + }
276 +
277 + static triggerUnsubscribe(clientId: string): void {
278 + try {
279 + if (!PusherUtils.pusherClient) {
280 + throw new Error('Pusher client not initialized');
281 + }
282 + PusherUtils.pusherClient.unsubscribe(`private-${clientId}_triggers`);
283 + logger.info('Successfully unsubscribed from triggers');
284 + } catch (error: unknown) {
285 + const errorMessage = error instanceof Error ? error.message : String(error);
286 + logger.error('Failed to unsubscribe from triggers:', error);
287 + throw new Error(`Failed to unsubscribe from triggers: ${errorMessage}`);
288 + }
289 + }
290 +}