Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 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 { |
| 8 | clients, |
| 9 | createClient, |
| 10 | hooks, |
| 11 | mockGetCredentials, |
| 12 | mockLoggerError, |
| 13 | mockLoggerInfo, |
| 14 | pusherConstructorOptions, |
| 15 | } = vi.hoisted(() => { |
| 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 { |
| 44 | clients: createdClients, |
| 45 | createClient: () => { |
| 46 | const client = new FakeClient(); |
| 47 | createdClients.push(client); |
| 48 | testHooks.onClientCreated(); |
| 49 | return client; |
| 50 | }, |
| 51 | hooks: testHooks, |
| 52 | mockGetCredentials: vi.fn(), |
| 53 | mockLoggerError: vi.fn(), |
| 54 | mockLoggerInfo: vi.fn(), |
| 55 | pusherConstructorOptions: [] as Array<Record<string, unknown>>, |
| 56 | }; |
| 57 | }); |
| 58 | |
| 59 | vi.mock('pusher-js', () => ({ |
| 60 | default: class FakePusher { |
| 61 | constructor(_key: string, options: Record<string, unknown>) { |
| 62 | pusherConstructorOptions.push(options); |
| 63 | return createClient(); |
| 64 | } |
| 65 | }, |
| 66 | })); |
| 67 | |
| 68 | vi.mock('../../src/services/internal/InternalService', () => ({ |
| 69 | InternalService: class FakeInternalService { |
| 70 | getSDKRealtimeCredentials = mockGetCredentials; |
| 71 | }, |
| 72 | })); |
| 73 | |
| 74 | vi.mock('../../src/utils/logger', () => ({ |
| 75 | default: { |
| 76 | debug: vi.fn(), |
| 77 | error: mockLoggerError, |
| 78 | info: mockLoggerInfo, |
| 79 | warn: vi.fn(), |
| 80 | }, |
| 81 | })); |
| 82 | |
| 83 | const credentials = { projectId: 'project-id', pusherKey: 'pusher-key', pusherCluster: 'mt1' }; |
| 84 | |
| 85 | const createService = () => |
| 86 | new PusherService({ baseURL: 'https://backend.composio.dev' } as never, { apiKey: 'api-key' }); |
| 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 () => { |
| 116 | const service = createService(); |
| 117 | |
| 118 | await service.subscribe(vi.fn()); |
| 119 | |
| 120 | await flushMacrotask(); |
| 121 | |
| 122 | expect(() => { |
| 123 | clients[0].channel.emit('pusher:subscription_error', { |
| 124 | type: 'AuthError', |
| 125 | error: 'Auth error: 401', |
| 126 | status: 401, |
| 127 | }); |
| 128 | }).not.toThrow(); |
| 129 | |
| 130 | expect(mockLoggerError).toHaveBeenCalledWith('Trigger subscription error:', { |
| 131 | type: 'AuthError', |
| 132 | error: 'Auth error: 401', |
| 133 | status: 401, |
| 134 | }); |
| 135 | expect(mockLoggerInfo).not.toHaveBeenCalled(); |
| 136 | }); |
| 137 | |
| 138 | it('logs success only after pusher confirms the subscription', async () => { |
| 139 | const service = createService(); |
| 140 | |
| 141 | await service.subscribe(vi.fn()); |
| 142 | |
| 143 | await flushMacrotask(); |
| 144 | |
| 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 () => { |
| 151 | const service = createService(); |
| 152 | const onSubscriptionError = vi.fn(); |
| 153 | |
| 154 | await service.subscribe(vi.fn(), onSubscriptionError); |
| 155 | |
| 156 | await flushMacrotask(); |
| 157 | |
| 158 | const payload = { type: 'AuthError', error: 'Auth error: 401', status: 401 }; |
| 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 () => { |
| 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 | |
| 172 | await flushMacrotask(); |
| 173 | |
| 174 | expect(() => { |
| 175 | clients[0].channel.emit('pusher:subscription_error', { error: 401 }); |
| 176 | }).not.toThrow(); |
| 177 | |
| 178 | expect(onSubscriptionError).toHaveBeenCalledTimes(1); |
| 179 | expect(mockLoggerError).toHaveBeenCalledWith( |
| 180 | '❌ Error in subscription error callback:', |
| 181 | 'handler exploded' |
| 182 | ); |
| 183 | }); |
| 184 | |
| 185 | it('contains rejections from async subscription error callbacks', async () => { |
| 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 | |
| 193 | await flushMacrotask(); |
| 194 | |
| 195 | clients[0].channel.emit('pusher:subscription_error', { error: 401 }); |
| 196 | |
| 197 | // let the rejected promise settle and the containment log run |
| 198 | await flushMacrotask(); |
| 199 | |
| 200 | expect(onSubscriptionError).toHaveBeenCalledTimes(1); |
| 201 | expect(mockLoggerError).toHaveBeenCalledWith( |
| 202 | '❌ Error in subscription error callback:', |
| 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', () => { |
| 428 | const baseURL = 'https://backend.composio.dev'; |
| 429 | const channelAuthHeaders = () => { |
| 430 | const options = pusherConstructorOptions.at(-1)!; |
| 431 | const channelAuthorization = options.channelAuthorization as { |
| 432 | headers: Record<string, string>; |
| 433 | }; |
| 434 | return channelAuthorization.headers; |
| 435 | }; |
| 436 | |
| 437 | beforeEach(() => { |
| 438 | vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignAmbientKey'); |
| 439 | }); |
| 440 | |
| 441 | afterEach(() => { |
| 442 | vi.unstubAllEnvs(); |
| 443 | }); |
| 444 | |
| 445 | it('sends the project key the SDK resolved as x-api-key', async () => { |
| 446 | const service = new PusherService({ baseURL } as never, { apiKey: 'ak_projectKey' }); |
| 447 | |
| 448 | await service.subscribe(vi.fn()); |
| 449 | |
| 450 | expect(channelAuthHeaders()).toEqual({ 'x-api-key': 'ak_projectKey' }); |
| 451 | }); |
| 452 | |
| 453 | it('sends no project key and never reads COMPOSIO_API_KEY when the SDK key is null', async () => { |
| 454 | const service = new PusherService({ baseURL } as never, { apiKey: null, userApiKey: null }); |
| 455 | |
| 456 | await service.subscribe(vi.fn()); |
| 457 | |
| 458 | expect(channelAuthHeaders()).toEqual({}); |
| 459 | expect(JSON.stringify(pusherConstructorOptions)).not.toContain('ak_foreignAmbientKey'); |
| 460 | }); |
| 461 | |
| 462 | it('sends the user API key the SDK resolved when the project key is null', async () => { |
| 463 | const service = new PusherService({ baseURL } as never, { |
| 464 | apiKey: null, |
| 465 | userApiKey: 'uak_userKey', |
| 466 | }); |
| 467 | |
| 468 | await service.subscribe(vi.fn()); |
| 469 | |
| 470 | expect(channelAuthHeaders()).toEqual({ 'x-user-api-key': 'uak_userKey' }); |
| 471 | }); |
| 472 | |
| 473 | it('sends the organization API key when it is the only key the SDK resolved', async () => { |
| 474 | const service = new PusherService({ baseURL } as never, { |
| 475 | apiKey: null, |
| 476 | userApiKey: null, |
| 477 | orgApiKey: 'oak_orgKey', |
| 478 | }); |
| 479 | |
| 480 | await service.subscribe(vi.fn()); |
| 481 | |
| 482 | expect(channelAuthHeaders()).toEqual({ 'x-org-api-key': 'oak_orgKey' }); |
| 483 | }); |
| 484 | |
| 485 | it('never reads a key back from the API client', async () => { |
| 486 | const client = { |
| 487 | baseURL, |
| 488 | get apiKey(): string { |
| 489 | throw new Error('client.apiKey must not be read'); |
| 490 | }, |
| 491 | get userApiKey(): string { |
| 492 | throw new Error('client.userApiKey must not be read'); |
| 493 | }, |
| 494 | }; |
| 495 | const service = new PusherService(client as never, { apiKey: 'ak_sdkKey' }); |
| 496 | |
| 497 | await service.subscribe(vi.fn()); |
| 498 | |
| 499 | expect(channelAuthHeaders()).toEqual({ 'x-api-key': 'ak_sdkKey' }); |
| 500 | }); |
| 501 | |
| 502 | it('falls back to the x-user-api-key default header when the SDK holds no key', async () => { |
| 503 | const service = new PusherService({ baseURL } as never, { |
| 504 | apiKey: null, |
| 505 | userApiKey: null, |
| 506 | defaultHeaders: { 'X-User-Api-Key': 'uak_headerKey', 'x-request-id': 'req-1' }, |
| 507 | }); |
| 508 | |
| 509 | await service.subscribe(vi.fn()); |
| 510 | |
| 511 | expect(channelAuthHeaders()).toEqual({ 'x-user-api-key': 'uak_headerKey' }); |
| 512 | }); |
| 513 | }); |