-
Notifications
You must be signed in to change notification settings - Fork 59
/
StreamConnection.php
435 lines (360 loc) · 11.5 KB
/
StreamConnection.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
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
<?php
/*
* This file is part of the Predis\Async package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Async\Connection;
use InvalidArgumentException;
use SplQueue;
use Predis\ClientException;
use Predis\ResponseError;
use Predis\ResponseQueued;
use Predis\Command\CommandInterface;
use Predis\Connection\ConnectionParametersInterface;
use Predis\Async\Buffer\StringBuffer;
use React\EventLoop\LoopInterface;
class StreamConnection implements ConnectionInterface
{
protected $parameters;
protected $loop;
protected $socket;
protected $reader;
protected $buffer;
protected $commands;
protected $state;
protected $timeout = null;
protected $errorCallback = null;
protected $readableCallback = null;
protected $writableCallback = null;
/**
* @param ConnectionParametersInterface $parameters
* @param LoopInterface $loop
*/
public function __construct(ConnectionParametersInterface $parameters, LoopInterface $loop)
{
$this->parameters = $parameters;
$this->loop = $loop;
$this->buffer = new StringBuffer();
$this->commands = new SplQueue();
$this->readableCallback = array($this, 'read');
$this->writableCallback = array($this, 'write');
$this->state = new State();
$this->state->setProcessCallback($this->getProcessCallback());
$this->initializeReader();
}
/**
* Disconnects from the server and destroys the underlying resource when
* PHP's garbage collector kicks in.
*/
public function __destruct()
{
phpiredis_reader_destroy($this->reader);
if ($this->isConnected()) {
$this->disconnect();
}
}
/**
* Initializes the protocol reader resource.
*/
protected function initializeReader()
{
$reader = phpiredis_reader_create();
phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
$this->reader = $reader;
}
/**
* Returns the callback used to handle commands and firing callbacks depending
* on the current state of the connection to Redis.
*
* @return mixed
*/
protected function getProcessCallback()
{
$connection = $this;
$commands = $this->commands;
$streamingWrapper = $this->getStreamingWrapperCreator();
return function ($state, $response) use ($commands, $connection, $streamingWrapper) {
list($command, $callback) = $commands->dequeue();
switch ($command->getId()) {
case 'SUBSCRIBE':
case 'PSUBSCRIBE':
$callback = $streamingWrapper($connection, $callback);
$state->setStreamingContext(State::PUBSUB, $callback);
break;
case 'MONITOR':
$callback = $streamingWrapper($connection, $callback);
$state->setStreamingContext(State::MONITOR, $callback);
break;
case 'MULTI':
$state->setState(State::MULTIEXEC);
goto process;
case 'EXEC':
case 'DISCARD':
$state->setState(State::CONNECTED);
goto process;
default:
process:
call_user_func($callback, $response, $connection, $command);
break;
}
};
}
/**
* Returns a wrapper to the user-provided callback passed to handle response chunks
* streamed down by replies to commands such as MONITOR, SUBSCRIBE and PSUBSCRIBE.
*
* @return mixed
*/
protected function getStreamingWrapperCreator()
{
return function ($connection, $callback) {
return function ($state, $response) use ($connection, $callback) {
call_user_func($callback, $response, $connection, null);
};
};
}
/**
* Creates the underlying resource used to communicate with Redis.
*
* @return mixed
*/
protected function createResource($connectCallback = null)
{
$connection = $this;
$parameters = $this->parameters;
$uri = "$parameters->scheme://".($parameters->scheme === 'unix' ? $parameters->path : "$parameters->host:$parameters->port");
$flags = STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT;
if (!$socket = @stream_socket_client($uri, $errno, $errstr, 0, $flags)) {
return $this->onError(new ConnectionException($this, trim($errstr), $errno));
}
stream_set_blocking($socket, 0);
$this->state->setState(State::CONNECTING);
$this->loop->addWriteStream($socket, function ($socket) use ($connection, $connectCallback) {
if ($connection->onConnect()) {
if (isset($connectCallback)) {
call_user_func($connectCallback, $connection);
}
$connection->write();
}
});
$this->timeout = $this->armTimeoutMonitor($this->parameters->timeout, $this->errorCallback);
return $socket;
}
/**
* Creates the underlying resource used to communicate with Redis.
*
* @param int $timeout Timeout in seconds
* @param mixed $callback Callback invoked on timeout.
*/
protected function armTimeoutMonitor($timeout, $callback)
{
$timer = $this->loop->addTimer($timeout, function ($timer) {
list($connection, $callback) = $timer->getData();
$connection->disconnect();
if (isset($callback)) {
call_user_func($callback, $connection, new ConnectionException($connection, 'Connection timed out'));
}
});
$timer->setData(array($this, $callback));
return $timer;
}
/**
* Disarm the timer used to monitor a connect() timeout is set.
*/
protected function disarmTimeoutMonitor()
{
if (isset($this->timeout)) {
$this->timeout->cancel();
$this->timeout = null;
}
}
/**
* {@inheritdoc}
*/
public function isConnected()
{
return isset($this->socket) && stream_socket_get_name($this->socket, true) !== false;
}
/**
* {@inheritdoc}
*/
public function connect($callback)
{
if (!$this->isConnected()) {
$this->socket = $this->createResource($callback);
}
}
/**
* {@inheritdoc}
*/
public function disconnect()
{
$this->disarmTimeoutMonitor();
$this->loop->removeStream($this->getResource());
$this->state->setState(State::DISCONNECTED);
$this->buffer->reset();
unset($this->socket);
}
/**
* {@inheritdoc}
*/
public function getResource()
{
if (isset($this->socket)) {
return $this->socket;
}
$this->socket = $this->createResource();
return $this->socket;
}
/**
* {@inheritdoc}
*/
public function setErrorCallback($callback)
{
if (!is_callable($callback)) {
throw new InvalidArgumentException('The specified callback must be a callable object');
}
$this->errorCallback = $callback;
}
/**
* {@inheritdoc}
*/
public function onConnect()
{
$socket = $this->getResource();
// The following one is a terrible hack but it looks like this is the only way to
// detect connection refused errors with PHP's stream sockets. Blame PHP as usual.
if (stream_socket_get_name($socket, true) === false) {
$this->disconnect();
$this->onError(new ConnectionException($this, "Connection refused"));
return false;
}
$this->state->setState(State::CONNECTED);
$this->disarmTimeoutMonitor();
$this->loop->removeWriteStream($socket);
$this->loop->addReadStream($socket, $this->readableCallback);
return true;
}
/**
* {@inheritdoc}
*/
protected function onError(\Exception $exception)
{
$this->disconnect();
if (isset($this->errorCallback)) {
call_user_func($this->errorCallback, $this, $exception);
}
}
/**
* Gets the handler used by the protocol reader to handle status replies.
*
* @return \Closure
*/
protected function getStatusHandler()
{
return function ($payload) {
switch ($payload) {
case 'OK':
return true;
case 'QUEUED':
return new ResponseQueued();
default:
return $payload;
}
};
}
/**
* Gets the handler used by the protocol reader to handle Redis errors.
*
* @param Boolean $throw_errors Specify if Redis errors throw exceptions.
* @return \Closure
*/
protected function getErrorHandler()
{
return function ($errorMessage) {
return new ResponseError($errorMessage);
};
}
/**
* {@inheritdoc}
*/
public function getParameters()
{
return $this->parameters;
}
/**
* {@inheritdoc}
*/
public function getEventLoop()
{
return $this->loop;
}
/**
* Gets an identifier for the connection.
*
* @return string
*/
protected function getIdentifier()
{
if ($this->parameters->scheme === 'unix') {
return $this->parameters->path;
}
return "{$this->parameters->host}:{$this->parameters->port}";
}
/**
* {@inheritdoc}
*/
public function write()
{
$socket = $this->getResource();
if ($this->buffer->isEmpty()) {
$this->loop->removeWriteStream($socket);
return;
}
$buffer = $this->buffer->read(4096);
if (-1 === $ret = @stream_socket_sendto($socket, $buffer)) {
return $this->onError(new ConnectionException($this, 'Error while writing bytes to the server'));
}
$this->buffer->discard(min($ret, strlen($buffer)));
}
/**
* {@inheritdoc}
*/
public function read()
{
$buffer = stream_socket_recvfrom($this->getResource(), 4096);
if ($buffer === false || $buffer === '') {
$this->onError(new ConnectionException($this, 'Error while reading bytes from the server'));
return;
}
phpiredis_reader_feed($reader = $this->reader, $buffer);
while (phpiredis_reader_get_state($reader) === PHPIREDIS_READER_STATE_COMPLETE) {
$this->state->process(phpiredis_reader_get_reply($reader));
}
}
/**
* {@inheritdoc}
*/
public function executeCommand(CommandInterface $command, $callback)
{
$cmdargs = $command->getArguments();
array_unshift($cmdargs, $command->getId());
if ($this->buffer->isEmpty()) {
$this->loop->addWriteStream($this->getResource(), $this->writableCallback);
}
$this->buffer->append(phpiredis_format_command($cmdargs));
$this->commands->enqueue(array($command, $callback));
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->getIdentifier();
}
}