-
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathFactory.php
More file actions
228 lines (197 loc) · 9.06 KB
/
Factory.php
File metadata and controls
228 lines (197 loc) · 9.06 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<?php
namespace Clue\React\Redis\Io;
use Clue\Redis\Protocol\Factory as ProtocolFactory;
use React\EventLoop\Loop;
use React\Promise\Deferred;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
use React\Socket\ConnectionInterface;
use React\Socket\Connector;
use React\Socket\ConnectorInterface;
use function React\Promise\reject;
/**
* @internal
*/
class Factory
{
/** @var ConnectorInterface */
private $connector;
/** @var ProtocolFactory */
private $protocol;
/**
* @param ?ConnectorInterface $connector
* @param ?ProtocolFactory $protocol
*/
public function __construct(?ConnectorInterface $connector = null, ?ProtocolFactory $protocol = null)
{
$this->connector = $connector ?: new Connector();
$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 PromiseInterface<StreamingClient> Promise that will
* be fulfilled with `StreamingClient` on success or rejects with `\Exception` on error.
*/
public function createClient(string $uri): PromiseInterface
{
// 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 {
$parts = parse_url($uri);
}
$uri = preg_replace(['/(:)[^:\/]*(@)/', '/([?&]password=).*?($|&)/'], '$1***$2', $uri);
assert(is_array($parts) && isset($parts['scheme'], $parts['host']));
assert(in_array($parts['scheme'], ['redis', 'rediss', 'redis+unix']));
$args = [];
parse_str($parts['query'] ?? '', $args);
$authority = $parts['host'] . ':' . ($parts['port'] ?? 6379);
if ($parts['scheme'] === 'rediss') {
$authority = 'tls://' . $authority;
} elseif ($parts['scheme'] === 'redis+unix') {
assert(isset($parts['path']));
$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();
});
$promise = $connecting->then(function (ConnectionInterface $stream) {
return new StreamingClient($stream, $this->protocol->createResponseParser(), $this->protocol->createSerializer());
}, function (\Throwable $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
if (isset($args['password']) || isset($parts['pass'])) {
$pass = $args['password'] ?? rawurldecode($parts['pass']); // @phpstan-ignore-line
$user = null;
if (isset($args['username']) || isset($parts['user'])) {
$user = $args['username'] ?? rawurldecode($parts['user']); // @phpstan-ignore-line
}
\assert(\is_string($pass));
\assert($user === null || \is_string($user));
$promise = $promise->then(function (StreamingClient $redis) use ($user, $pass, $uri) {
if ($user !== null) {
$authPromise = $redis->callAsync('auth', $user, $pass);
} else {
$authPromise = $redis->callAsync('auth', $pass);
}
return $authPromise->then(
function () use ($redis) {
return $redis;
},
function (\Throwable $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 = $args['db'] ?? substr($parts['path'], 1); // @phpstan-ignore-line
\assert(\is_string($db));
$promise = $promise->then(function (StreamingClient $redis) use ($db, $uri) {
return $redis->callAsync('select', $db)->then(
function () use ($redis) {
return $redis;
},
function (\Throwable $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([$deferred, 'resolve'], [$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();
}
$promise = $deferred->promise();
/** @var Promise<StreamingClient> */
$ret = new Promise(function (callable $resolve, callable $reject) use ($timeout, $promise, $uri): void {
/** @var ?\React\EventLoop\TimerInterface */
$timer = null;
$promise = $promise->then(function (StreamingClient $v) use (&$timer, $resolve): void {
if ($timer) {
Loop::cancelTimer($timer);
}
$timer = false;
$resolve($v);
}, function (\Throwable $e) use (&$timer, $reject): void {
if ($timer) {
Loop::cancelTimer($timer);
}
$timer = false;
$reject($e);
});
// promise already settled => no need to start timer
if ($timer === false) {
return;
}
// start timeout timer which will cancel the pending promise
$timer = Loop::addTimer($timeout, function () use ($timeout, &$promise, $reject, $uri): void {
$reject(new \RuntimeException(
'Connection to ' . $uri . ' timed out after ' . $timeout . ' seconds (ETIMEDOUT)',
\defined('SOCKET_ETIMEDOUT') ? \SOCKET_ETIMEDOUT : 110
));
// Cancel pending connection to clean up any underlying resources and references.
// Avoid garbage references in call stack by passing pending promise by reference.
\assert($promise instanceof PromiseInterface);
$promise->cancel();
$promise = null;
});
}, function () use (&$promise): void {
// Cancelling this promise will cancel the pending connection, thus triggering the rejection logic above.
// Avoid garbage references in call stack by passing pending promise by reference.
\assert($promise instanceof PromiseInterface);
$promise->cancel();
$promise = null;
});
// variable assignment needed for legacy PHPStan on PHP 7.1 only
return $ret;
}
}