import * as Flex from '@twilio/flex-ui'; import { FlexPluginError } from '../ErrorManager'; import { EncodedParams, FlexPluginErrorContents } from '../../types'; import { delay, getPluginSpecificData } from '../../utils'; import { RETRY_CONFIG } from '../../constants'; import { FlexPluginErrorType } from '../../enums'; import datadogBrowserLogger from '../BrowserLogger'; type ErrorManager = { createAndProcessError: ( message: string, content?: FlexPluginErrorContents, showNotification?: boolean ) => FlexPluginError; }; export interface ApiServiceConfig { errorManager?: ErrorManager; serverlessDomain?: string; retryConfig?: { maxAttempts?: number; maxRetryDelay?: number; retryInterval?: number; }; } export abstract class ApiService { readonly serverlessDomain: string; protected manager = Flex.Manager.getInstance(); protected errorManager?: ErrorManager; // Retry configuration private readonly maxAttempts: number; private readonly maxRetryDelay: number; private readonly retryInterval: number; constructor(config: ApiServiceConfig = {}) { this.errorManager = config.errorManager; // Set retry configuration with defaults const retryConfig = config.retryConfig ?? {}; this.maxAttempts = retryConfig.maxAttempts ?? RETRY_CONFIG.MAX_ATTEMPTS; this.maxRetryDelay = retryConfig.maxRetryDelay ?? RETRY_CONFIG.MAX_RETRY_DELAY; this.retryInterval = retryConfig.retryInterval ?? RETRY_CONFIG.RETRY_INTERVAL; try { this.serverlessDomain = config.serverlessDomain ?? process.env.FLEX_APP_SERVERLESS_FUNCTONS_DOMAIN ?? ''; if (!this.serverlessDomain) throw Error('serverless_functions_domain is not set'); } catch (e) { this.errorManager?.createAndProcessError('Could not set serverless function domain', { type: FlexPluginErrorType.serverless, description: e instanceof Error ? `${e.message}` : 'Could not set serverless function domain', context: 'Plugin.ApiService', wrappedError: e, }); // Set a default empty domain to prevent further errors this.serverlessDomain = ''; } } protected buildBody(encodedParams: EncodedParams): string { return Object.keys(encodedParams).reduce((result, paramName, idx) => { if (encodedParams[paramName] === undefined) { return result; } if (idx > 0) { return `${result}&${paramName}=${encodedParams[paramName]}`; } return `${paramName}=${encodedParams[paramName]}`; }, ''); } protected async fetchJsonWithReject(url: string, config: RequestInit, attempts = 0): Promise { return fetch(url, config) .then(async (response) => { if (!response.ok) { throw response; } const logInfoData = { url, method: config.method, status: response.status, statusText: response.statusText, timestamp: new Date().toISOString(), type: FlexPluginErrorType.serverless, ...getPluginSpecificData(url) } datadogBrowserLogger?.info('API SUCCESS - ', logInfoData); return response.json(); }) .catch(async (error) => { try { // Generic retry when calls return a 'too many requests' response // or when Fetch API returns a TypeError due to a network error const logErrorData = { url, method: config.method, status: error.status, statusText: error.statusText, timestamp: new Date().toISOString(), message: error.message, type: FlexPluginErrorType.serverless, ...getPluginSpecificData(url) } datadogBrowserLogger?.error('API ERROR - ', logErrorData); if ( ((error instanceof TypeError && (error.message === 'Failed to fetch' || error.message === 'NetworkError when attempting to fetch resource.')) || error.status === 429) && attempts < this.maxAttempts ) { // Calculate the exponential backoff delay const backoffDelay = Math.min(this.maxRetryDelay, this.retryInterval * Math.pow(2, attempts)); // Apply full jitter to the delay; reduces load const jitterDelay = Math.floor(backoffDelay * Math.random()); await delay(jitterDelay); return await this.fetchJsonWithReject(url, config, attempts + 1); } return error.json().then((response: any) => { if (typeof response === 'object' && Object.keys(response).length > 0) { // Error response body is an actual JSON object with keys; return them all throw { status: error.status, ...response, }; } else { // Error response body is not JSON throw { status: error.status, message: response, }; } }); } catch (e) { // Process error with error manager if available this.errorManager?.createAndProcessError('API request failed', { type: FlexPluginErrorType.serverless, description: error instanceof Error ? error.message : 'Unknown error occurred', context: 'Plugin.ApiService.fetchJsonWithReject', wrappedError: error, }); throw error; } }); } }