|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Class to implement CruftFlake. |
|
5
|
|
|
* |
|
6
|
|
|
* @author @bobbyjason |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Gendoria\CruftFlake\Zmq; |
|
10
|
|
|
|
|
11
|
|
|
use Gendoria\CruftFlake\ClientInterface; |
|
12
|
|
|
use Gendoria\CruftFlake\Generator\GeneratorStatus; |
|
13
|
|
|
use RuntimeException; |
|
14
|
|
|
|
|
15
|
|
|
class ZmqClient implements ClientInterface |
|
16
|
|
|
{ |
|
17
|
|
|
protected $context; |
|
18
|
|
|
protected $socket; |
|
19
|
|
|
protected $bindUri; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(\ZMQContext $context, \ZMQSocket $socket, $bindUri = 'tcp://127.0.0.1:5599') |
|
22
|
|
|
{ |
|
23
|
|
|
$this->context = $context; |
|
24
|
|
|
$this->socket = $socket; |
|
25
|
|
|
$this->bindUri = $bindUri; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* {@inheritdoc} |
|
30
|
|
|
* |
|
31
|
|
|
* @throws RuntimeException |
|
32
|
|
|
*/ |
|
33
|
|
|
public function generateId() |
|
34
|
|
|
{ |
|
35
|
|
|
$this->socket->connect($this->bindUri); |
|
36
|
|
|
$this->socket->setSockOpt(\ZMQ::SOCKOPT_LINGER, 0); |
|
37
|
|
|
$this->socket->send('GEN'); |
|
38
|
|
|
$reply = $this->socket->recv(); |
|
39
|
|
|
if (empty($reply)) { |
|
40
|
|
|
throw new RuntimeException('Server error - received empty reply.'); |
|
41
|
|
|
} |
|
42
|
|
|
$response = json_decode($reply, true); |
|
43
|
|
|
|
|
44
|
|
|
if ($response['code'] != 200) { |
|
45
|
|
|
throw new RuntimeException('Server error: '.$response['message']); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return (int) $response['message']; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* {@inheritdoc} |
|
53
|
|
|
*/ |
|
54
|
|
|
public function status() |
|
55
|
|
|
{ |
|
56
|
|
|
$this->socket->connect($this->bindUri); |
|
57
|
|
|
$this->socket->setSockOpt(\ZMQ::SOCKOPT_LINGER, 0); |
|
58
|
|
|
$this->socket->send('STATUS'); |
|
59
|
|
|
$reply = $this->socket->recv(); |
|
60
|
|
|
|
|
61
|
|
|
$response = json_decode($reply, true); |
|
62
|
|
|
|
|
63
|
|
|
return new GeneratorStatus($response['message']['machine'], |
|
64
|
|
|
$response['message']['lastTime'], $response['message']['sequence'], |
|
65
|
|
|
$response['message']['is32Bit']); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
public function __toString() |
|
69
|
|
|
{ |
|
70
|
|
|
return $this->generateId(); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Set ZMQ send timeout. |
|
75
|
|
|
* |
|
76
|
|
|
* @param int $timeout |
|
77
|
|
|
*/ |
|
78
|
|
|
public function setTimeout($timeout = 5) |
|
79
|
|
|
{ |
|
80
|
|
|
$this->socket->setSockOpt(\ZMQ::SOCKOPT_SNDTIMEO, $timeout); |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|