requestWithRetry<T> function

Future<DataResponse<T>> requestWithRetry<T>(
  1. RequestOptions options, {
  2. int retryCount = 0,
  3. Client? client,
})

Make HTTP request with retry logic

Implementation

Future<DataResponse<T>> requestWithRetry<T>(
  RequestOptions options, {
  int retryCount = 0,
  http.Client? client,
}) async {
  try {
    // Prepare headers
    final headers = <String, String>{...?options.headers};

    // Handle JSON content type
    if (options.json != null || options.responseType == ResponseType.json) {
      headers['Content-Type'] = 'application/json';
      headers['Accept'] = 'application/json';
    }

    // Prepare request body
    String? bodyString;
    if (options.json != null) {
      bodyString = jsonEncode(options.json);
    } else if (options.body != null) {
      bodyString = options.body.toString();
    }

    // Create HTTP request
    final request = http.Request(options.method, Uri.parse(options.url));
    request.headers.addAll(headers);
    if (bodyString != null) {
      request.body = bodyString;
      if (options.url.contains('oauth.ring.com')) {
        // ignore: avoid_print
        print('[DEBUG] OAuth request body: ${bodyString.length} chars');
        // ignore: avoid_print
        print('[DEBUG] OAuth headers: ${headers.keys.toList()}');
      }
    }

    // Make the request with timeout
    final httpClient = client ?? http.Client();
    final shouldCloseClient = client == null;
    try {
      final streamedResponse = await httpClient
          .send(request)
          .timeout(
            options.timeout,
            onTimeout: () {
              throw TimeoutException(
                'Request timed out after ${options.timeout.inSeconds}s',
              );
            },
          );

      final response = await http.Response.fromStream(streamedResponse);

      if (response.statusCode < 200 || response.statusCode >= 300) {
        if (options.url.contains('oauth.ring.com')) {
          // ignore: avoid_print
          print('[DEBUG] OAuth response status: ${response.statusCode}');
          // ignore: avoid_print
          print('[DEBUG] OAuth response body: ${response.body}');
        }
        final error = await _responseToError(response);
        throw error;
      }

      // Parse response data
      T data;
      if (options.responseType == ResponseType.buffer) {
        data = response.bodyBytes as T;
      } else {
        final text = response.body;
        if (text.isEmpty) {
          data = null as T;
        } else {
          try {
            data = jsonDecode(text) as T;
          } catch (_) {
            data = text as T;
          }
        }
      }

      // Extract timestamps from headers
      int? responseTimestamp;
      int? timeMillis;

      final dateHeader = response.headers['date'];
      if (dateHeader != null) {
        try {
          responseTimestamp = DateTime.parse(dateHeader).millisecondsSinceEpoch;
        } catch (_) {
          // ignore
        }
      }

      final xTimeHeader = response.headers['x-time-millis'];
      if (xTimeHeader != null) {
        timeMillis = int.tryParse(xTimeHeader);
      }

      return DataResponse<T>(
        data: data,
        responseTimestamp: responseTimestamp,
        timeMillis: timeMillis,
      );
    } finally {
      if (shouldCloseClient) {
        httpClient.close();
      }
    }
  } catch (e) {
    // Check if this is a network error (no response from server)
    final isNetworkError = e is! ResponseError;

    if (isNetworkError && !options.allowNoResponse) {
      if (retryCount > 0) {
        String detailedError = 'Error: ${e.toString()}';
        if (e is Exception) {
          detailedError += ', Exception: ${e.runtimeType}';
        }
        logError(
          'Retry #$retryCount failed to reach Ring server at ${options.url}. '
          '$detailedError. Trying again in 5 seconds...',
        );
        logDebug(e);
      }

      await delay(5000);
      return requestWithRetry<T>(
        options,
        retryCount: retryCount + 1,
        client: client,
      );
    }

    rethrow;
  }
}