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

next
ts 165 lines 6.37 KB
Raw
1 /**
2 * @fileoverview Connection request function for Composio SDK, used to manage an initiated connection request.
3 *
4 * @author Musthaq Ahamad <musthaq@composio.dev>
5 * @date 2025-05-05
6 * @module ConnectionRequest
7 */
8 import ComposioClient from '@composio/client';
9 import {
10 ConnectedAccountStatus,
11 ConnectedAccountStatuses,
12 ConnectedAccountRetrieveResponse,
13 } from '../types/connectedAccounts.types';
14 import {
15 ConnectionRequestFailedError,
16 ConnectionRequestTimeoutError,
17 } from '../errors/ConnectionRequestErrors';
18 import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccountsErrors';
19 import { telemetry } from '../telemetry/Telemetry';
20 import { transformConnectedAccountResponse } from '../utils/transformers/connectedAccounts';
21 import { ConnectionRequest, ConnectionRequestState } from '../types/connectionRequest.types';
22 import { getRetryAfterSeconds, isRateLimitResponse } from '../utils/rateLimit';
23
24 const INITIAL_POLL_DELAY_MS = 1000;
25 const MAX_POLL_DELAY_MS = 5000;
26 const POLL_DELAY_GROWTH = 1.5;
27
28 /**
29 * Creates a connection request object with methods to manage the connection lifecycle.
30 *
31 * @param {ComposioClient} client - The Composio client instance
32 * @param {string} connectedAccountId - The ID of the connected account
33 * @param {ConnectedAccountStatus} [status] - Initial status of the connection
34 * @param {string | null} [redirectUrl] - OAuth redirect URL if applicable
35 * @returns {ConnectionRequest} Connection request object with state and methods
36 */
37 export function createConnectionRequest(
38 client: ComposioClient,
39 connectedAccountId: string,
40 status?: ConnectedAccountStatus,
41 redirectUrl?: string | null
42 ): ConnectionRequest {
43 // `waitForConnection` records each observed status on this same object, so
44 // `request.status` and `toJSON()` never disagree.
45 const request: ConnectionRequest = {
46 id: connectedAccountId,
47 status: status || ConnectedAccountStatuses.INITIATED,
48 redirectUrl,
49 waitForConnection,
50 toJSON: (): ConnectionRequestState => ({
51 id: request.id,
52 status: request.status,
53 redirectUrl: request.redirectUrl,
54 }),
55 toString: () => JSON.stringify(request.toJSON(), null, 2),
56 };
57
58 telemetry.instrument(request, 'ConnectionRequest');
59
60 /**
61 * Waits for the connection request to complete and become active.
62 *
63 * This method polls the Composio API to check the status of the connection request until it
64 * either becomes active, enters a terminal error state, or times out. The delay between polls
65 * grows from 1 second to 5 seconds, so a connection can be up to 5 seconds old when this returns.
66 * A rate-limited poll doesn't fail the wait: once the client's own retries run out, it waits as
67 * long as the response asks before polling again. If that delay reaches the timeout, the wait
68 * times out without another poll. The client's retries can carry the wait past the timeout,
69 * because they aren't bound by it.
70 *
71 * @param {number} [timeout=60000] - Maximum time to wait in milliseconds before timing out (default: 60 seconds)
72 * @returns {Promise<ConnectedAccountRetrieveResponse>} The final connected account response when successful
73 * @throws {ComposioConnectedAccountNotFoundError} If the connected account cannot be found
74 * @throws {ConnectionRequestFailedError} If the connection enters a failed, expired, or deleted state
75 * @throws {ConnectionRequestTimeoutError} If the connection request does not complete within the timeout period
76 *
77 * @example
78 * ```typescript
79 * // Wait for connection with default timeout (60 seconds)
80 * try {
81 * const connection = await connectionRequest.waitForConnection();
82 * console.log('Connection established:', connection.id);
83 * } catch (error) {
84 * console.error('Connection failed:', error.message);
85 * }
86 *
87 * // Wait for connection with custom timeout (2 minutes)
88 * const connection = await connectionRequest.waitForConnection(120000);
89 * ```
90 */
91 async function waitForConnection(
92 timeout: number = 60000
93 ): Promise<ConnectedAccountRetrieveResponse> {
94 const terminalErrorStates: ConnectedAccountStatus[] = [
95 ConnectedAccountStatuses.FAILED,
96 ConnectedAccountStatuses.EXPIRED,
97 ConnectedAccountStatuses.REVOKED,
98 ];
99 const failIfTerminal = (response: {
100 status: ConnectedAccountStatus;
101 status_reason?: string | null;
102 }) => {
103 if (terminalErrorStates.includes(response.status)) {
104 throw new ConnectionRequestFailedError(
105 `Connection request failed with status: ${response.status}${response.status_reason ? `, reason: ${response.status_reason}` : ''}`,
106 {
107 meta: {
108 connectedAccountId: request.id,
109 status: response.status,
110 statusReason: response.status_reason,
111 },
112 }
113 );
114 }
115 };
116
117 const deadline = Date.now() + timeout;
118 let pollDelay = INITIAL_POLL_DELAY_MS;
119
120 while (true) {
121 let delay = pollDelay;
122 let rateLimited = false;
123 try {
124 const response = await client.connectedAccounts.retrieve(request.id);
125 request.status = response.status;
126 if (response.status === ConnectedAccountStatuses.ACTIVE) {
127 return transformConnectedAccountResponse(response);
128 }
129 failIfTerminal(response);
130 } catch (error) {
131 if (error instanceof ComposioClient.NotFoundError) {
132 throw new ComposioConnectedAccountNotFoundError(
133 `Connected account with id ${request.id} not found`,
134 {
135 meta: {
136 connectedAccountId: request.id,
137 },
138 }
139 );
140 }
141 if (!isRateLimitResponse(error)) {
142 throw error;
143 }
144 rateLimited = true;
145 delay = Math.max(delay, (getRetryAfterSeconds(error) ?? 0) * 1000);
146 }
147
148 const remaining = deadline - Date.now();
149 // Written so a NaN timeout times out rather than polling forever.
150 if (!(remaining > 0)) {
151 break;
152 }
153 await new Promise(resolve => setTimeout(resolve, Math.min(delay, remaining)));
154 // A rate-limited poll must not start a fresh client retry cycle at the deadline.
155 if (rateLimited && Date.now() >= deadline) {
156 break;
157 }
158 pollDelay = Math.min(pollDelay * POLL_DELAY_GROWTH, MAX_POLL_DELAY_MS);
159 }
160
161 throw new ConnectionRequestTimeoutError(`Connection request timed out for ${request.id}`);
162 }
163
164 return request;
165 }