php: add watchForReady method

pull/2877/head
Stanley Cheung 9 years ago
parent 4c5c7b8647
commit 04b7a41d18
  1. 34
      src/php/lib/Grpc/BaseStub.php
  2. 17
      src/php/tests/unit_tests/EndToEndTest.php

@ -82,6 +82,40 @@ class BaseStub {
return $this->channel->getConnectivityState($try_to_connect); return $this->channel->getConnectivityState($try_to_connect);
} }
/**
* @param $timeout in microseconds
* @return bool true if channel is ready
*/
public function watchForReady($timeout) {
$new_state = $this->getConnectivityState(true);
if ($this->_checkConnectivityState($new_state)) {
return true;
}
$now = Timeval::now();
$delta = new Timeval($timeout);
$deadline = $now->add($delta);
if (!$this->channel->watchConnectivityState($new_state, $deadline)) {
return false;
}
$new_state = $this->getConnectivityState();
if ($this->_checkConnectivityState($new_state)) {
return true;
}
return false;
}
private function _checkConnectivityState($new_state) {
if ($new_state == Grpc\CHANNEL_READY) {
return true;
}
if ($new_state == Grpc\CHANNEL_FATAL_ERROR) {
throw new Exception('Failed to connect to server');
}
return false;
}
/** /**
* Close the communication channel associated with this stub * Close the communication channel associated with this stub
*/ */

@ -175,7 +175,7 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
$this->assertTrue($idle_state == Grpc\CHANNEL_IDLE); $this->assertTrue($idle_state == Grpc\CHANNEL_IDLE);
$now = Grpc\Timeval::now(); $now = Grpc\Timeval::now();
$delta = new Grpc\Timeval(100000); $delta = new Grpc\Timeval(3000000); // should finish well before
$deadline = $now->add($delta); $deadline = $now->add($delta);
$this->assertTrue($this->channel->watchConnectivityState( $this->assertTrue($this->channel->watchConnectivityState(
@ -184,4 +184,19 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
$new_state = $this->channel->getConnectivityState(); $new_state = $this->channel->getConnectivityState();
$this->assertTrue($idle_state != $new_state); $this->assertTrue($idle_state != $new_state);
} }
public function testWatchConnectivityStateDoNothing() {
$idle_state = $this->channel->getConnectivityState();
$this->assertTrue($idle_state == Grpc\CHANNEL_IDLE);
$now = Grpc\Timeval::now();
$delta = new Grpc\Timeval(100000);
$deadline = $now->add($delta);
$this->assertFalse($this->channel->watchConnectivityState(
$idle_state, $deadline));
$new_state = $this->channel->getConnectivityState();
$this->assertTrue($new_state == Grpc\CHANNEL_IDLE);
}
} }

Loading…
Cancel
Save