Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSonyflake.php
More file actions
303 lines (266 loc) · 9.41 KB
/
Copy pathSonyflake.php
File metadata and controls
303 lines (266 loc) · 9.41 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
<?php
declare(strict_types=1);
namespace Infocyph\UID;
use DateTimeImmutable;
use Exception;
use Infocyph\UID\Configuration\SonyflakeConfig;
use Infocyph\UID\Enums\ClockBackwardPolicy;
use Infocyph\UID\Enums\IdOutputType;
use Infocyph\UID\Exceptions\FileLockException;
use Infocyph\UID\Exceptions\SonyflakeException;
use Infocyph\UID\Sequence\SequenceProviderInterface;
use Infocyph\UID\Support\BaseEncoder;
use Infocyph\UID\Support\EpochGuard;
use Infocyph\UID\Support\GetSequence;
use Infocyph\UID\Support\NumericIdCodec;
use Infocyph\UID\Support\OutputFormatter;
final class Sonyflake
{
use GetSequence;
private static int $lastElapsedTime = 0;
private static int $maxMachineIdLength = 16;
private static int $maxSequenceLength = 8;
private static int $maxTimestampLength = 39;
private static ?int $startTime = null;
/**
* Decodes one of bases: 16, 32, 36, 58, 62 into Sonyflake decimal.
*
* @throws SonyflakeException
*/
public static function fromBase(string $encoded, int $base): string
{
return self::decodeNumeric(
fn(): string => NumericIdCodec::decimalFromBase($encoded, $base, 8),
null,
);
}
/**
* Converts 8-byte Sonyflake binary data to decimal string.
*
* @throws SonyflakeException
*/
public static function fromBytes(string $bytes): string
{
return self::decodeNumeric(
fn(): string => NumericIdCodec::decimalFromBytes($bytes, 8),
'Sonyflake binary data must be exactly 8 bytes',
);
}
/**
* Generates a unique identifier using the SonyFlake algorithm.
*
* @param int $machineId The machine identifier. Must be between 0 and the maximum machine ID.
* @return string The generated unique identifier.
* @throws SonyflakeException|FileLockException
*/
public static function generate(int $machineId = 0): string
{
return (string) self::generateInternal(
$machineId,
self::getStartTimeStamp(),
ClockBackwardPolicy::WAIT,
IdOutputType::STRING,
);
}
/**
* Generates Sonyflake using configuration object.
*
* @throws SonyflakeException|FileLockException
*/
public static function generateWithConfig(SonyflakeConfig $config): int|string
{
return self::generateInternal(
$config->resolveMachineId(),
$config->resolveCustomEpochMs() ?? self::getStartTimeStamp(),
$config->clockBackwardPolicy,
$config->outputType,
$config->sequenceProvider,
);
}
/**
* Checks whether a Sonyflake ID string has a valid numeric shape.
*/
public static function isValid(string $id): bool
{
return preg_match('/^\d+$/', $id) === 1 && $id !== '0';
}
/**
* Parse the given ID into components.
*
* @param string $id The ID to parse.
* @return array{time: DateTimeImmutable, sequence: int, machine_id: int}
* @throws Exception
*/
public static function parse(string $id): array
{
return self::parseWithEpoch($id, self::getStartTimeStamp());
}
/**
* Parse Sonyflake using custom epoch in milliseconds.
*
* @return array{time: DateTimeImmutable, sequence: int, machine_id: int}
* @throws Exception
*/
public static function parseWithEpoch(string $id, int $startTimestamp): array
{
$parts = self::extractParts($id, $startTimestamp);
return [
'time' => new DateTimeImmutable(
'@'
. $parts['seconds']
. '.'
. str_pad($parts['fraction'], 6, '0', STR_PAD_LEFT),
),
'sequence' => $parts['sequence'],
'machine_id' => $parts['machine_id'],
];
}
/**
* Sets the start timestamp for the SonyFlake algorithm.
*
* @param string $timeString The start time in string format.
* @throws SonyflakeException
*/
public static function setStartTimeStamp(string $timeString): void
{
try {
$resolved = EpochGuard::resolveStartTime(
$timeString,
'Invalid start time format',
'The start time cannot be in the future',
);
} catch (\InvalidArgumentException $exception) {
throw new SonyflakeException($exception->getMessage(), 0, $exception);
}
$time = $resolved['time'];
$current = $resolved['current'];
self::ensureEffectiveRuntime(floor(($current - $time) / 10) | 0);
self::$startTime = $time * 1000;
}
/**
* Encodes Sonyflake bytes into one of bases: 16, 32, 36, 58, 62.
*
* @throws SonyflakeException
*/
public static function toBase(string $id, int $base): string
{
return BaseEncoder::encodeBytes(self::toBytes($id), $base);
}
/**
* Converts a Sonyflake decimal string to 8-byte binary representation.
*
* @throws SonyflakeException
*/
public static function toBytes(string $id): string
{
return self::decodeNumeric(
fn(): string => NumericIdCodec::bytesFromDecimal(
$id,
8,
self::isValid(...),
'Invalid Sonyflake ID string',
),
'Unable to convert Sonyflake ID to bytes',
);
}
/**
* @param callable():string $operation
* @throws SonyflakeException
*/
private static function decodeNumeric(callable $operation, ?string $customMessage): string
{
try {
return $operation();
} catch (\InvalidArgumentException $exception) {
throw new SonyflakeException($customMessage ?? $exception->getMessage(), 0, $exception);
}
}
/**
* Calculates the elapsed time in 10ms units.
*/
private static function elapsedTime(int $startTimestamp): int
{
return floor(((new DateTimeImmutable('now'))->format('Uv') - $startTimestamp) / 10) | 0;
}
/**
* Ensures that the elapsed time does not exceed the maximum life cycle of the algorithm.
*
* @param int $elapsedTime The elapsed time in milliseconds.
* @throws SonyflakeException If the elapsed time exceeds the maximum life cycle.
*/
private static function ensureEffectiveRuntime(int $elapsedTime): void
{
if ($elapsedTime > (-1 ^ (-1 << self::$maxTimestampLength))) {
throw new SonyflakeException('Exceeding the maximum life cycle of the algorithm');
}
}
/**
* @return array{seconds:string,fraction:string,sequence:int,machine_id:int}
*/
private static function extractParts(string $id, int $startTimestamp): array
{
$binary = decbin((int) $id);
$tailBitLength = self::$maxMachineIdLength + self::$maxSequenceLength;
$elapsed = bindec(substr($binary, 0, strlen($binary) - $tailBitLength));
$timestamp = (string) ($startTimestamp + ($elapsed * 10));
$timeParts = str_split($timestamp, 10);
return [
'seconds' => $timeParts[0],
'fraction' => $timeParts[1] ?? '0',
'sequence' => (int) bindec(substr($binary, -1 * self::$maxSequenceLength)),
'machine_id' => (int) bindec(substr($binary, -1 * $tailBitLength, self::$maxMachineIdLength)),
];
}
/**
* @throws SonyflakeException|FileLockException
*/
private static function generateInternal(
int $machineId,
int $startTimestamp,
ClockBackwardPolicy $clockBackwardPolicy,
IdOutputType $outputType,
?SequenceProviderInterface $sequenceProvider = null,
): int|string {
$maxMachineID = -1 ^ (-1 << self::$maxMachineIdLength);
if ($machineId < 0 || $machineId > $maxMachineID) {
throw new SonyflakeException("Invalid machine ID, must be between 0 ~ $maxMachineID.");
}
$elapsedTime = self::elapsedTime($startTimestamp);
if ($elapsedTime < self::$lastElapsedTime) {
if ($clockBackwardPolicy === ClockBackwardPolicy::THROW) {
throw new SonyflakeException('Clock moved backwards while generating Sonyflake ID');
}
$elapsedTime = self::waitUntilElapsed(self::$lastElapsedTime, $startTimestamp);
}
while (($sequence = self::sequence(
$elapsedTime,
$machineId,
'sonyflake',
$sequenceProvider,
)) > (-1 ^ (-1 << self::$maxSequenceLength))) {
$elapsedTime = self::waitUntilElapsed($elapsedTime, $startTimestamp);
}
self::$lastElapsedTime = $elapsedTime;
self::ensureEffectiveRuntime($elapsedTime);
$id = (string) ($elapsedTime << (self::$maxMachineIdLength + self::$maxSequenceLength)
| ($machineId << self::$maxSequenceLength)
| ($sequence));
return OutputFormatter::formatNumeric($id, $outputType);
}
/**
* Retrieves the start timestamp.
*/
private static function getStartTimeStamp(): int
{
return self::$startTime ??= (strtotime('2020-01-01 00:00:00') * 1000);
}
private static function waitUntilElapsed(int $elapsedTime, int $startTimestamp): int
{
$next = self::elapsedTime($startTimestamp);
while ($next <= $elapsedTime) {
usleep(1000);
$next = self::elapsedTime($startTimestamp);
}
return $next;
}
}
You can’t perform that action at this time.
