-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMessageIdCodec.php
More file actions
266 lines (233 loc) · 8.55 KB
/
Copy pathMessageIdCodec.php
File metadata and controls
266 lines (233 loc) · 8.55 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
<?php
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache\Rocketmq;
/**
* MessageIdCodec - Message ID Codec
*
* The codec for the message-id.
*
* Codec here provides the following two functions:
* 1. Provide decoding function of message-id of all versions above v0.
* 2. Provide a generator of message-id of v1 version.
*
* The message-id of versions above V1 consists of 17 bytes in total. The first two bytes represent the version
* number. For V1, these two bytes are 0x0001.
*
* V1 message id example:
* ┌──┬────────────┬────┬────────┬────────┐
* │01│56F7E71C361B│21BC│024CCDBE│00000000│
* └──┴────────────┴────┴────────┴────────┘
*
* V1 version message id generation rules:
* process id(lower 2bytes)
* ▲
* mac address(lower 6bytes) │ sequence number(big endian)
* ▲ │ ▲ (4bytes)
* │ │ │
* ┌─────┴─────┐ ┌┴┐ ┌───┐ ┌─┴─┐
* 0x01+ │ 6 │ │2│ │ 4 │ │ 4 │
* └───────────┘ └─┘ └─┬─┘ └───┘
* │
* ▼
* seconds since 2021-01-01 00:00:00(UTC+0)
* (lower 4bytes)
*/
class MessageIdCodec
{
const MESSAGE_ID_LENGTH_FOR_V1_OR_LATER = 34;
const MESSAGE_ID_VERSION_V0 = '00';
const MESSAGE_ID_VERSION_V1 = '01';
private static ?self $instance = null;
private string $processFixedStringV1;
private int $secondsSinceCustomEpoch;
private int $secondsStartTimestamp;
private int $seconds;
private int $sequence;
/**
* Private constructor (singleton pattern).
*
* @throws \Exception If MAC address retrieval fails
*/
private function __construct()
{
// Generate process fixed string (MAC address + PID)
$this->processFixedStringV1 = $this->generateProcessFixedString();
// Calculate seconds since custom epoch (2021-01-01 00:00:00 UTC)
$this->secondsSinceCustomEpoch = time() - $this->customEpochMillis();
// Record startup timestamp
$this->secondsStartTimestamp = hrtime(true);
// Initialize current seconds
$this->seconds = $this->deltaSeconds();
// Initialize sequence number
$this->sequence = 0;
}
/**
* Get singleton instance
*
* @return MessageIdCodec
*/
public static function getInstance(): MessageIdCodec
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Generate the next message ID.
*
* @return MessageId
*/
public function nextMessageId(): MessageId
{
// Calculate delta seconds
$deltaSeconds = $this->deltaSeconds();
if ($this->seconds !== $deltaSeconds) {
$this->seconds = $deltaSeconds;
}
// Build buffer (4-byte seconds + 4-byte sequence number)
$buffer = pack('NN', $deltaSeconds & 0xFFFFFFFF, $this->sequence++);
// Convert to hexadecimal string
$suffix = $this->processFixedStringV1 . strtoupper(bin2hex($buffer));
return new MessageIdImpl(self::MESSAGE_ID_VERSION_V1, $suffix);
}
/**
* Decode message ID string.
*
* @param string $messageId Message ID string
* @return MessageId
*/
public function decode(string $messageId): MessageId
{
if (strlen($messageId) !== self::MESSAGE_ID_LENGTH_FOR_V1_OR_LATER) {
return new MessageIdImpl(self::MESSAGE_ID_VERSION_V0, $messageId);
}
return new MessageIdImpl(substr($messageId, 0, 2), substr($messageId, 2));
}
/**
* Generate process fixed string (MAC address + PID).
*
* @return string Hexadecimal string
* @throws \Exception If MAC address retrieval fails
*/
private function generateProcessFixedString(): string
{
// Get MAC address (take first 6 bytes)
$macAddress = $this->getMacAddress();
// Get process ID (take lower 2 bytes)
$pid = getmypid() & 0xFFFF;
// Combine: 6-byte MAC + 2-byte PID = 8 bytes
$buffer = $macAddress . pack('n', $pid);
return strtoupper(bin2hex($buffer));
}
/**
* Get MAC address.
*
* @return string 6-byte MAC address
* @throws \Exception If no suitable source of randomness is available for fallback
*/
private function getMacAddress(): string
{
// Try to read from /sys/class/net (Linux)
$macAddress = $this->readMacFromSysfs();
// Try ifconfig (macOS / Linux)
if ($macAddress === null) {
$macAddress = $this->readMacFromIfconfig();
}
// Use random value if unable to obtain
if ($macAddress === null || strlen($macAddress) < 6) {
$macAddress = random_bytes(6);
}
return substr($macAddress, 0, 6);
}
/**
* Read MAC address from /sys/class/net (Linux sysfs).
*
* @return string|null Binary MAC address string, or null if not available
*/
private function readMacFromSysfs(): ?string
{
$interfaces = @scandir('/sys/class/net/');
if ($interfaces === false) {
return null;
}
foreach ($interfaces as $iface) {
if ($iface === '.' || $iface === '..' || $iface === 'lo') {
continue;
}
$mac = @file_get_contents('/sys/class/net/' . $iface . '/address');
if ($mac !== false && strlen(trim($mac)) === 17) {
$macString = str_replace(':', '', trim($mac));
$binary = hex2bin($macString);
if ($binary !== false) {
return $binary;
}
}
}
return null;
}
/**
* Read MAC address from ifconfig command output (macOS/Linux fallback).
*
* @return string|null Binary MAC address string, or null if not available
*/
private function readMacFromIfconfig(): ?string
{
// ifconfig/grep/head are not available on Windows
if (\PHP_OS_FAMILY === 'Windows') {
return null;
}
$disabled = array_map('trim', explode(',', ini_get('disable_functions')));
if (in_array('exec', $disabled, true)) {
return null;
}
$output = [];
exec('ifconfig 2>/dev/null | grep -E "ether|HWaddr" | head -n 1', $output);
if (!empty($output)) {
$line = $output[0];
if (preg_match('/([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})/', $line, $matches)) {
$macString = str_replace([':', '-'], '', $matches[0]);
$macAddress = hex2bin($macString);
if ($macAddress !== false) {
return $macAddress;
}
}
}
return null;
}
/**
* Calculate custom epoch milliseconds (2021-01-01 00:00:00 UTC)
*
* @return int Epoch milliseconds
*/
private function customEpochMillis(): int
{
return gmmktime(0, 0, 0, 1, 1, 2021) * 1000;
}
/**
* Calculate seconds since custom epoch
*
* @return int Number of seconds
*/
private function deltaSeconds(): int
{
$nanoTime = hrtime(true);
$elapsedSeconds = intdiv($nanoTime - $this->secondsStartTimestamp, 1000000000);
return $this->secondsSinceCustomEpoch + $elapsedSeconds;
}
}