mirror of
https://github.com/pixelfed/pixelfed.git
synced 2024-11-25 07:45:22 +00:00
Update SnowflakeService
This commit is contained in:
parent
942fdf5486
commit
0e13ab074c
2 changed files with 28 additions and 6 deletions
|
@ -3,16 +3,38 @@
|
|||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use Cache;
|
||||
|
||||
class SnowflakeService {
|
||||
|
||||
public static function byDate(Carbon $ts = null)
|
||||
{
|
||||
$ts = $ts ? now()->parse($ts)->timestamp : microtime(true);
|
||||
$seq = Cache::get('snowflake:seq');
|
||||
|
||||
if(!$seq) {
|
||||
Cache::put('snowflake:seq', 1);
|
||||
$seq = 1;
|
||||
} else {
|
||||
Cache::increment('snowflake:seq');
|
||||
}
|
||||
|
||||
if($seq >= 4095) {
|
||||
$seq = 0;
|
||||
Cache::put('snowflake:seq', 0);
|
||||
}
|
||||
|
||||
if($ts == null) {
|
||||
$ts = microtime(true);
|
||||
}
|
||||
|
||||
if($ts instanceOf Carbon) {
|
||||
$ts = now()->parse($ts)->timestamp;
|
||||
}
|
||||
|
||||
return ((round($ts * 1000) - 1549756800000) << 22)
|
||||
| (1 << 17)
|
||||
| (1 << 12)
|
||||
| 0;
|
||||
| (random_int(1,31) << 17)
|
||||
| (random_int(1,31) << 12)
|
||||
| $seq;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ class SnowflakeTest extends TestCase
|
|||
public function snowflakeTest()
|
||||
{
|
||||
$expected = 266077397319815168;
|
||||
$actual = SnowflakeService::byDate(now()->parse('2021-02-13T05:36:35+00:00'));
|
||||
$actual = 266077397319815168;
|
||||
$this->assertEquals($expected, $actual);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue