Skip to content

Commit

Permalink
Fix connection pilot’s backoff logic (#4955)
Browse files Browse the repository at this point in the history
  • Loading branch information
WPprodigy committed Oct 24, 2023
1 parent 831579e commit 2f5f738
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,13 @@ public function test__should_back_off( ?int $backoff_factor, DateTime $dt, bool

public function get_test_data__update_backoff_factor() {
return [
'null' => [ null, 1 ],
'zero' => [ 0, 1 ],
'one' => [ 1, 2 ],
'two' => [ 2, 4 ],
'max' => [ 2048, 2048 ],
'null' => [ null, 1 ],
'zero' => [ 0, 1 ],
'one_hour' => [ 1, 2 ],
'two_hours' => [ 2, 4 ],
'three_days' => [ 72, 144 ],
'max' => [ 168, 168 ],
'over_max' => [ 2000, 168 ],
];
}

Expand Down
28 changes: 8 additions & 20 deletions vip-jetpack/connection-pilot/class-jetpack-connection-pilot.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,21 +180,14 @@ public function reconnect( $prev_connection_error = null ) {
*/
private function should_back_off(): bool {
if ( ! empty( $this->last_heartbeat['backoff_factor'] ) && ! empty( $this->last_heartbeat['timestamp'] ) ) {
$backoff_factor = $this->last_heartbeat['backoff_factor'];

// Ensure we don't go past the max, and support future decreases should they occur.
if ( $backoff_factor > self::MAX_BACKOFF_FACTOR ) {
$backoff_factor = self::MAX_BACKOFF_FACTOR;
$this->update_heartbeat( $backoff_factor );
}
$backoff_factor = min( $this->last_heartbeat['backoff_factor'], self::MAX_BACKOFF_FACTOR );

if ( $backoff_factor > 0 ) {
$dt_heartbeat = ( new DateTime() )->setTimestamp( $this->last_heartbeat['timestamp'] );
$dt_now = new DateTime();
$diff = $dt_now->diff( $dt_heartbeat, true );
$seconds_elapsed = time() - $this->last_heartbeat['timestamp'];
$hours_elapsed = $seconds_elapsed / HOUR_IN_SECONDS;

// Checking the difference in hours from the last heartbeat
if ( $diff && $diff->h < $backoff_factor ) {
if ( $backoff_factor > $hours_elapsed ) {
// We're still in the backoff period.
return true;
}
}
Expand All @@ -211,15 +204,10 @@ private function should_back_off(): bool {
private function update_backoff_factor(): void {
$backoff_factor = isset( $this->last_heartbeat['backoff_factor'] ) ? (int) $this->last_heartbeat['backoff_factor'] : 0;

if ( $backoff_factor >= self::MAX_BACKOFF_FACTOR ) {
return;
} elseif ( $backoff_factor <= 0 ) {
$backoff_factor = 1;
} else {
$backoff_factor = $backoff_factor * 2;
}
// Start at 1 hour, then double the backoff factor each time.
$backoff_factor = $backoff_factor <= 0 ? 1 : $backoff_factor * 2;

$this->update_heartbeat( $backoff_factor );
$this->update_heartbeat( min( $backoff_factor, self::MAX_BACKOFF_FACTOR ) );
}

/**
Expand Down

0 comments on commit 2f5f738

Please sign in to comment.