4
4
5
5
use Clue \Redis \Protocol \Factory as ProtocolFactory ;
6
6
use React \EventLoop \LoopInterface ;
7
- use React \Promise ;
8
7
use React \Promise \Deferred ;
8
+ use React \Promise \Timer \TimeoutException ;
9
9
use React \Socket \ConnectionInterface ;
10
10
use React \Socket \Connector ;
11
11
use React \Socket \ConnectorInterface ;
12
12
use InvalidArgumentException ;
13
13
14
14
class Factory
15
15
{
16
+ private $ loop ;
16
17
private $ connector ;
17
18
private $ protocol ;
18
19
@@ -32,6 +33,7 @@ public function __construct(LoopInterface $loop, ConnectorInterface $connector =
32
33
$ protocol = new ProtocolFactory ();
33
34
}
34
35
36
+ $ this ->loop = $ loop ;
35
37
$ this ->connector = $ connector ;
36
38
$ this ->protocol = $ protocol ;
37
39
}
@@ -47,7 +49,7 @@ public function createClient($target)
47
49
try {
48
50
$ parts = $ this ->parseUrl ($ target );
49
51
} catch (InvalidArgumentException $ e ) {
50
- return Promise \reject ($ e );
52
+ return \ React \ Promise \reject ($ e );
51
53
}
52
54
53
55
$ connecting = $ this ->connector ->connect ($ parts ['authority ' ]);
@@ -97,7 +99,20 @@ function ($error) use ($client) {
97
99
98
100
$ promise ->then (array ($ deferred , 'resolve ' ), array ($ deferred , 'reject ' ));
99
101
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
+ });
101
116
}
102
117
103
118
/**
@@ -150,6 +165,10 @@ private function parseUrl($target)
150
165
if (isset ($ args ['db ' ])) {
151
166
$ ret ['db ' ] = $ args ['db ' ];
152
167
}
168
+
169
+ if (isset ($ args ['timeout ' ])) {
170
+ $ ret ['timeout ' ] = $ args ['timeout ' ];
171
+ }
153
172
}
154
173
155
174
return $ ret ;
0 commit comments