44
55use Clue \Redis \Protocol \Factory as ProtocolFactory ;
66use React \EventLoop \LoopInterface ;
7- use React \Promise ;
87use React \Promise \Deferred ;
8+ use React \Promise \Timer \TimeoutException ;
99use React \Socket \ConnectionInterface ;
1010use React \Socket \Connector ;
1111use React \Socket \ConnectorInterface ;
1212use InvalidArgumentException ;
1313
1414class Factory
1515{
16+ private $ loop ;
1617 private $ connector ;
1718 private $ protocol ;
1819
@@ -32,6 +33,7 @@ public function __construct(LoopInterface $loop, ConnectorInterface $connector =
3233 $ protocol = new ProtocolFactory ();
3334 }
3435
36+ $ this ->loop = $ loop ;
3537 $ this ->connector = $ connector ;
3638 $ this ->protocol = $ protocol ;
3739 }
@@ -47,7 +49,7 @@ public function createClient($target)
4749 try {
4850 $ parts = $ this ->parseUrl ($ target );
4951 } catch (InvalidArgumentException $ e ) {
50- return Promise \reject ($ e );
52+ return \ React \ Promise \reject ($ e );
5153 }
5254
5355 $ connecting = $ this ->connector ->connect ($ parts ['authority ' ]);
@@ -97,7 +99,20 @@ function ($error) use ($client) {
9799
98100 $ promise ->then (array ($ deferred , 'resolve ' ), array ($ deferred , 'reject ' ));
99101
100- return $ deferred ->promise ();
102+ // use timeout from explicit ?timeout=x parameter or default to PHP's default_socket_timeout (60)
103+ $ timeout = (float ) isset ($ parts ['timeout ' ]) ? $ parts ['timeout ' ] : ini_get ("default_socket_timeout " );
104+ if ($ timeout < 0 ) {
105+ return $ deferred ->promise ();
106+ }
107+
108+ return \React \Promise \Timer \timeout ($ deferred ->promise (), $ timeout , $ this ->loop )->then (null , function ($ e ) {
109+ if ($ e instanceof TimeoutException) {
110+ throw new \RuntimeException (
111+ 'Connection to database server timed out after ' . $ e ->getTimeout () . ' seconds '
112+ );
113+ }
114+ throw $ e ;
115+ });
101116 }
102117
103118 /**
@@ -150,6 +165,10 @@ private function parseUrl($target)
150165 if (isset ($ args ['db ' ])) {
151166 $ ret ['db ' ] = $ args ['db ' ];
152167 }
168+
169+ if (isset ($ args ['timeout ' ])) {
170+ $ ret ['timeout ' ] = $ args ['timeout ' ];
171+ }
153172 }
154173
155174 return $ ret ;
0 commit comments