forked from clue/reactphp-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisClient.php
More file actions
272 lines (235 loc) · 7.92 KB
/
RedisClient.php
File metadata and controls
272 lines (235 loc) · 7.92 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
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
<?php
namespace Clue\React\Redis;
use Clue\React\Redis\Io\Factory;
use Clue\React\Redis\Io\StreamingClient;
use Evenement\EventEmitter;
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Promise\PromiseInterface;
use React\Socket\ConnectorInterface;
use React\Stream\Util;
use function React\Promise\reject;
/**
* Simple interface for executing redis commands
*
* @event error(Exception $error)
* @event close()
*
* @event message($channel, $message)
* @event subscribe($channel, $numberOfChannels)
* @event unsubscribe($channel, $numberOfChannels)
*
* @event pmessage($pattern, $channel, $message)
* @event psubscribe($channel, $numberOfChannels)
* @event punsubscribe($channel, $numberOfChannels)
*/
class RedisClient extends EventEmitter
{
/** @var string */
private $target;
/** @var Factory */
private $factory;
/** @var bool */
private $closed = false;
/** @var ?PromiseInterface<StreamingClient> */
private $promise = null;
/** @var LoopInterface */
private $loop;
/** @var float */
private $idlePeriod = 0.001;
/** @var ?\React\EventLoop\TimerInterface */
private $idleTimer = null;
/** @var int */
private $pending = 0;
/** @var array<string,bool> */
private $subscribed = [];
/** @var array<string,bool> */
private $psubscribed = [];
/**
* @param string $url
* @param ?ConnectorInterface $connector
* @param ?LoopInterface $loop
*/
public function __construct($url, ConnectorInterface $connector = null, LoopInterface $loop = null)
{
$args = [];
\parse_str((string) \parse_url($url, \PHP_URL_QUERY), $args);
if (isset($args['idle'])) {
$this->idlePeriod = (float)$args['idle'];
}
$this->target = $url;
$this->loop = $loop ?: Loop::get();
$this->factory = new Factory($this->loop, $connector);
}
/**
* @return PromiseInterface<StreamingClient>
*/
private function client(): PromiseInterface
{
if ($this->promise !== null) {
return $this->promise;
}
return $this->promise = $this->factory->createClient($this->target)->then(function (StreamingClient $redis) {
// connection completed => remember only until closed
$redis->on('close', function () {
$this->promise = null;
// foward unsubscribe/punsubscribe events when underlying connection closes
$n = count($this->subscribed);
foreach ($this->subscribed as $channel => $_) {
$this->emit('unsubscribe', [$channel, --$n]);
}
$n = count($this->psubscribed);
foreach ($this->psubscribed as $pattern => $_) {
$this->emit('punsubscribe', [$pattern, --$n]);
}
$this->subscribed = $this->psubscribed = [];
if ($this->idleTimer !== null) {
$this->loop->cancelTimer($this->idleTimer);
$this->idleTimer = null;
}
});
// keep track of all channels and patterns this connection is subscribed to
$redis->on('subscribe', function (string $channel) {
$this->subscribed[$channel] = true;
});
$redis->on('psubscribe', function (string $pattern) {
$this->psubscribed[$pattern] = true;
});
$redis->on('unsubscribe', function (string $channel) {
unset($this->subscribed[$channel]);
});
$redis->on('punsubscribe', function (string $pattern) {
unset($this->psubscribed[$pattern]);
});
Util::forwardEvents(
$redis,
$this,
[
'message',
'subscribe',
'unsubscribe',
'pmessage',
'psubscribe',
'punsubscribe',
]
);
return $redis;
}, function (\Throwable $e) {
assert($e instanceof \Exception);
// connection failed => discard connection attempt
$this->promise = null;
throw $e;
});
}
/**
* Invoke the given command and return a Promise that will be resolved when the request has been replied to
*
* This is a magic method that will be invoked when calling any redis
* command on this instance.
*
* @param string $name
* @param string[] $args
* @return PromiseInterface<mixed>
*/
public function __call(string $name, array $args): PromiseInterface
{
if ($this->closed) {
return reject(new \RuntimeException(
'Connection closed (ENOTCONN)',
defined('SOCKET_ENOTCONN') ? SOCKET_ENOTCONN : 107
));
}
return $this->client()->then(function (StreamingClient $redis) use ($name, $args) {
$this->awake();
assert(\is_callable([$redis, $name])); // @phpstan-ignore-next-line
return \call_user_func_array([$redis, $name], $args)->then(
function ($result) {
$this->idle();
return $result;
},
function (\Exception $error) {
$this->idle();
throw $error;
}
);
});
}
/**
* end connection once all pending requests have been replied to
*
* @return void
* @uses self::close() once all replies have been received
* @see self::close() for closing the connection immediately
*/
public function end(): void
{
if ($this->promise === null) {
$this->close();
}
if ($this->closed) {
return;
}
$this->client()->then(function (StreamingClient $redis) {
$redis->on('close', function () {
$this->close();
});
$redis->end();
});
}
/**
* close connection immediately
*
* This will emit the "close" event.
*
* @return void
* @see self::end() for closing the connection once the client is idle
*/
public function close(): void
{
if ($this->closed) {
return;
}
$this->closed = true;
// either close active connection or cancel pending connection attempt
if ($this->promise !== null) {
$this->promise->then(function (StreamingClient $redis) {
$redis->close();
}, function () {
// ignore to avoid reporting unhandled rejection
});
if ($this->promise !== null) {
assert(\method_exists($this->promise, 'cancel'));
$this->promise->cancel();
$this->promise = null;
}
}
if ($this->idleTimer !== null) {
$this->loop->cancelTimer($this->idleTimer);
$this->idleTimer = null;
}
$this->emit('close');
$this->removeAllListeners();
}
private function awake(): void
{
++$this->pending;
if ($this->idleTimer !== null) {
$this->loop->cancelTimer($this->idleTimer);
$this->idleTimer = null;
}
}
private function idle(): void
{
--$this->pending;
if ($this->pending < 1 && $this->idlePeriod >= 0 && !$this->subscribed && !$this->psubscribed && $this->promise !== null) {
$this->idleTimer = $this->loop->addTimer($this->idlePeriod, function () {
assert($this->promise instanceof PromiseInterface);
$this->promise->then(function (StreamingClient $redis) {
$redis->close();
});
$this->promise = null;
$this->idleTimer = null;
});
}
}
}