23 use Wikimedia\Assert\Assert;
50 $this->nodeIdFile =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-nodeid';
52 if ( is_file( $this->nodeIdFile ) ) {
53 $nodeId = file_get_contents( $this->nodeIdFile );
56 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
57 MediaWiki\suppressWarnings();
61 $line = substr( $csv, 0, strcspn( $csv,
"\n" ) );
62 $info = str_getcsv(
$line );
63 $nodeId = isset( $info[0] ) ? str_replace(
'-',
'', $info[0] ) :
'';
64 } elseif ( is_executable(
'/sbin/ifconfig' ) ) {
67 preg_match(
'/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
69 $nodeId = isset( $m[1] ) ? str_replace(
':',
'', $m[1] ) :
'';
71 MediaWiki\restoreWarnings();
72 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
74 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 );
76 file_put_contents( $this->nodeIdFile, $nodeId );
78 $this->nodeId32 = Wikimedia\base_convert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
79 $this->nodeId48 = Wikimedia\base_convert( $nodeId, 16, 2, 48 );
82 $this->lockFile88 =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-88';
83 $this->lockFile128 =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-128';
84 $this->lockFileUUID =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UUID-128';
92 if ( self::$instance ===
null ) {
93 self::$instance =
new self();
115 Assert::parameterType(
'integer',
$base,
'$base' );
116 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
117 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
120 $info = $gen->getTimeAndDelay(
'lockFile88', 1, 1024, 1024 );
121 $info[
'offsetCounter'] = $info[
'offsetCounter'] % 1024;
122 return Wikimedia\base_convert( $gen->getTimestampedID88( $info ), 2,
$base );
132 if ( isset( $info[
'time'] ) ) {
133 $time = $info[
'time'];
134 $counter = $info[
'offsetCounter'];
142 $id_bin .= str_pad( decbin( $counter ), 10,
'0', STR_PAD_LEFT );
146 if ( strlen( $id_bin ) !== 88 ) {
147 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
168 Assert::parameterType(
'integer',
$base,
'$base' );
169 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
170 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
173 $info = $gen->getTimeAndDelay(
'lockFile128', 16384, 1048576, 1048576 );
174 $info[
'offsetCounter'] = $info[
'offsetCounter'] % 1048576;
176 return Wikimedia\base_convert( $gen->getTimestampedID128( $info ), 2,
$base );
186 if ( isset( $info[
'time'] ) ) {
187 $time = $info[
'time'];
188 $counter = $info[
'offsetCounter'];
189 $clkSeq = $info[
'clkSeq'];
198 $id_bin .= str_pad( decbin( $counter ), 20,
'0', STR_PAD_LEFT );
200 $id_bin .= str_pad( decbin( $clkSeq ), 14,
'0', STR_PAD_LEFT );
204 if ( strlen( $id_bin ) !== 128 ) {
205 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
223 return $gen->getUUIDv1( $gen->getTimeAndDelay(
'lockFileUUID', 16384, 5000, 5001 ) );
234 return str_replace(
'-',
'', self::newUUIDv1() );
242 $clkSeq_bin = Wikimedia\base_convert( $info[
'clkSeq'], 10, 2, 14 );
245 $id_bin = substr( $time_bin, 28, 32 );
247 $id_bin .= substr( $time_bin, 12, 16 );
251 $id_bin .= substr( $time_bin, 0, 12 );
255 $id_bin .= substr( $clkSeq_bin, 0, 6 );
257 $id_bin .= substr( $clkSeq_bin, 6, 8 );
261 if ( strlen( $id_bin ) !== 128 ) {
262 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
264 $hex = Wikimedia\base_convert( $id_bin, 2, 16, 32 );
265 return sprintf(
'%s-%s-%s-%s-%s',
267 substr( $hex, 0, 8 ),
269 substr( $hex, 8, 4 ),
271 substr( $hex, 12, 4 ),
273 substr( $hex, 16, 4 ),
275 substr( $hex, 20, 12 )
291 return sprintf(
'%s-%s-%s-%s-%s',
293 substr( $hex, 0, 8 ),
295 substr( $hex, 8, 4 ),
297 '4' . substr( $hex, 12, 3 ),
299 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
301 substr( $hex, 19, 12 )
313 return str_replace(
'-',
'', self::newUUIDv4(
$flags ) );
329 return current( self::newSequentialPerNodeIDs( $bucket, $bits, 1,
$flags ) );
345 return $gen->getSequentialPerNodeIDs( $bucket, $bits, $count,
$flags );
362 } elseif ( $bits < 16 || $bits > 48 ) {
363 throw new RuntimeException(
"Requested bit size ($bits) is out of range." );
371 if ( (
$flags & self::QUICK_VOLATILE ) && PHP_SAPI !==
'cli' ) {
372 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
375 $counter =
$cache->incrWithInit( $bucket, $cache::TTL_INDEFINITE, $count, $count );
376 if ( $counter ===
false ) {
377 throw new RuntimeException(
'Unable to set value to ' . get_class(
$cache ) );
382 if ( $counter ===
null ) {
383 $path =
wfTempDir() .
'/mw-' . __CLASS__ .
'-' . rawurlencode( $bucket ) .
'-48';
385 if ( isset( $this->fileHandles[
$path] ) ) {
386 $handle = $this->fileHandles[
$path];
388 $handle = fopen(
$path,
'cb+' );
389 $this->fileHandles[
$path] = $handle ?:
null;
392 if ( $handle ===
false ) {
393 throw new RuntimeException(
"Could not open '{$path}'." );
394 } elseif ( !flock( $handle, LOCK_EX ) ) {
396 throw new RuntimeException(
"Could not acquire '{$path}'." );
400 $counter = floor( trim( fgets( $handle ) ) ) + $count;
402 ftruncate( $handle, 0 );
404 fwrite( $handle, fmod( $counter, pow( 2, 48 ) ) );
407 flock( $handle, LOCK_UN );
411 $divisor = pow( 2, $bits );
412 $currentId = floor( $counter - $count );
413 for ( $i = 0; $i < $count; ++$i ) {
414 $ids[] = fmod( ++$currentId, $divisor );
432 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
434 if ( isset( $this->fileHandles[$lockFile] ) ) {
435 $handle = $this->fileHandles[$lockFile];
437 $handle = fopen( $this->$lockFile,
'cb+' );
438 $this->fileHandles[$lockFile] = $handle ?:
null;
441 if ( $handle ===
false ) {
442 throw new RuntimeException(
"Could not open '{$this->$lockFile}'." );
443 } elseif ( !flock( $handle, LOCK_EX ) ) {
445 throw new RuntimeException(
"Could not acquire '{$this->$lockFile}'." );
449 $data = explode(
' ', fgets( $handle ) );
450 $clockChanged =
false;
451 if (
count( $data ) == 5 ) {
452 $clkSeq = (int)$data[0] % $clockSeqSize;
453 $prevTime = [ (int)$data[1], (
int)$data[2] ];
454 $offset = (int)$data[4] % $counterSize;
460 $clockChanged =
true;
462 } elseif (
$time == $prevTime ) {
464 $counter = (int)$data[3] % $counterSize;
465 if ( ++$counter >= $counterSize ) {
466 flock( $handle, LOCK_UN );
467 throw new RuntimeException(
"Counter overflow for timestamp value." );
471 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
473 $offset = mt_rand( 0, $offsetSize - 1 );
479 if ( abs( time() -
$time[0] ) >= 2 ) {
482 flock( $handle, LOCK_UN );
483 throw new RuntimeException(
"Process clock is outdated or drifted." );
486 if ( $clockChanged ) {
489 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
490 $offset = mt_rand( 0, $offsetSize - 1 );
491 trigger_error(
"Clock was set back; sequence number incremented." );
494 ftruncate( $handle, 0 );
496 fwrite( $handle,
"{$clkSeq} {$time[0]} {$time[1]} {$counter} {$offset}" );
499 flock( $handle, LOCK_UN );
503 'counter' => $counter,
506 'offsetCounter' => $counter + $offset
520 if ( $ct >=
$time ) {
523 }
while ( ( (
$time[0] - $ct[0] ) * 1000 + (
$time[1] - $ct[1] ) ) <= 10 );
535 $ts = 1000 * $sec + $msec;
536 if ( $ts > pow( 2, 52 ) ) {
537 throw new RuntimeException( __METHOD__ .
538 ': sorry, this function doesn\'t work after the year 144680' );
541 return substr(
Wikimedia\base_convert( $ts, 10, 2, 46 ), -46 );
552 $offset =
'122192928000000000';
553 if ( PHP_INT_SIZE >= 8 ) {
554 $ts = ( 1000 * $sec + $msec ) * 10000 + (
int)$offset + $delta;
555 $id_bin = str_pad( decbin( $ts % pow( 2, 60 ) ), 60,
'0', STR_PAD_LEFT );
556 } elseif ( extension_loaded(
'gmp' ) ) {
557 $ts = gmp_add( gmp_mul( (
string)$sec,
'1000' ), (
string)$msec );
558 $ts = gmp_add( gmp_mul( $ts,
'10000' ), $offset );
559 $ts = gmp_add( $ts, (
string)$delta );
560 $ts = gmp_mod( $ts, gmp_pow(
'2',
'60' ) );
561 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60,
'0', STR_PAD_LEFT );
562 } elseif ( extension_loaded(
'bcmath' ) ) {
563 $ts = bcadd( bcmul( $sec, 1000 ), $msec );
564 $ts = bcadd( bcmul( $ts, 10000 ), $offset );
565 $ts = bcadd( $ts, $delta );
566 $ts = bcmod( $ts, bcpow( 2, 60 ) );
567 $id_bin = Wikimedia\base_convert( $ts, 10, 2, 60 );
569 throw new RuntimeException(
'bcmath or gmp extension required for 32 bit machines.' );
578 list( $msec, $sec ) = explode(
' ', microtime() );
580 return [ (int)$sec, (
int)( $msec * 1000 ) ];
596 foreach ( $this->fileHandles
as $path => $handle ) {
597 if ( $handle !==
null ) {
600 if ( is_file(
$path ) ) {
603 unset( $this->fileHandles[
$path] );
605 if ( is_file( $this->nodeIdFile ) ) {
606 unlink( $this->nodeIdFile );
624 $gen->deleteCacheFiles();
628 array_map(
'fclose', array_filter( $this->fileHandles ) );