- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConsumer.php
More file actions
240 lines (199 loc) · 7.72 KB
/
Consumer.php
File metadata and controls
240 lines (199 loc) · 7.72 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
<?php
declare(strict_types=1);
/**
* This file is part of friendsofhyperf/components.
*
* @link https://github.com/friendsofhyperf/components
* @document https://github.com/friendsofhyperf/components/blob/main/README.md
* @contact huangdijia@gmail.com
*/
namespace FriendsOfHyperf\Trigger;
use FriendsOfHyperf\Trigger\Monitor\HealthMonitor;
use FriendsOfHyperf\Trigger\Mutex\ServerMutexInterface;
use FriendsOfHyperf\Trigger\Snapshot\BinLogCurrentSnapshotInterface;
use Hyperf\Coordinator\Constants;
use Hyperf\Coordinator\CoordinatorManager;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Stringable\Str;
use MySQLReplication\Config\ConfigBuilder;
use MySQLReplication\MySQLReplicationFactory;
use Psr\Log\LoggerInterface;
use Throwable;
use function Hyperf\Support\make;
use function Hyperf\Tappable\tap;
class Consumer
{
public Config $config;
public string $name;
public string $identifier;
public ?HealthMonitor $healthMonitor = null;
public ?ServerMutexInterface $serverMutex = null;
public BinLogCurrentSnapshotInterface $binLogCurrentSnapshot;
private bool $stopped = false;
public function __construct(
protected SubscriberManager $subscriberManager,
protected TriggerManager $triggerManager,
public string $connection = 'default',
array $options = [],
public ?LoggerInterface $logger = null
) {
$this->name = $options['name'] ?? sprintf('trigger.%s', $this->connection);
$this->identifier = $options['identifier'] ?? sprintf('trigger.%s', $this->connection);
$this->config = new Config($options);
$this->binLogCurrentSnapshot = make(BinLogCurrentSnapshotInterface::class, ['consumer' => $this]);
if ($this->config->get('health_monitor.enable', true)) {
$this->healthMonitor = make(HealthMonitor::class, ['consumer' => $this]);
}
if ($this->config->get('server_mutex.enable', true)) {
$this->serverMutex = make(ServerMutexInterface::class, [
'connection' => $this->connection,
'options' => (array) $this->config->get('server_mutex', []),
'owner' => Util::getInternalIp(),
'logger' => $this->logger,
]);
}
}
public function start(): void
{
$context = ['connection' => $this->connection];
$callback = function () use ($context) {
// Reset stopped status
$this->stopped = false;
// Health monitor start
$this->healthMonitor?->process();
$replication = $this->makeReplication();
// Replication start
CoordinatorManager::until($this->identifier)->resume();
$this->logger?->debug('[{connection}] Consumer started.', $context);
// Worker exit
Coroutine::create(function () use ($context) {
CoordinatorManager::until(Constants::WORKER_EXIT)->yield();
$this->stop();
$this->logger?->warning('[{connection}] Consumer exit.', $context);
});
while (1) {
if ($this->isStopped()) {
$this->logger?->warning('[{connection}] Consumer stopped.', $context);
break;
}
try {
$replication->consume();
} catch (Throwable $e) {
$this->logger?->warning('[{connection}] Error occurred, will retry later.', $context + ['message' => $e->getMessage()]);
$this->logger?->error((string) $e);
$this->stop();
}
}
};
if ($this->serverMutex) {
$this->serverMutex->attempt($callback);
} else {
$callback();
}
}
/**
* @deprecated since v3.1, use `$this->binLogCurrentSnapshot` instead, will be removed in v3.2.
*/
public function getBinLogCurrentSnapshot(): BinLogCurrentSnapshotInterface
{
return $this->binLogCurrentSnapshot;
}
/**
* @deprecated since v3.1, use `$this->healthMonitor` instead, will be removed in v3.2.
*/
public function getHealthMonitor(): ?HealthMonitor
{
return $this->healthMonitor;
}
/**
* @deprecated since v3.1, use `$this->name` instead, will be removed in v3.2.
*/
public function getName(): string
{
return $this->name;
}
/**
* @deprecated since v3.1, use `$this->config->get($key, $default)` instead, will be removed in v3.2.
*/
public function getOption(?string $key = null, mixed $default = null): mixed
{
if (is_null($key)) {
return (fn () => $this->configs ?? [])->call($this->config);
}
return $this->config->get($key, $default);
}
/**
* @deprecated since v3.1, use `$this->connection` instead, will be removed in v3.2.
*/
public function getConnection(): string
{
return $this->connection;
}
/**
* @deprecated since v3.1, use `$this->identifier` instead, will be removed in v3.2.
*/
public function getIdentifier(): string
{
return $this->identifier;
}
public function stop(): void
{
$this->stopped = true;
$this->serverMutex?->release();
}
public function isStopped(): bool
{
return $this->stopped;
}
protected function makeReplication(): MySQLReplicationFactory
{
$connection = $this->connection;
// Get databases of replication
$databasesOnly = array_merge(
$this->config->get('databases_only', []),
$this->triggerManager->getDatabases($connection)
);
// Get tables of replication
$tablesOnly = array_merge(
$this->config->get('tables_only', []),
$this->triggerManager->getTables($connection)
);
$configBuilder = (new ConfigBuilder())
->withUser($this->config->get('user', 'root'))
->withHost($this->config->get('host', '127.0.0.1'))
->withPassword($this->config->get('password', 'root'))
->withPort((int) $this->config->get('port', 3306))
->withSlaveId(random_int(10000, 9999999))
->withHeartbeatPeriod((float) $this->config->get('heartbeat_period', 3))
->withDatabasesOnly($databasesOnly)
->withTablesOnly($tablesOnly);
if (method_exists($configBuilder, 'withSlaveUuid')) { // php-mysql-replication >= 8.0
$configBuilder->withSlaveUuid(Str::uuid()->toString());
}
if ($binLogCurrent = $this->binLogCurrentSnapshot->get()) {
$configBuilder->withBinLogFileName($binLogCurrent->getBinFileName())
->withBinLogPosition($binLogCurrent->getBinLogPosition());
$this->logger?->debug(
'[{connection}] Continue with position, binLogCurrent: {binlog_current}',
compact('connection') + ['binlog_current' => json_encode($binLogCurrent->jsonSerialize())]
);
}
$eventDispatcher = make(EventDispatcher::class);
return tap(
make(MySQLReplicationFactory::class, [
'config' => $configBuilder->build(),
'eventDispatcher' => $eventDispatcher,
'logger' => $this->logger,
]),
function (MySQLReplicationFactory $factory) use ($connection) {
$subscribers = $this->subscriberManager->get($connection);
foreach ($subscribers as $subscriber) {
$factory->registerSubscriber(make($subscriber, [
'consumer' => $this,
'logger' => $this->logger,
]));
}
}
);
}
}