-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Factory.php
203 lines (178 loc) · 8.41 KB
/
Factory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
<?php
namespace Clue\React\Redis;
use Clue\Redis\Protocol\Factory as ProtocolFactory;
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
use React\Promise\Timer\TimeoutException;
use React\Socket\ConnectionInterface;
use React\Socket\Connector;
use React\Socket\ConnectorInterface;
class Factory
{
/** @var LoopInterface */
private $loop;
/** @var ConnectorInterface */
private $connector;
/** @var ProtocolFactory */
private $protocol;
/**
* @param ?LoopInterface $loop
* @param ?ConnectorInterface $connector
* @param ?ProtocolFactory $protocol (internal, should not usually be passed)
*/
public function __construct($loop = null, $connector = null, $protocol = null)
{
if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
throw new \InvalidArgumentException('Argument #1 ($loop) expected null|React\EventLoop\LoopInterface');
}
if ($connector !== null && !$connector instanceof ConnectorInterface) { // manual type check to support legacy PHP < 7.1
throw new \InvalidArgumentException('Argument #2 ($connector) expected null|React\Socket\ConnectorInterface');
}
if ($protocol !== null && !$protocol instanceof ProtocolFactory) { // manual type check to support legacy PHP < 7.1
throw new \InvalidArgumentException('Argument #3 ($protocol) expected null|Clue\Redis\Protocol\Factory');
}
$this->loop = $loop ?: Loop::get();
$this->connector = $connector ?: new Connector(array(), $this->loop);
$this->protocol = $protocol ?: new ProtocolFactory();
}
/**
* Create Redis client connected to address of given redis instance
*
* @param string $uri Redis server URI to connect to
* @return \React\Promise\PromiseInterface<Client,\Exception> Promise that will
* be fulfilled with `Client` on success or rejects with `\Exception` on error.
*/
public function createClient($uri)
{
// support `redis+unix://` scheme for Unix domain socket (UDS) paths
if (preg_match('/^(redis\+unix:\/\/(?:[^:]*:[^@]*@)?)(.+?)?$/', $uri, $match)) {
$parts = parse_url($match[1] . 'localhost/' . $match[2]);
} else {
if (strpos($uri, '://') === false) {
$uri = 'redis://' . $uri;
}
$parts = parse_url($uri);
}
$uri = preg_replace(array('/(:)[^:\/]*(@)/', '/([?&]password=).*?($|&)/'), '$1***$2', $uri);
if ($parts === false || !isset($parts['scheme'], $parts['host']) || !in_array($parts['scheme'], array('redis', 'rediss', 'redis+unix'))) {
return \React\Promise\reject(new \InvalidArgumentException(
'Invalid Redis URI given (EINVAL)',
defined('SOCKET_EINVAL') ? SOCKET_EINVAL : 22
));
}
$args = array();
parse_str(isset($parts['query']) ? $parts['query'] : '', $args);
$authority = $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 6379);
if ($parts['scheme'] === 'rediss') {
$authority = 'tls://' . $authority;
} elseif ($parts['scheme'] === 'redis+unix') {
$authority = 'unix://' . substr($parts['path'], 1);
unset($parts['path']);
}
$connecting = $this->connector->connect($authority);
$deferred = new Deferred(function ($_, $reject) use ($connecting, $uri) {
// connection cancelled, start with rejecting attempt, then clean up
$reject(new \RuntimeException(
'Connection to ' . $uri . ' cancelled (ECONNABORTED)',
defined('SOCKET_ECONNABORTED') ? SOCKET_ECONNABORTED : 103
));
// either close successful connection or cancel pending connection attempt
$connecting->then(function (ConnectionInterface $connection) {
$connection->close();
}, function () {
// ignore to avoid reporting unhandled rejection
});
$connecting->cancel();
});
$protocol = $this->protocol;
$promise = $connecting->then(function (ConnectionInterface $stream) use ($protocol) {
return new StreamingClient($stream, $protocol->createResponseParser(), $protocol->createSerializer());
}, function (\Exception $e) use ($uri) {
throw new \RuntimeException(
'Connection to ' . $uri . ' failed: ' . $e->getMessage(),
$e->getCode(),
$e
);
});
// use `?password=secret` query or `user:secret@host` password form URL
$pass = isset($args['password']) ? $args['password'] : (isset($parts['pass']) ? rawurldecode($parts['pass']) : null);
if (isset($args['password']) || isset($parts['pass'])) {
$pass = isset($args['password']) ? $args['password'] : rawurldecode($parts['pass']);
$promise = $promise->then(function (StreamingClient $redis) use ($pass, $uri) {
return $redis->auth($pass)->then(
function () use ($redis) {
return $redis;
},
function (\Exception $e) use ($redis, $uri) {
$redis->close();
$const = '';
$errno = $e->getCode();
if ($errno === 0) {
$const = ' (EACCES)';
$errno = $e->getCode() ?: (defined('SOCKET_EACCES') ? SOCKET_EACCES : 13);
}
throw new \RuntimeException(
'Connection to ' . $uri . ' failed during AUTH command: ' . $e->getMessage() . $const,
$errno,
$e
);
}
);
});
}
// use `?db=1` query or `/1` path (skip first slash)
if (isset($args['db']) || (isset($parts['path']) && $parts['path'] !== '/')) {
$db = isset($args['db']) ? $args['db'] : substr($parts['path'], 1);
$promise = $promise->then(function (StreamingClient $redis) use ($db, $uri) {
return $redis->select($db)->then(
function () use ($redis) {
return $redis;
},
function (\Exception $e) use ($redis, $uri) {
$redis->close();
$const = '';
$errno = $e->getCode();
if ($errno === 0 && strpos($e->getMessage(), 'NOAUTH ') === 0) {
$const = ' (EACCES)';
$errno = defined('SOCKET_EACCES') ? SOCKET_EACCES : 13;
} elseif ($errno === 0) {
$const = ' (ENOENT)';
$errno = defined('SOCKET_ENOENT') ? SOCKET_ENOENT : 2;
}
throw new \RuntimeException(
'Connection to ' . $uri . ' failed during SELECT command: ' . $e->getMessage() . $const,
$errno,
$e
);
}
);
});
}
$promise->then(array($deferred, 'resolve'), array($deferred, 'reject'));
// use timeout from explicit ?timeout=x parameter or default to PHP's default_socket_timeout (60)
$timeout = isset($args['timeout']) ? (float) $args['timeout'] : (int) ini_get("default_socket_timeout");
if ($timeout < 0) {
return $deferred->promise();
}
return \React\Promise\Timer\timeout($deferred->promise(), $timeout, $this->loop)->then(null, function ($e) use ($uri) {
if ($e instanceof TimeoutException) {
throw new \RuntimeException(
'Connection to ' . $uri . ' timed out after ' . $e->getTimeout() . ' seconds (ETIMEDOUT)',
defined('SOCKET_ETIMEDOUT') ? SOCKET_ETIMEDOUT : 110
);
}
throw $e;
});
}
/**
* Create Redis client connected to address of given redis instance
*
* @param string $target
* @return Client
*/
public function createLazyClient($target)
{
return new LazyClient($target, $this, $this->loop);
}
}