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, 04:45 UTC
| 1 | import ComposioClient from '@composio/client'; |
| 2 | import { PusherChannel, PusherClient, TChunkedTriggerData } from '../../types/pusher.types'; |
| 3 | import { InternalService } from '../internal/InternalService'; |
| 4 | import { SDKRealtimeCredentialsResponse } from '../internal/InternalService.types'; |
| 5 | import { |
| 6 | ComposioFailedToCreatePusherClientError, |
| 7 | ComposioFailedToGetSDKRealtimeCredentialsError, |
| 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'; |
| 15 | |
| 16 | export type PusherServiceOptions = { |
| 17 | /** The project API key the owning SDK instance resolved, or `null` when disabled. */ |
| 18 | apiKey?: string | null; |
| 19 | /** The user API key the owning SDK instance resolved, or `null`. */ |
| 20 | userApiKey?: string | null; |
| 21 | /** The organization API key the owning SDK instance resolved, or `null`. */ |
| 22 | orgApiKey?: string | null; |
| 23 | /** Default headers of the owning SDK instance; only `x-user-api-key` is consulted. */ |
| 24 | defaultHeaders?: ComposioRequestHeaders; |
| 25 | }; |
| 26 | |
| 27 | /** A pusher-js client and the triggers channel it subscribed to. */ |
| 28 | type TriggerConnection = { |
| 29 | client: PusherClient; |
| 30 | channel: PusherChannel; |
| 31 | channelName: string; |
| 32 | }; |
| 33 | |
| 34 | /** |
| 35 | * Setup of the connection for one subscription period, which runs from the first `subscribe()` |
| 36 | * to the next `unsubscribe()`. Concurrent `subscribe()` calls share `ready`; `unsubscribe()` |
| 37 | * aborts `controller` so that setup still in flight neither connects nor installs handlers. |
| 38 | */ |
| 39 | type ConnectionAttempt = { |
| 40 | controller: AbortController; |
| 41 | ready: Promise<TriggerConnection>; |
| 42 | }; |
| 43 | |
| 44 | /** |
| 45 | * Owns the realtime connection that delivers trigger events. |
| 46 | * |
| 47 | * Each subscription period gets its own pusher-js client, which `unsubscribe()` disconnects. |
| 48 | * Reusing one client across periods is unsafe: pusher-js keeps a channel, its bound handlers and |
| 49 | * its cancellation flag through `disconnect()` and resubscribes every kept channel on the next |
| 50 | * `connect()`, and a channel-auth reply requested on the old socket can arrive after a reconnect |
| 51 | * and be sent on the new one. |
| 52 | */ |
| 53 | export class PusherService { |
| 54 | // these details are set via the client SDK |
| 55 | private pusherBaseURL!: string; |
| 56 | private authHeaders!: Record<string, string>; |
| 57 | private composioClient!: ComposioClient; |
| 58 | private attempt?: ConnectionAttempt; |
| 59 | // Set as soon as the current attempt creates its client, so that `unsubscribe()` can close it |
| 60 | // before the `subscribe()` calls waiting on `attempt.ready` resume. |
| 61 | private connection?: TriggerConnection; |
| 62 | |
| 63 | constructor(client: ComposioClient, options: PusherServiceOptions = {}) { |
| 64 | this.composioClient = client; |
| 65 | this.pusherBaseURL = client.baseURL; |
| 66 | // Channel authorization mirrors the SDK instance's effective auth, from the |
| 67 | // keys the SDK resolved; the environment is never consulted here. |
| 68 | this.authHeaders = resolveCredentialHeaders({ |
| 69 | apiKey: options.apiKey, |
| 70 | userApiKey: options.userApiKey, |
| 71 | orgApiKey: options.orgApiKey, |
| 72 | defaultHeaders: options.defaultHeaders, |
| 73 | }); |
| 74 | telemetry.instrument(this, 'PusherService'); |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Returns the connection attempt of the current subscription period, starting one if needed. |
| 79 | * A failed attempt is forgotten, so the next `subscribe()` retries. |
| 80 | */ |
| 81 | private connect(): ConnectionAttempt { |
| 82 | if (this.attempt) return this.attempt; |
| 83 | |
| 84 | const controller = new AbortController(); |
| 85 | const ready = this.openConnection(controller.signal); |
| 86 | const attempt = { controller, ready }; |
| 87 | this.attempt = attempt; |
| 88 | ready.catch(() => { |
| 89 | if (this.attempt === attempt) this.attempt = undefined; |
| 90 | }); |
| 91 | return attempt; |
| 92 | } |
| 93 | |
| 94 | /** |
| 95 | * Fetches the SDK realtime credentials from the Apollo API, creates a Pusher client and |
| 96 | * subscribes it to the triggers channel. |
| 97 | */ |
| 98 | private async openConnection(signal: AbortSignal): Promise<TriggerConnection> { |
| 99 | const internalService = new InternalService(this.composioClient); |
| 100 | let sdkRealtimeCredentials: SDKRealtimeCredentialsResponse; |
| 101 | try { |
| 102 | sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials(); |
| 103 | } catch (error) { |
| 104 | throw new ComposioFailedToGetSDKRealtimeCredentialsError( |
| 105 | 'Failed to get SDK realtime credentials', |
| 106 | { |
| 107 | cause: error, |
| 108 | } |
| 109 | ); |
| 110 | } |
| 111 | |
| 112 | const { projectId, pusherKey, pusherCluster } = sdkRealtimeCredentials; |
| 113 | const channelName = `private-${projectId}_triggers`; |
| 114 | |
| 115 | let Pusher: (typeof import('pusher-js'))['default']; |
| 116 | try { |
| 117 | ({ default: Pusher } = await import('pusher-js')); |
| 118 | } catch (error) { |
| 119 | throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', { |
| 120 | cause: error, |
| 121 | }); |
| 122 | } |
| 123 | |
| 124 | // unsubscribe() ran while the credentials or pusher-js were loading. Everything below is |
| 125 | // synchronous, so this is the last point at which it can cancel the attempt. |
| 126 | if (signal.aborted) { |
| 127 | throw new Error('Connection attempt cancelled by unsubscribe()'); |
| 128 | } |
| 129 | |
| 130 | logger.debug( |
| 131 | `[PusherService] Creating Pusher client for client ID: ${projectId} in cluster ${pusherCluster}` |
| 132 | ); |
| 133 | |
| 134 | let client: PusherClient; |
| 135 | try { |
| 136 | client = new Pusher(pusherKey, { |
| 137 | cluster: pusherCluster, |
| 138 | channelAuthorization: { |
| 139 | endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`, |
| 140 | headers: { ...this.authHeaders }, |
| 141 | transport: 'ajax', |
| 142 | }, |
| 143 | }); |
| 144 | } catch (error) { |
| 145 | throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', { |
| 146 | cause: error, |
| 147 | }); |
| 148 | } |
| 149 | |
| 150 | logger.debug(`[PusherService] Subscribing to channel: ${channelName}`); |
| 151 | try { |
| 152 | this.connection = { client, channel: client.subscribe(channelName), channelName }; |
| 153 | } catch (error) { |
| 154 | client.disconnect(); |
| 155 | throw error; |
| 156 | } |
| 157 | return this.connection; |
| 158 | } |
| 159 | |
| 160 | /** |
| 161 | * Binds a chunked event to a Pusher client |
| 162 | * |
| 163 | * |
| 164 | * @param channel - The Pusher client to bind the event to |
| 165 | * @param event - The event to bind to |
| 166 | * @param callback - The function to call when the event is received |
| 167 | */ |
| 168 | private bindWithChunking( |
| 169 | channel: PusherChannel, |
| 170 | event: string, |
| 171 | callback: (data: Record<string, unknown>) => void |
| 172 | ): void { |
| 173 | try { |
| 174 | channel.bind(event, callback); |
| 175 | |
| 176 | // Now the chunked variation. Allows arbitrarily long messages. |
| 177 | const events: { |
| 178 | [key: string]: { chunks: string[]; receivedFinal: boolean }; |
| 179 | } = {}; |
| 180 | |
| 181 | channel.bind('chunked-' + event, data => { |
| 182 | try { |
| 183 | const typedData = data as TChunkedTriggerData; |
| 184 | |
| 185 | // Validate chunked data |
| 186 | if ( |
| 187 | !typedData || |
| 188 | typeof typedData.id !== 'string' || |
| 189 | typeof typedData.index !== 'number' |
| 190 | ) { |
| 191 | throw new Error('Invalid chunked trigger data format'); |
| 192 | } |
| 193 | |
| 194 | if (!events.hasOwnProperty(typedData.id)) { |
| 195 | events[typedData.id] = { chunks: [], receivedFinal: false }; |
| 196 | } |
| 197 | |
| 198 | const ev = events[typedData.id]; |
| 199 | ev.chunks[typedData.index] = typedData.chunk; |
| 200 | |
| 201 | if (typedData.final) ev.receivedFinal = true; |
| 202 | |
| 203 | if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) { |
| 204 | try { |
| 205 | const parsedData = JSON.parse(ev.chunks.join('')); |
| 206 | callback(parsedData); |
| 207 | } catch (parseError: unknown) { |
| 208 | const errorMessage = |
| 209 | parseError instanceof Error ? parseError.message : String(parseError); |
| 210 | logger.error('Failed to parse chunked data:', errorMessage); |
| 211 | } finally { |
| 212 | delete events[typedData.id]; |
| 213 | } |
| 214 | } |
| 215 | } catch (error: unknown) { |
| 216 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 217 | logger.error('Error processing chunked trigger data:', errorMessage); |
| 218 | // Clean up the event data to prevent memory leaks |
| 219 | if (data && typeof data === 'object' && 'id' in data) { |
| 220 | delete events[data.id as string]; |
| 221 | } |
| 222 | } |
| 223 | }); |
| 224 | } catch (error: unknown) { |
| 225 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 226 | logger.error('Failed to bind chunked events:', error); |
| 227 | throw new Error(`Failed to bind chunked events: ${errorMessage}`); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /** |
| 232 | * Subscribes to pusher to receive events from the server |
| 233 | * |
| 234 | * The first call of a subscription period creates the Pusher client; concurrent calls share |
| 235 | * it. A call still waiting for the client when `unsubscribe()` runs resolves without |
| 236 | * subscribing. |
| 237 | * |
| 238 | * @param fn - The function to call when the event is received |
| 239 | * @param onSubscriptionError - Optional callback invoked with the raw payload when the |
| 240 | * Pusher subscription fails (for example on auth or permission rejection). Errors thrown |
| 241 | * from — or promises rejected by — this callback are contained and logged, never rethrown. |
| 242 | */ |
| 243 | async subscribe( |
| 244 | fn: (data: Record<string, unknown>) => void, |
| 245 | onSubscriptionError?: (data: Record<string, unknown>) => void |
| 246 | ) { |
| 247 | const attempt = this.connect(); |
| 248 | let connection: TriggerConnection; |
| 249 | try { |
| 250 | connection = await attempt.ready; |
| 251 | } catch (error) { |
| 252 | if (attempt.controller.signal.aborted) { |
| 253 | logger.debug('[PusherService] Subscribe cancelled by unsubscribe() before it connected'); |
| 254 | return; |
| 255 | } |
| 256 | throw new ComposioFailedToSubscribeToPusherChannelError( |
| 257 | 'Failed to subscribe to Pusher channel', |
| 258 | { |
| 259 | cause: error, |
| 260 | } |
| 261 | ); |
| 262 | } |
| 263 | // unsubscribe() ran after the client was created but before this call resumed. |
| 264 | if (attempt.controller.signal.aborted) { |
| 265 | logger.debug('[PusherService] Subscribe cancelled by unsubscribe() before it connected'); |
| 266 | return; |
| 267 | } |
| 268 | |
| 269 | try { |
| 270 | const { channel } = connection; |
| 271 | channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => { |
| 272 | logger.error('Trigger subscription error:', data); |
| 273 | |
| 274 | // surface the failure to the caller without letting a faulty |
| 275 | // handler crash the host (same containment as the trigger callback). |
| 276 | invokeUserCallback('❌ Error in subscription error callback:', () => |
| 277 | onSubscriptionError?.(data) |
| 278 | ); |
| 279 | }); |
| 280 | |
| 281 | // log success only when Pusher itself confirms the subscription |
| 282 | channel.bind('pusher:subscription_succeeded', () => { |
| 283 | logger.info(`✅ Subscribed to triggers. You should start receiving events now.`); |
| 284 | }); |
| 285 | |
| 286 | // don't let a failing callback break the subscription |
| 287 | const safeCallback = (data: Record<string, unknown>) => { |
| 288 | invokeUserCallback('❌ Error in trigger callback:', () => fn(data)); |
| 289 | }; |
| 290 | |
| 291 | this.bindWithChunking(channel, 'trigger_to_client', safeCallback); |
| 292 | } catch (error) { |
| 293 | throw new ComposioFailedToSubscribeToPusherChannelError( |
| 294 | 'Failed to subscribe to Pusher channel', |
| 295 | { |
| 296 | cause: error, |
| 297 | } |
| 298 | ); |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | /** |
| 303 | * Unsubscribes from the triggers channel and closes the connection |
| 304 | * |
| 305 | * This ends the subscription period: setup still in flight is cancelled, the handlers bound by |
| 306 | * every `subscribe()` call are removed, and the Pusher client is disconnected. Without a prior |
| 307 | * `subscribe()` this does nothing; it never creates a client or fetches credentials. |
| 308 | */ |
| 309 | async unsubscribe() { |
| 310 | const { attempt, connection } = this; |
| 311 | this.attempt = undefined; |
| 312 | this.connection = undefined; |
| 313 | attempt?.controller.abort(); |
| 314 | |
| 315 | if (!connection) { |
| 316 | logger.debug('[PusherService] No open connection to unsubscribe from'); |
| 317 | return; |
| 318 | } |
| 319 | |
| 320 | logger.debug(`[PusherService] Unsubscribing from channel: ${connection.channelName}`); |
| 321 | try { |
| 322 | // pusher-js keeps a reference to every client it creates, so release the handlers this |
| 323 | // service bound and the user callbacks they hold. |
| 324 | connection.channel.unbind_all(); |
| 325 | connection.client.unsubscribe(connection.channelName); |
| 326 | } catch (error) { |
| 327 | throw new ComposioFailedToSubscribeToPusherChannelError( |
| 328 | 'Failed to unsubscribe from Pusher channel', |
| 329 | { |
| 330 | cause: error, |
| 331 | } |
| 332 | ); |
| 333 | } finally { |
| 334 | connection.client.disconnect(); |
| 335 | } |
| 336 | logger.info(`✅ Unsubscribed from triggers.`); |
| 337 | } |
| 338 | } |