Repository navigation
Expand file tree
/
Copy pathClient.php
More file actions
376 lines (339 loc) · 13.2 KB
/
Copy pathClient.php
File metadata and controls
376 lines (339 loc) · 13.2 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
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
<?php
namespace ccxt\pro;
use Ratchet\Client\Connector;
use React;
use React\EventLoop\Loop;
use React\Promise\Timer;
use React\Promise\Timer\TimeoutException;
use ccxt\RequestTimeout;
use ccxt\NetworkError;
use ccxt\Exchange;
use Ratchet\RFC6455\Messaging\Frame;
use Ratchet\RFC6455\Messaging\Message;
use Exception;
use RuntimeException;
class NoOriginHeaderConnector extends Connector {
public function generateRequest($url, array $subProtocols, array $headers) {
return parent::generateRequest($url, $subProtocols, $headers)->withoutHeader('Origin');
}
}
class Client {
public $url;
public $futures = array();
public $subscriptions = array();
public $rejections = array();
public $message_queue = array();
public $useMessageQueue = false;
public $options = array();
public $on_message_callback;
public $on_error_callback;
public $on_close_callback;
public $on_connected_callback;
public $error;
public $connectionStarted;
public $connectionEstablished;
// public $connection_timer; // ?
public $connectionTimeout = 30000;
public $pingInterval;
public $keepAlive = 30000;
public $maxPingPongMisses = 2.0;
public $lastPong = null;
public $ping = null;
public $verbose = false; // verbose output
public $gunzip = false;
public $inflate = false;
public $throttler = null;
public $throttle = null;
public $connection = null;
public $connected; // connection-related Future
public $isConnected = false;
public $noOriginHeader = true;
public $log = null;
public $heartbeat = null;
public $cost = 1;
// ratchet/pawl/reactphp stuff
public $connector = null;
// ------------------------------------------------------------------------
public function future($message_hash) {
if (!array_key_exists($message_hash, $this->futures)) {
$this->futures[$message_hash] = new Future();
}
$future = $this->futures[$message_hash];
if (array_key_exists($message_hash, $this->rejections)) {
$future->reject($this->rejections[$message_hash]);
unset($this->rejections[$message_hash]);
unset($this->message_queue[$message_hash]);
return $future;
}
if ($this->useMessageQueue && array_key_exists($message_hash, $this->message_queue)) {
$queue = $this->message_queue[$message_hash];
if (count($queue) > 0) {
$future->resolve(array_shift($queue));
unset($this->futures[$message_hash]);
}
}
return $future;
}
public function resolve($result, $message_hash) {
if ($this->verbose && ($message_hash === null)) {
$this->log(date('c'), 'resolve received null messageHash');
}
if ($this->useMessageQueue) {
if (!array_key_exists($message_hash, $this->message_queue)) {
$this->message_queue[$message_hash] = array();
}
$queue = $this->message_queue[$message_hash];
array_push($queue, $result);
while (count($queue) > 10) {
array_shift($queue);
}
if (array_key_exists($message_hash, $this->futures)) {
$promise = $this->futures[$message_hash];
$promise->resolve(array_shift($queue));
unset($this->futures[$message_hash]);
}
} else {
if (array_key_exists($message_hash, $this->futures)) {
$promise = $this->futures[$message_hash];
$promise->resolve($result);
unset($this->futures[$message_hash]);
}
}
return $result;
}
public function reject($result, $message_hash = null) {
if ($message_hash) {
if (array_key_exists($message_hash, $this->futures)) {
$promise = $this->futures[$message_hash];
unset($this->futures[$message_hash]);
$promise->reject($result);
} else {
$this->rejections[$message_hash] = $result;
}
} else {
$message_hashes = array_keys($this->futures);
foreach ($message_hashes as $message_hash) {
$this->reject($result, $message_hash);
}
}
return $result;
}
public function __construct(
$url,
callable $on_message_callback,
callable $on_error_callback,
callable $on_close_callback,
callable $on_connected_callback,
$config
) {
$this->url = $url;
$this->futures = array();
$this->subscriptions = array();
$this->rejections = array();
$this->on_message_callback = $on_message_callback;
$this->on_error_callback = $on_error_callback;
$this->on_close_callback = $on_close_callback;
$this->on_connected_callback = $on_connected_callback;
foreach ($config as $key => $value) {
$this->{$key} =
(property_exists($this, $key) && is_array($this->{$key}) && is_array($value)) ?
array_replace_recursive($this->{$key}, $value) :
$value;
}
$this->connected = new Future();
}
public function set_ws_connector($proxy_address = null, $proxy_conenctor = null) {
// set default connector
if (!$proxy_address) {
$react_default_connector = new React\Socket\Connector();
if ($this->noOriginHeader) {
$this->connector = new NoOriginHeaderConnector(Loop::get(), $react_default_connector);
} else {
$this->connector = new Connector(Loop::get(), $react_default_connector);
}
} else {
if ($this->noOriginHeader) {
$this->connector = new NoOriginHeaderConnector(Loop::get(), $proxy_conenctor);
} else {
$this->connector = new Connector(Loop::get(), $proxy_conenctor);
}
}
}
public function create_connection() {
return React\Async\async(function () {
$timeout = $this->connectionTimeout / 1000;
if ($this->verbose) {
echo date('c'), ' connecting to ', $this->url, "\n";
}
$headers = property_exists($this, 'options') && array_key_exists('headers', $this->options) ? $this->options['headers'] : [];
$promise = call_user_func($this->connector, $this->url, [], $headers);
Timer\timeout($promise, $timeout, Loop::get())->then(
function($connection) {
if ($this->verbose) {
echo date('c'), " connected\n";
}
$this->connection = $connection;
$this->connection->on('message', array($this, 'on_message'));
$this->connection->on('close', array($this, 'on_close'));
$this->connection->on('error', array($this, 'on_error'));
$this->connection->on('pong', array($this, 'on_pong'));
$this->isConnected = true;
$this->connectionEstablished = $this->milliseconds();
$this->connected->resolve($this->url);
$this->set_ping_interval();
$on_connected_callback = $this->on_connected_callback;
$on_connected_callback($this);
},
function(\Exception $error) {
// echo date('c'), ' connection failed ', get_class($error), ' ', $error->getMessage(), "\n";
// the ordering of these exceptions is important
// since one inherits another
if ($error instanceof TimeoutException) {
$error = new RequestTimeout($error->getMessage());
} else if ($error instanceof RuntimeException) {
// connection failed or rejected
$error = new NetworkError($error->getMessage());
}
$this->on_error($error);
}
);
})();
}
public function connect($backoff_delay = 0) {
if (!$this->connection) {
$this->connection = true;
if ($backoff_delay) {
if ($this->verbose) {
echo date('c'), ' backoff delay ', $backoff_delay, " seconds\n";
}
$callback = array($this, 'create_connection');
Loop::addTimer(((float)$backoff_delay) / 1000, $callback);
} else {
if ($this->verbose) {
echo date('c'), ' no backoff delay', "\n";
}
$this->create_connection();
}
}
return $this->connected;
}
public function send($data) {
return React\Async\async(function () use ($data) {
$message = is_string($data) ? $data : Exchange::json($data);
if ($this->verbose) {
echo date('c'), ' sending ', $message, "\n";
}
return $this->connection->send($message);
})();
}
public function close() {
$this->connection->close();
}
public function on_pong($message) {
// echo date('c'), ' on_pong ', (string) $message, "\n";
$this->lastPong = $this->milliseconds();
}
public function on_error($error) {
if ($this->verbose) {
echo date('c'), ' on_error ', get_class($error), ' ', $error->getMessage(), "\n";
}
$this->error = $error;
$on_error_callback = $this->on_error_callback;
$on_error_callback($this, $error);
$this->reset($error);
}
public function on_close($message) {
if ($this->verbose) {
echo date('c'), ' on_close ', (string) $message, "\n";
}
$on_close_callback = $this->on_close_callback;
$on_close_callback($this, $message);
if (!$this->error) {
// todo: exception types for server-side disconnects
$this->reset(new NetworkError($message));
}
if ($this->error) {
$this->reset($this->error);
}
}
public function on_message(Message $message) {
if (preg_match('~[^\x20-\x7E\t\r\n]~', $message) > 0) { // only decompress if the message is a binary
if ($this->gunzip) {
$message = \ccxt\pro\gunzip($message);
} else if ($this->inflate) {
$message = \ccxt\pro\inflate($message);
}
}
try {
$message = (string) $message;
if ($this->verbose) {
echo date('c'), ' on_message ', $message, "\n";
}
$message = Exchange::is_json_encoded_object($message) ? json_decode($message, true) : $message;
} catch (Exception $e) {
if ($this->verbose) {
echo date('c'), ' on_message json_decode ', $e->getMessage(), "\n";
}
// reset with a json encoding error?
}
try {
$on_message_callback = $this->on_message_callback;
$on_message_callback($this, $message);
} catch (Exception $error) {
$this->reject($error);
}
}
public function reset($error) {
$this->clear_ping_interval();
$this->message_queue = array();
$this->reject($error);
}
public function set_ping_interval() {
if ($this->keepAlive) {
$delay = ($this->keepAlive / 1000);
$this->pingInterval = Loop::addPeriodicTimer($delay, array($this, 'on_ping_interval'));
}
}
public function clear_ping_interval() {
if ($this->pingInterval) {
Loop::cancelTimer($this->pingInterval);
}
}
public function milliseconds() {
list($msec, $sec) = explode(' ', microtime());
return (int)($sec . substr($msec, 2, 3));
}
public function on_ping_interval() {
if ($this->keepAlive && $this->isConnected) {
$now = $this->milliseconds();
$this->lastPong = isset ($this->lastPong) ? $this->lastPong : $now;
if (($this->lastPong + $this->keepAlive * $this->maxPingPongMisses) < $now) {
$this->on_error(new RequestTimeout('Connection to ' . $this->url . ' timed out due to a ping-pong keepalive missing on time'));
} else {
if ($this->ping) {
try {
$this->send(call_user_func($this->ping, $this));
} catch (Exception $e) {
$this->on_error($e);
}
} else {
try {
$this->connection->send(new Frame('', true, Frame::OP_PING));
} catch (Exception $e) {
$this->on_error($e);
}
}
}
}
}
public function log() {
$args = func_get_args();
if (is_array($args)) {
$array = array();
foreach ($args as $arg) {
$array[] = is_string($arg) ? $arg : json_encode($arg, JSON_PRETTY_PRINT);
}
echo implode(' ', $array), "\n";
}
}
};