{"version":3,"file":"algo-http-client-with-retry.mjs","names":[],"sources":["../../src/types/algo-http-client-with-retry.ts"],"sourcesContent":["import { IntDecoding, parseJSON, stringifyJSON } from 'algosdk'\nimport { BaseHTTPClientResponse, Query, URLTokenBaseHTTPClient } from 'algosdk/client'\nimport { Config } from '../config'\n\n/** A HTTP Client that wraps the Algorand SDK HTTP Client with retries */\nexport class AlgoHttpClientWithRetry extends URLTokenBaseHTTPClient {\n  private static readonly MAX_TRIES = 5\n  private static readonly MAX_BACKOFF_MS = 10000\n\n  // These lists come from https://visionmedia.github.io/superagent/#retrying-requests\n  // which is the underlying library used by algosdk - but the CloudFlare specific 52X status codes have been removed\n  private static readonly RETRY_STATUS_CODES = [408, 413, 429, 500, 502, 503, 504]\n  private static readonly RETRY_ERROR_CODES = [\n    'ETIMEDOUT',\n    'ECONNRESET',\n    'EADDRINUSE',\n    'ECONNREFUSED',\n    'EPIPE',\n    'ENOTFOUND',\n    'ENETUNREACH',\n    'EAI_AGAIN',\n    'EPROTO', // We get this intermittently with AlgoNode API\n  ]\n\n  private async callWithRetry(func: () => Promise<BaseHTTPClientResponse>): Promise<BaseHTTPClientResponse> {\n    let response: BaseHTTPClientResponse | undefined\n    let numTries = 1\n    do {\n      try {\n        response = await func()\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      } catch (err: any) {\n        if (numTries >= AlgoHttpClientWithRetry.MAX_TRIES) {\n          throw err\n        }\n        // Only retry for one of the hardcoded conditions\n        if (\n          !(\n            AlgoHttpClientWithRetry.RETRY_ERROR_CODES.includes(err.code) ||\n            AlgoHttpClientWithRetry.RETRY_STATUS_CODES.includes(Number(err.status)) ||\n            ('response' in err && AlgoHttpClientWithRetry.RETRY_STATUS_CODES.includes(Number(err.response.status)))\n          )\n        ) {\n          throw err\n        }\n        // Retry immediately the first time, then exponentially backoff.\n        const delayTimeMs = numTries == 1 ? 0 : Math.min(1000 * Math.pow(2, numTries - 1), AlgoHttpClientWithRetry.MAX_BACKOFF_MS)\n        if (delayTimeMs > 0) {\n          await new Promise((r) => setTimeout(r, delayTimeMs))\n        }\n        Config.logger.warn(`algosdk request failed ${numTries} times. Retrying in ${delayTimeMs}ms: ${err}`)\n      }\n    } while (!response && ++numTries <= AlgoHttpClientWithRetry.MAX_TRIES)\n    return response!\n  }\n\n  async get(relativePath: string, query?: Query<string>, requestHeaders: Record<string, string> = {}): Promise<BaseHTTPClientResponse> {\n    const response = await this.callWithRetry(() => super.get(relativePath, query, requestHeaders))\n    if (\n      relativePath.startsWith('/v2/accounts/') &&\n      relativePath.endsWith('/created-applications') &&\n      response.status === 200 &&\n      query?.['include-all']?.toString() === 'true'\n    ) {\n      // todo: Temporary hack\n      // Indexer get created applications by account returns approvalProgram and clearStateProgram as null, which breaks the algosdk@3 decoder\n      // instead we will detect this call and set them to empty byte arrays\n      try {\n        const json = parseJSON(Buffer.from(response.body).toString(), { intDecoding: IntDecoding.MIXED })\n        if (json.applications) {\n          for (const app of json.applications) {\n            if (app.params) {\n              if (app.params['approval-program'] === null) {\n                app.params['approval-program'] = ''\n              }\n              if (app.params['clear-state-program'] === null) {\n                app.params['clear-state-program'] = ''\n              }\n            }\n          }\n          response.body = Buffer.from(stringifyJSON(json))\n        }\n      } catch (e) {\n        // Make this hack resilient so we never break the app\n        Config.logger.warn('Failed to fix indexer response for created applications', e)\n      }\n    }\n    return response\n  }\n\n  async post(\n    relativePath: string,\n    data: Uint8Array,\n    query?: Query<string>,\n    requestHeaders: Record<string, string> = {},\n  ): Promise<BaseHTTPClientResponse> {\n    return await this.callWithRetry(() => super.post(relativePath, data, query, requestHeaders))\n  }\n\n  async delete(\n    relativePath: string,\n    data: Uint8Array,\n    query?: Query<string>,\n    requestHeaders: Record<string, string> = {},\n  ): Promise<BaseHTTPClientResponse> {\n    return await this.callWithRetry(() => super.delete(relativePath, data, query, requestHeaders))\n  }\n}\n"],"mappings":";;;;;AAKA,IAAa,0BAAb,MAAa,gCAAgC,uBAAuB;CAClE,OAAwB,YAAY;CACp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