WordPress.org

Making WordPress.org

Changeset 4379


Ignore:
Timestamp:
11/19/2016 09:40:13 PM (4 years ago)
Author:
iandunn
Message:

WordCamp Helpers: Add a wrapper for wp_remote_get() that retries failures

File:
1 edited

Legend:

Unmodified
Added
Removed
  • sites/trunk/wordcamp.org/public_html/wp-content/mu-plugins/helper-functions.php

    r4253 r4379  
    11<?php
     2
     3use WordCamp\Logger;
    24
    35/**
     
    217219    return $fields;
    218220}
     221
     222/**
     223 * Make a remote HTTP request, and retry if it fails
     224 *
     225 * Sometimes the HTTP request times out, or there's a temporary server-side error, etc. Some use cases require a
     226 * successful request, like stats scripts, where the resulting data would be distorted by a failed response.
     227 *
     228 * @todo Remove this if https://github.com/rmccue/Requests/issues/222 is implemented
     229 *
     230 * @param string $request_url
     231 * @param array  $request_args
     232 *
     233 * @return array|WP_Error
     234 */
     235function wcorg_redundant_remote_get( $request_url, $request_args = array() ) {
     236    $attempt_count = 1;
     237
     238    while ( true ) {
     239        $response    = wp_remote_get( $request_url, $request_args );
     240        $status_code = wp_remote_retrieve_response_code( $response );
     241        $body        = wp_remote_retrieve_body( $response );
     242        $retry_after = wp_remote_retrieve_header( $response, 'retry-after' ) ?: 5;
     243        $retry_after = min( $retry_after * $attempt_count, 30 );
     244
     245        if ( ! is_wp_error( $response ) && 200 === $status_code && $body ) {
     246            break;
     247        }
     248
     249        if ( $attempt_count < 3 ) {
     250            Logger\log( 'request_failed_temporarily', compact( 'request_url', 'request_args', 'response', 'attempt_count', 'retry_after' ) );
     251            sleep( $retry_after );
     252        } else {
     253            Logger\log( 'request_failed_permenantly', compact( 'request_url', 'request_args', 'response' ) );
     254            break;
     255        }
     256
     257        $attempt_count++;
     258    }
     259
     260    return $response;
     261}
Note: See TracChangeset for help on using the changeset viewer.