Repository navigation
Expand file tree
/
Copy pathMetaGenerator.php
More file actions
77 lines (59 loc) · 2.33 KB
/
Copy pathMetaGenerator.php
File metadata and controls
77 lines (59 loc) · 2.33 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
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Snowflake;
use Hyperf\Snowflake\Exception\SnowflakeException;
abstract class MetaGenerator implements MetaGeneratorInterface
{
protected int $sequence = 0;
protected int $lastTimestamp = 0;
public function __construct(protected ConfigurationInterface $configuration, protected int $beginTimestamp)
{
$this->lastTimestamp = $this->getTimestamp();
}
public function generate(): Meta
{
$timestamp = $this->getTimestamp();
if ($timestamp == $this->lastTimestamp) {
$this->sequence = ($this->sequence + 1) % $this->configuration->maxSequence();
if ($this->sequence == 0) {
$timestamp = $this->getNextTimestamp();
}
} elseif ($timestamp < $this->lastTimestamp) {
$this->clockMovedBackwards($timestamp, $this->lastTimestamp);
$this->sequence = ($this->sequence + 1) % $this->configuration->maxSequence();
$timestamp = $this->lastTimestamp;
} else {
$this->sequence = 0;
}
if ($timestamp < $this->beginTimestamp) {
throw new SnowflakeException(sprintf('The beginTimestamp %d is invalid, because it smaller than timestamp %d.', $this->beginTimestamp, $timestamp));
}
$this->lastTimestamp = $timestamp;
$sequence = $this->sequence;
return new Meta($this->getDataCenterId(), $this->getWorkerId(), $sequence, $timestamp, $this->beginTimestamp);
}
public function getBeginTimestamp(): int
{
return $this->beginTimestamp;
}
public function getConfiguration(): ConfigurationInterface
{
return $this->configuration;
}
abstract public function getDataCenterId(): int;
abstract public function getWorkerId(): int;
abstract public function getTimestamp(): int;
abstract public function getNextTimestamp(): int;
protected function clockMovedBackwards($timestamp, $lastTimestamp)
{
throw new SnowflakeException(sprintf('Clock moved backwards. Refusing to generate id for %d milliseconds.', $lastTimestamp - $timestamp));
}
}