Skip to content

chore: make random sequence resolver more random #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Snowflake & Sonyflake algorithm PHP implementation [中文文档](https://github

![file](https://images.godruoyi.com/logos/201908/13/_1565672621_LPW65Pi8cG.png)

Snowflake is a network service that generates unique ID numbers at high scale with simple guarantees.
Snowflake is a network service that generates unique ID numbers at a high scale with simple guarantees.

1. The first bit is an unused sign bit.
2. The second part consists of a 41-bit timestamp (in milliseconds) representing the offset of the current time relative to a certain reference time.
Expand Down Expand Up @@ -84,7 +84,7 @@ $snowflake = new \Godruoyi\Snowflake\Snowflake($datacenterId, $workerId);
$snowflake->id();
```

3. Specify start time.
3. Specify the start time.

```php
$snowflake = new \Godruoyi\Snowflake\Snowflake;
Expand All @@ -95,7 +95,16 @@ $snowflake->id();

> The maximum value of a 41-bit timestamp (in milliseconds) can represent up to 69 years, so the Snowflake algorithm can run safely for 69 years. In order to make the most of it, we recommend setting a start time.

4. Use Sonyflake
4. Using different sequence number resolvers (optional).

```php
$snowflake = new \Godruoyi\Snowflake\Snowflake;
$snowflake->setSequenceResolver(new \Godruoyi\Snowflake\RandomSequenceResolver);

$snowflake->id();
```

5. Use Sonyflake

```php
$sonyflake = new \Godruoyi\Snowflake\Sonyflake;
Expand Down
2 changes: 1 addition & 1 deletion src/RandomSequenceResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function sequence(int $currentTime): int
return $this->sequence;
}

$this->sequence = random_int(0, $this->maxSequence);
$this->sequence = crc32(uniqid((string) random_int(0, PHP_INT_MAX), true)) % $this->maxSequence;
$this->lastTimeStamp = $currentTime;

return $this->sequence;
Expand Down
4 changes: 2 additions & 2 deletions src/Snowflake.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public function __construct(int $datacenter = 0, int $workerId = 0)
$maxWorkId = -1 ^ (-1 << self::MAX_WORKID_LENGTH);

// If not set datacenter or workid, we will set a default value to use.
$this->datacenter = $datacenter > $maxDataCenter || $datacenter < 0 ? random_int(0, 31) : $datacenter;
$this->workerId = $workerId > $maxWorkId || $workerId < 0 ? random_int(0, 31) : $workerId;
$this->datacenter = $datacenter > $maxDataCenter || $datacenter <= 0 ? random_int(0, 31) : $datacenter;
$this->workerId = $workerId > $maxWorkId || $workerId <= 0 ? random_int(0, 31) : $workerId;
}

/**
Expand Down
7 changes: 4 additions & 3 deletions tests/FileLockResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@
class FileLockResolverTest extends TestCase
{
private static string $mainLockFileDirPath;

private static string $unWriteableFileDirPath;

private FileLockResolver $fileLocker;

public static function setUpBeforeClass(): void
{
self::$mainLockFileDirPath = dirname(__DIR__) . '/.locks';
self::$unWriteableFileDirPath = __DIR__ . '/.locks';
self::$mainLockFileDirPath = dirname(__DIR__).'/.locks';
self::$unWriteableFileDirPath = __DIR__.'/.locks';
}

protected function setUp(): void
Expand Down Expand Up @@ -375,7 +376,7 @@ private function touch(string $content = ''): string

private function cleanUpLockFileDirs(): void
{
$glob = self::$mainLockFileDirPath . '/*';
$glob = self::$mainLockFileDirPath.'/*';
$files = glob($glob);
foreach ($files as $file) {
if (is_file($file)) {
Expand Down
2 changes: 1 addition & 1 deletion tests/PredisSequenceResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

class PredisSequenceResolverTest extends TestCase
{
public function setUp(): void
protected function setUp(): void
{
if (! class_exists('Predis\\Client')) {
$this->markTestSkipped('Predis extension is not installed');
Expand Down
17 changes: 16 additions & 1 deletion tests/RandomSequenceResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function test_basic(): void
$this->assertCount(Snowflake::MAX_SEQUENCE_SIZE, $seqs);
}

public function test_can_generate_unique_id_by_snowflake(): void
public function test_can_generate_unique_id_using_same_instance(): void
{
$snowflake = new Snowflake(1, 1);
$seqs = [];
Expand All @@ -40,4 +40,19 @@ public function test_can_generate_unique_id_by_snowflake(): void

$this->assertCount(Snowflake::MAX_SEQUENCE_SIZE, $seqs);
}

public function test_can_generate_unique_id_by_different_instance(): void
{
for ($i = 0; $i < 1000; $i++) {
$ids = [];

for ($i = 0; $i < 100_000; $i++) {
$snowflake = new Snowflake();
$ids[$snowflake->id()] = true;
}

// We expect to have at least 100_000 - 10 unique ids if using random sequence resolver
$this->assertGreaterThanOrEqual(100_000 - 10, count($ids));
}
}
}
2 changes: 1 addition & 1 deletion tests/RedisSequenceResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

class RedisSequenceResolverTest extends TestCase
{
public function setUp(): void
protected function setUp(): void
{
if (! extension_loaded('redis')) {
$this->markTestSkipped('Redis extension is not installed');
Expand Down
2 changes: 1 addition & 1 deletion tests/SwooleSequenceResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

class SwooleSequenceResolverTest extends TestCase
{
public function setUp(): void
protected function setUp(): void
{
if (version_compare(PHP_VERSION, '8.4') >= 0) {
$this->markTestSkipped('Swoole does not yet support PHP 8.4');
Expand Down