-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
EventSource.php
286 lines (255 loc) · 9.41 KB
/
EventSource.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
<?php
namespace Clue\React\EventSource;
use Evenement\EventEmitter;
use Psr\Http\Message\ResponseInterface;
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Http\Browser;
use React\Stream\ReadableStreamInterface;
/**
* The `EventSource` class is responsible for communication with the remote Server-Sent Events (SSE) endpoint.
*
* The `EventSource` object works very similar to the one found in common
* web browsers. Unless otherwise noted, it follows the same semantics as defined
* under https://html.spec.whatwg.org/multipage/server-sent-events.html
*
* Its constructor simply requires the URL to the remote Server-Sent Events (SSE) endpoint:
*
* ```php
* $es = new Clue\React\EventSource\EventSource('https://example.com/stream.php');
* ```
*
* This class takes an optional `LoopInterface|null $loop` parameter that can be used to
* pass the event loop instance to use for this object. You can use a `null` value
* here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
* This value SHOULD NOT be given unless you're sure you want to explicitly use a
* given event loop instance.
*
* If you need custom connector settings (DNS resolution, TLS parameters, timeouts,
* proxy servers etc.), you can explicitly pass a custom instance of the
* [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface)
* to the [`Browser`](https://github.com/reactphp/http#browser) instance
* and pass it as an additional argument to the `EventSource` like this:
*
* ```php
* $connector = new React\Socket\Connector(null, [
* 'dns' => '127.0.0.1',
* 'tcp' => [
* 'bindto' => '192.168.10.1:0'
* ],
* 'tls' => [
* 'verify_peer' => false,
* 'verify_peer_name' => false
* ]
* ]);
* $browser = new React\Http\Browser(null, $connector);
*
* $es = new Clue\React\EventSource\EventSource('https://example.com/stream.php', null, $browser);
* ```
*/
class EventSource extends EventEmitter
{
// ready state
const CONNECTING = 0;
const OPEN = 1;
const CLOSED = 2;
/**
* @var int (read-only)
* @see self::CONNECTING
* @see self::OPEN
* @see self::CLOSED
* @psalm-readonly-allow-private-mutation
*/
public $readyState = self::CLOSED;
/**
* @var string (read-only) URL
* @readonly
*/
public $url;
/**
* @var string last event ID received
*/
private $lastEventId = '';
/**
* @var LoopInterface
* @readonly
*/
private $loop;
/**
* @var Browser
* @readonly
*/
private $browser;
/**
* @var ?\React\Promise\PromiseInterface
*/
private $request;
/**
* @var ?\React\EventLoop\TimerInterface
*/
private $timer;
/**
* @var float
*/
private $reconnectTime = 3.0;
/**
* The `EventSource` class is responsible for communication with the remote Server-Sent Events (SSE) endpoint.
*
* The `EventSource` object works very similar to the one found in common
* web browsers. Unless otherwise noted, it follows the same semantics as defined
* under https://html.spec.whatwg.org/multipage/server-sent-events.html
*
* Its constructor simply requires the URL to the remote Server-Sent Events (SSE) endpoint:
*
* ```php
* $es = new Clue\React\EventSource\EventSource('https://example.com/stream.php');
* ```
*
* If you need custom connector settings (DNS resolution, TLS parameters, timeouts,
* proxy servers etc.), you can explicitly pass a custom instance of the
* [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface)
* to the [`Browser`](https://github.com/reactphp/http#browser) instance
* and pass it as an additional argument to the `EventSource` like this:
*
* ```php
* $connector = new React\Socket\Connector([
* 'dns' => '127.0.0.1',
* 'tcp' => [
* 'bindto' => '192.168.10.1:0'
* ],
* 'tls' => [
* 'verify_peer' => false,
* 'verify_peer_name' => false
* ]
* ]);
* $browser = new React\Http\Browser($connector);
*
* $es = new Clue\React\EventSource\EventSource('https://example.com/stream.php', $browser);
* ```
*
* This class takes an optional `LoopInterface|null $loop` parameter that can be used to
* pass the event loop instance to use for this object. You can use a `null` value
* here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
* This value SHOULD NOT be given unless you're sure you want to explicitly use a
* given event loop instance.
*
* @param string $url
* @param ?Browser $browser
* @param ?LoopInterface $loop
* @throws \InvalidArgumentException for invalid URL
*/
public function __construct($url, Browser $browser = null, LoopInterface $loop = null)
{
$parts = parse_url($url);
if (!isset($parts['scheme'], $parts['host']) || !in_array($parts['scheme'], array('http', 'https'))) {
throw new \InvalidArgumentException();
}
$this->loop = $loop ?: Loop::get();
if ($browser === null) {
$browser = new Browser(null, $this->loop);
}
$this->browser = $browser->withRejectErrorResponse(false);
$this->url = $url;
$this->readyState = self::CONNECTING;
$this->request();
}
private function request()
{
$headers = array(
'Accept' => 'text/event-stream',
'Cache-Control' => 'no-cache'
);
if ($this->lastEventId !== '') {
$headers['Last-Event-ID'] = $this->lastEventId;
}
$this->request = $this->browser->requestStreaming(
'GET',
$this->url,
$headers
);
$this->request->then(function (ResponseInterface $response) {
if ($response->getStatusCode() !== 200) {
$this->readyState = self::CLOSED;
$this->emit('error', array(new \UnexpectedValueException('Unexpected status code')));
$this->close();
return;
}
// match `Content-Type: text/event-stream` (case insensitve and ignore additional parameters)
if (!preg_match('/^text\/event-stream(?:$|;)/i', $response->getHeaderLine('Content-Type'))) {
$this->readyState = self::CLOSED;
$this->emit('error', array(new \UnexpectedValueException('Unexpected Content-Type')));
$this->close();
return;
}
$stream = $response->getBody();
assert($stream instanceof ReadableStreamInterface);
$buffer = '';
$stream->on('data', function ($chunk) use (&$buffer, $stream) {
$messageEvents = preg_split(
'/(?:\r\n|\r(?!\n)|\n){2}/S',
$buffer . $chunk
);
$buffer = array_pop($messageEvents);
foreach ($messageEvents as $data) {
$message = MessageEvent::parse($data, $this->lastEventId, $this->reconnectTime);
$this->lastEventId = $message->lastEventId;
if ($message->data !== '') {
$this->emit($message->type, array($message));
if ($this->readyState === self::CLOSED) {
break;
}
}
}
});
$stream->on('close', function () use (&$buffer) {
$buffer = '';
$this->request = null;
if ($this->readyState === self::OPEN) {
$this->readyState = self::CONNECTING;
$this->emit('error', [new \RuntimeException('Stream closed, reconnecting in ' . $this->reconnectTime . ' seconds')]);
if ($this->readyState === self::CLOSED) {
return;
}
$this->timer = $this->loop->addTimer($this->reconnectTime, function () {
$this->timer = null;
$this->request();
});
}
});
$this->readyState = self::OPEN;
$this->emit('open');
})->then(null, function ($e) {
$this->request = null;
if ($this->readyState === self::CLOSED) {
return;
}
$this->emit('error', [$e]);
if ($this->readyState === self::CLOSED) {
return;
}
$this->timer = $this->loop->addTimer($this->reconnectTime, function () {
$this->timer = null;
$this->request();
});
});
}
public function close()
{
$this->readyState = self::CLOSED;
if ($this->request !== null) {
$request = $this->request;
$this->request = null;
$request->then(function (ResponseInterface $response) {
$response->getBody()->close();
}, function () {
// ignore to avoid reporting unhandled rejection
});
$request->cancel();
}
if ($this->timer !== null) {
$this->loop->cancelTimer($this->timer);
$this->timer = null;
}
$this->removeAllListeners();
}
}