From 04b7a41d18744d2e882a486862ec2afb7433655f Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Thu, 13 Aug 2015 09:39:04 -0700 Subject: [PATCH] php: add watchForReady method --- src/php/lib/Grpc/BaseStub.php | 34 +++++++++++++++++++++++ src/php/tests/unit_tests/EndToEndTest.php | 17 +++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/php/lib/Grpc/BaseStub.php b/src/php/lib/Grpc/BaseStub.php index 9f5c07b5f5e..dc507df92cf 100755 --- a/src/php/lib/Grpc/BaseStub.php +++ b/src/php/lib/Grpc/BaseStub.php @@ -82,6 +82,40 @@ class BaseStub { 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 */ diff --git a/src/php/tests/unit_tests/EndToEndTest.php b/src/php/tests/unit_tests/EndToEndTest.php index df4cebc9662..4c0cf91d512 100755 --- a/src/php/tests/unit_tests/EndToEndTest.php +++ b/src/php/tests/unit_tests/EndToEndTest.php @@ -175,7 +175,7 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{ $this->assertTrue($idle_state == Grpc\CHANNEL_IDLE); $now = Grpc\Timeval::now(); - $delta = new Grpc\Timeval(100000); + $delta = new Grpc\Timeval(3000000); // should finish well before $deadline = $now->add($delta); $this->assertTrue($this->channel->watchConnectivityState( @@ -184,4 +184,19 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{ $new_state = $this->channel->getConnectivityState(); $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); + } }