twitteroauth icon indicating copy to clipboard operation
twitteroauth copied to clipboard

Add error resilience in uploadMediaChunked method

Open abzolv opened this issue 5 years ago • 3 comments

The last week or so, some upload requests generate a PHP Notice error on $init->media_id_string, saying media_id_string does not exist.

That's either because the init request failed, or because of a Twitter bug that does not return media_id_string.

I'd suggest adding resilience by checking the init request response code and automatically retrying it a few times, with usleeps inbetween, if the response code is >= 500.

abzolv avatar Apr 08 '19 10:04 abzolv

Thanks. I'll put this on the list. In the meantime you should wrap the media upload request in a catch and retry if it fails.

abraham avatar Apr 18 '19 14:04 abraham

It is happening for some image uploads constantly for me

usamaejaz avatar Aug 12 '19 09:08 usamaejaz

This is happening to me too, and I have worked it out easily by just retrying every upload until it works or a number of failed retries is reached, whatever happens first. And with a small time delay in-between, as @abzolv suggest.

I have set up a simple convenience function for this:

function retry($function, int $maxRetries = 5, int $delay = 500) {
    $retries = 0;
    $failed = false;
    do {
        $result = $function();
        if ($result) {
            return $result;
        }

        usleep($delay * 1000);

        $failed = ++$retries >= $maxRetries;
    } while (!$failed);

    return false;
}

And I am now wrapping every asset upload with it so it is automatically retried:

$media_id_string = retry(function() use ($connection, $thumbnail) {
    $result = $connection->upload('media/upload', [
        'media' => $thumbnail,
    ]);
    return empty($result->media_id_string) ? false : $result->media_id_string;
});

I still keep the error-checking logic in place, but now it only triggers an error when the upload fails for five times in a row in a 2.5 seconds time span, which has never happened to me yet:

if (!$media_id_string) {
    $error = sprintf('Error uploading %s to Twitter', $thumbnail);
    trigger_error($error, E_USER_ERROR);
}

Perhaps this issue could be addressed just by suggesting an approach like this one in the docs, leaving to the consumer the responsibility to retry failed API calls.

JaimeObregon avatar Oct 16 '20 18:10 JaimeObregon

this is still an issue. are you planning on fixing it?

ldunphyAK avatar Jun 06 '23 15:06 ldunphyAK

TwitterOAuth is in maintenance mode and major improvements are no longer planned. https://github.com/abraham/twitteroauth/issues/1188

abraham avatar Jul 24 '23 03:07 abraham