22use Wikimedia\Assert\Assert;
54 $this->nodeIdFile =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-nodeid';
56 if ( is_file( $this->nodeIdFile ) ) {
57 $nodeId = file_get_contents( $this->nodeIdFile );
60 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
61 Wikimedia\suppressWarnings();
65 $line = substr( $csv, 0, strcspn( $csv,
"\n" ) );
66 $info = str_getcsv(
$line );
67 $nodeId = isset( $info[0] ) ? str_replace(
'-',
'', $info[0] ) :
'';
68 } elseif ( is_executable(
'/sbin/ifconfig' ) ) {
71 preg_match(
'/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
73 $nodeId = isset( $m[1] ) ? str_replace(
':',
'', $m[1] ) :
'';
75 Wikimedia\restoreWarnings();
76 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
78 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 );
80 file_put_contents( $this->nodeIdFile, $nodeId );
82 $this->nodeId32 = Wikimedia\base_convert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
83 $this->nodeId48 = Wikimedia\base_convert( $nodeId, 16, 2, 48 );
86 $this->lockFile88 =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-88';
87 $this->lockFile128 =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-128';
88 $this->lockFileUUID =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UUID-128';
96 if ( self::$instance ===
null ) {
97 self::$instance =
new self();
119 Assert::parameterType(
'integer',
$base,
'$base' );
120 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
121 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
124 $info = $gen->getTimeAndDelay(
'lockFile88', 1, 1024, 1024 );
125 $info[
'offsetCounter'] = $info[
'offsetCounter'] % 1024;
126 return Wikimedia\base_convert( $gen->getTimestampedID88( $info ), 2,
$base );
136 if ( isset( $info[
'time'] ) ) {
137 $time = $info[
'time'];
138 $counter = $info[
'offsetCounter'];
140 list( $time, $counter ) = $info;
145 $id_bin .= str_pad( decbin( $counter ), 10,
'0', STR_PAD_LEFT );
149 if ( strlen( $id_bin ) !== 88 ) {
150 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
171 Assert::parameterType(
'integer',
$base,
'$base' );
172 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
173 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
176 $info = $gen->getTimeAndDelay(
'lockFile128', 16384, 1048576, 1048576 );
177 $info[
'offsetCounter'] = $info[
'offsetCounter'] % 1048576;
179 return Wikimedia\base_convert( $gen->getTimestampedID128( $info ), 2,
$base );
189 if ( isset( $info[
'time'] ) ) {
190 $time = $info[
'time'];
191 $counter = $info[
'offsetCounter'];
192 $clkSeq = $info[
'clkSeq'];
194 list( $time, $counter, $clkSeq ) = $info;
199 $id_bin .= str_pad( decbin( $counter ), 20,
'0', STR_PAD_LEFT );
201 $id_bin .= str_pad( decbin( $clkSeq ), 14,
'0', STR_PAD_LEFT );
205 if ( strlen( $id_bin ) !== 128 ) {
206 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
224 return $gen->getUUIDv1( $gen->getTimeAndDelay(
'lockFileUUID', 16384, 5000, 5001 ) );
235 return str_replace(
'-',
'', self::newUUIDv1() );
243 $clkSeq_bin = Wikimedia\base_convert( $info[
'clkSeq'], 10, 2, 14 );
246 $id_bin = substr( $time_bin, 28, 32 );
248 $id_bin .= substr( $time_bin, 12, 16 );
252 $id_bin .= substr( $time_bin, 0, 12 );
256 $id_bin .= substr( $clkSeq_bin, 0, 6 );
258 $id_bin .= substr( $clkSeq_bin, 6, 8 );
262 if ( strlen( $id_bin ) !== 128 ) {
263 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
265 $hex = Wikimedia\base_convert( $id_bin, 2, 16, 32 );
266 return sprintf(
'%s-%s-%s-%s-%s',
268 substr( $hex, 0, 8 ),
270 substr( $hex, 8, 4 ),
272 substr( $hex, 12, 4 ),
274 substr( $hex, 16, 4 ),
276 substr( $hex, 20, 12 )
292 return sprintf(
'%s-%s-%s-%s-%s',
294 substr( $hex, 0, 8 ),
296 substr( $hex, 8, 4 ),
298 '4' . substr( $hex, 12, 3 ),
300 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
302 substr( $hex, 19, 12 )
314 return str_replace(
'-',
'', self::newUUIDv4( $flags ) );
330 return current( self::newSequentialPerNodeIDs( $bucket, $bits, 1, $flags ) );
346 return $gen->getSequentialPerNodeIDs( $bucket, $bits, $count, $flags );
364 if ( $bits < 16 || $bits > 48 ) {
365 throw new RuntimeException(
"Requested bit size ($bits) is out of range." );
373 if ( ( $flags & self::QUICK_VOLATILE ) && !
wfIsCLI() ) {
374 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
377 $counter =
$cache->incrWithInit( $bucket, $cache::TTL_INDEFINITE, $count, $count );
378 if ( $counter ===
false ) {
379 throw new RuntimeException(
'Unable to set value to ' . get_class(
$cache ) );
384 if ( $counter ===
null ) {
385 $path =
wfTempDir() .
'/mw-' . __CLASS__ .
'-' . rawurlencode( $bucket ) .
'-48';
387 if ( isset( $this->fileHandles[
$path] ) ) {
388 $handle = $this->fileHandles[
$path];
390 $handle = fopen(
$path,
'cb+' );
391 $this->fileHandles[
$path] = $handle ?:
null;
394 if ( $handle ===
false ) {
395 throw new RuntimeException(
"Could not open '{$path}'." );
397 if ( !flock( $handle, LOCK_EX ) ) {
399 throw new RuntimeException(
"Could not acquire '{$path}'." );
403 $counter = floor( trim( fgets( $handle ) ) ) + $count;
405 ftruncate( $handle, 0 );
407 fwrite( $handle, fmod( $counter, 2 ** 48 ) );
410 flock( $handle, LOCK_UN );
414 $divisor = 2 ** $bits;
415 $currentId = floor( $counter - $count );
416 for ( $i = 0; $i < $count; ++$i ) {
417 $ids[] = fmod( ++$currentId, $divisor );
440 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
442 if ( isset( $this->fileHandles[$lockFile] ) ) {
443 $handle = $this->fileHandles[$lockFile];
445 $handle = fopen( $this->$lockFile,
'cb+' );
446 $this->fileHandles[$lockFile] = $handle ?:
null;
449 if ( $handle ===
false ) {
450 throw new RuntimeException(
"Could not open '{$this->$lockFile}'." );
452 if ( !flock( $handle, LOCK_EX ) ) {
454 throw new RuntimeException(
"Could not acquire '{$this->$lockFile}'." );
499 $msecCounterSize = $counterSize * 1000;
504 $data = explode(
' ', fgets( $handle ) );
506 if ( count( $data ) === 4 ) {
508 $clkSeq = (int)$data[0] % $clockSeqSize;
509 $prevSec = (int)$data[1];
512 $randOffset = (int)$data[3] % $counterSize;
519 if ( $sec ===
false ) {
523 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
525 $randOffset = mt_rand( 0, $offsetSize - 1 );
526 trigger_error(
"Clock was set back; sequence number incremented." );
527 } elseif ( $sec === $prevSec ) {
530 $msecCounter = (int)$data[2] % $msecCounterSize;
532 if ( ++$msecCounter >= $msecCounterSize ) {
534 flock( $handle, LOCK_UN );
535 throw new RuntimeException(
"Counter overflow for timestamp value." );
540 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
543 $randOffset = mt_rand( 0, $offsetSize - 1 );
547 ftruncate( $handle, 0 );
549 fwrite( $handle,
"{$clkSeq} {$sec} {$msecCounter} {$randOffset}" );
551 flock( $handle, LOCK_UN );
554 $msec = (int)( $msecCounter / 1000 );
555 $counter = $msecCounter % 1000;
558 'time' => [ $sec, $msec ],
559 'counter' => $counter,
561 'offset' => $randOffset,
562 'offsetCounter' => $counter + $randOffset,
574 $start = microtime(
true );
578 if ( $ct >= $time ) {
582 }
while ( ( microtime(
true ) - $start ) <= 0.010 );
593 list( $sec, $msec ) = $time;
594 $ts = 1000 * $sec + $msec;
595 if ( $ts > 2 ** 52 ) {
596 throw new RuntimeException( __METHOD__ .
597 ': sorry, this function doesn\'t work after the year 144680' );
600 return substr(
Wikimedia\base_convert( $ts, 10, 2, 46 ), -46 );
610 list( $sec, $msec ) = $time;
611 $offset =
'122192928000000000';
612 if ( PHP_INT_SIZE >= 8 ) {
613 $ts = ( 1000 * $sec + $msec ) * 10000 + (
int)$offset + $delta;
614 $id_bin = str_pad( decbin( $ts % ( 2 ** 60 ) ), 60,
'0', STR_PAD_LEFT );
615 } elseif ( extension_loaded(
'gmp' ) ) {
616 $ts = gmp_add( gmp_mul( (
string)$sec,
'1000' ), (
string)$msec );
617 $ts = gmp_add( gmp_mul( $ts,
'10000' ), $offset );
618 $ts = gmp_add( $ts, (
string)$delta );
619 $ts = gmp_mod( $ts, gmp_pow(
'2',
'60' ) );
620 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60,
'0', STR_PAD_LEFT );
621 } elseif ( extension_loaded(
'bcmath' ) ) {
622 $ts = bcadd( bcmul( $sec, 1000 ), $msec );
623 $ts = bcadd( bcmul( $ts, 10000 ), $offset );
624 $ts = bcadd( $ts, $delta );
625 $ts = bcmod( $ts, bcpow( 2, 60 ) );
626 $id_bin = Wikimedia\base_convert( $ts, 10, 2, 60 );
628 throw new RuntimeException(
'bcmath or gmp extension required for 32 bit machines.' );
647 foreach ( $this->fileHandles as
$path => $handle ) {
648 if ( $handle !==
null ) {
651 if ( is_file(
$path ) ) {
654 unset( $this->fileHandles[
$path] );
656 if ( is_file( $this->nodeIdFile ) ) {
657 unlink( $this->nodeIdFile );
677 $gen->deleteCacheFiles();
681 array_map(
'fclose', array_filter( $this->fileHandles ) );
wfTempDir()
Tries to get the system directory for temporary files.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfIsWindows()
Check if the operating system is Windows.
wfIsCLI()
Check if we are running from the commandline.
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format.
Class for getting statistically unique IDs.
static newRawUUIDv1()
Return an RFC4122 compliant v1 UUID.
string $nodeIdFile
Local file path.
deleteCacheFiles()
Delete all cache files that have been created.
static newSequentialPerNodeID( $bucket, $bits=48, $flags=0)
Return an ID that is sequential only for this node and bucket.
array $fileHandles
Cached file handles.
millisecondsSinceEpochBinary(array $time)
getTimestampedID88(array $info)
string $lockFile128
Local file path.
static newSequentialPerNodeIDs( $bucket, $bits, $count, $flags=0)
Return IDs that are sequential only for this node and bucket.
string $nodeId32
Node ID in binary (32 bits)
getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize)
Get a (time,counter,clock sequence) where (time,counter) is higher than any previous (time,...
string $nodeId48
Node ID in binary (48 bits)
string $lockFile88
Local file path.
static UIDGenerator $instance
static newRawUUIDv4( $flags=0)
Return an RFC4122 compliant v4 UUID.
getSequentialPerNodeIDs( $bucket, $bits, $count, $flags)
Return IDs that are sequential only for this node and bucket.
timeWaitUntil( $time)
Wait till the current timestamp reaches $time and return the current timestamp.
getTimestampedID128(array $info)
intervalsSinceGregorianBinary(array $time, $delta=0)
static newUUIDv4( $flags=0)
Return an RFC4122 compliant v4 UUID.
string $lockFileUUID
Local file path.
static newUUIDv1()
Return an RFC4122 compliant v1 UUID.
static newTimestampedUID128( $base=10)
Get a statistically unique 128-bit unsigned integer ID string.
static unitTestTearDown()
Cleanup resources when tearing down after a unit test.
static newTimestampedUID88( $base=10)
Get a statistically unique 88-bit unsigned integer ID string.