23use InvalidArgumentException;
25use Wikimedia\Assert\Assert;
26use Wikimedia\AtEase\AtEase;
27use Wikimedia\Timestamp\ConvertibleTimestamp;
60 public const QUICK_VOLATILE = 1;
86 __CLASS__ .
' with a BagOStuff instance was deprecated in MediaWiki 1.37.',
91 if ( !strlen( $tempDirectory ) ) {
92 throw new InvalidArgumentException(
"No temp directory provided" );
94 $this->tmpDir = $tempDirectory;
95 $this->nodeIdFile = $tempDirectory .
'/' . self::FILE_PREFIX .
'-UID-nodeid';
98 $this->lockFile88 = $tempDirectory .
'/' . self::FILE_PREFIX .
'-UID-88';
99 $this->lockFile128 = $tempDirectory .
'/' . self::FILE_PREFIX .
'-UID-128';
100 $this->lockFileUUID = $tempDirectory .
'/' . self::FILE_PREFIX .
'-UUID-128';
121 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
122 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
141 $id_bin .= str_pad( decbin( $counter ), 10,
'0', STR_PAD_LEFT );
145 if ( strlen( $id_bin ) !== 88 ) {
146 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
167 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
168 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
170 $info = $this->
getTimeAndDelay(
'lockFile128', 16384, 1048576, 1048576 );
188 $id_bin .= str_pad( decbin( $counter ), 20,
'0', STR_PAD_LEFT );
190 $id_bin .= str_pad( decbin( $clkSeq ), 14,
'0', STR_PAD_LEFT );
194 if ( strlen( $id_bin ) !== 128 ) {
195 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
219 $clkSeq_bin = \Wikimedia\base_convert( $info[self::CLOCK_SEQUENCE], 10, 2, 14 );
221 $info[self::CLOCK_TIME],
222 $info[self::CLOCK_OFFSET_COUNTER]
225 $id_bin = substr( $time_bin, 28, 32 );
227 $id_bin .= substr( $time_bin, 12, 16 );
231 $id_bin .= substr( $time_bin, 0, 12 );
235 $id_bin .= substr( $clkSeq_bin, 0, 6 );
237 $id_bin .= substr( $clkSeq_bin, 6, 8 );
241 if ( strlen( $id_bin ) !== 128 ) {
242 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
244 $hex = \Wikimedia\base_convert( $id_bin, 2, 16, 32 );
245 return sprintf(
'%s-%s-%s-%s-%s',
247 substr( $hex, 0, 8 ),
249 substr( $hex, 8, 4 ),
251 substr( $hex, 12, 4 ),
253 substr( $hex, 16, 4 ),
255 substr( $hex, 20, 12 )
266 return str_replace(
'-',
'', $this->
newUUIDv1() );
276 $hex = bin2hex( random_bytes( 32 / 2 ) );
278 return sprintf(
'%s-%s-%s-%s-%s',
280 substr( $hex, 0, 8 ),
282 substr( $hex, 8, 4 ),
284 '4' . substr( $hex, 12, 3 ),
286 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
288 substr( $hex, 19, 12 )
299 return str_replace(
'-',
'', $this->
newUUIDv4() );
342 '/^([0-9a-f]{8})-([0-9a-f]{4})-(1[0-9a-f]{3})-([89ab][0-9a-f]{3})-([0-9a-f]{12})$/',
346 throw new InvalidArgumentException(
"Invalid UUIDv1 {$uuid}" );
349 $timestamp = hexdec( substr( $components[3], 1 ) . $components[2] . $components[1] );
352 $unixTime = ( $timestamp - 0x01b21dd213814000 ) / 1e7;
354 return ConvertibleTimestamp::convert( $format, $unixTime );
372 if ( $bits < 16 || $bits > 48 ) {
373 throw new RuntimeException(
"Requested bit size ($bits) is out of range." );
376 $path = $this->tmpDir .
'/' . self::FILE_PREFIX .
'-' . rawurlencode( $bucket ) .
'-48';
378 if ( isset( $this->fileHandles[
$path] ) ) {
379 $handle = $this->fileHandles[
$path];
381 $handle = fopen(
$path,
'cb+' );
382 $this->fileHandles[
$path] = $handle ?:
null;
385 if ( $handle ===
false ) {
386 throw new RuntimeException(
"Could not open '{$path}'." );
388 if ( !flock( $handle, LOCK_EX ) ) {
390 throw new RuntimeException(
"Could not acquire '{$path}'." );
394 $counter = floor( (
float)trim( fgets( $handle ) ) ) + $count;
396 ftruncate( $handle, 0 );
399 fwrite( $handle, fmod( $counter, 2 ** 48 ) );
402 flock( $handle, LOCK_UN );
405 $divisor = 2 ** $bits;
406 $currentId = floor( $counter - $count );
407 for ( $i = 0; $i < $count; ++$i ) {
409 $ids[] = fmod( ++$currentId, $divisor );
432 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
434 if ( isset( $this->fileHandles[$this->$lockFile] ) ) {
435 $handle = $this->fileHandles[$this->$lockFile];
437 $handle = fopen( $this->$lockFile,
'cb+' );
438 $this->fileHandles[$this->$lockFile] = $handle ?:
null;
441 if ( $handle ===
false ) {
442 throw new RuntimeException(
"Could not open '{$this->$lockFile}'." );
444 if ( !flock( $handle, LOCK_EX ) ) {
446 throw new RuntimeException(
"Could not acquire '{$this->$lockFile}'." );
491 $msecCounterSize = $counterSize * 1000;
496 $data = explode(
' ', fgets( $handle ) );
498 if ( count( $data ) === 4 ) {
500 $clkSeq = (int)$data[0] % $clockSeqSize;
501 $prevSec = (int)$data[1];
504 $randOffset = (int)$data[3] % $counterSize;
511 if ( $sec ===
false ) {
515 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
517 $randOffset = mt_rand( 0, $offsetSize - 1 );
518 trigger_error(
"Clock was set back; sequence number incremented." );
519 } elseif ( $sec === $prevSec ) {
522 $msecCounter = (int)$data[2] % $msecCounterSize;
524 if ( ++$msecCounter >= $msecCounterSize ) {
526 flock( $handle, LOCK_UN );
527 throw new RuntimeException(
"Counter overflow for timestamp value." );
532 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
535 $randOffset = mt_rand( 0, $offsetSize - 1 );
539 ftruncate( $handle, 0 );
541 fwrite( $handle,
"{$clkSeq} {$sec} {$msecCounter} {$randOffset}" );
543 flock( $handle, LOCK_UN );
546 $msec = (int)( $msecCounter / 1000 );
547 $counter = $msecCounter % 1000;
550 self::CLOCK_TIME => [ $sec, $msec ],
551 self::CLOCK_COUNTER => $counter,
552 self::CLOCK_SEQUENCE => $clkSeq,
553 self::CLOCK_OFFSET => $randOffset,
554 self::CLOCK_OFFSET_COUNTER => $counter + $randOffset,
566 $start = microtime(
true );
570 if ( $ct >= $time ) {
574 }
while ( ( microtime(
true ) - $start ) <= 0.010 );
585 list( $sec, $msec ) = $time;
586 $ts = 1000 * $sec + $msec;
587 if ( $ts > 2 ** 52 ) {
588 throw new RuntimeException( __METHOD__ .
589 ': sorry, this function doesn\'t work after the year 144680' );
592 return substr( \
Wikimedia\base_convert( $ts, 10, 2, 46 ), -46 );
602 list( $sec, $msec ) = $time;
603 $offset =
'122192928000000000';
604 if ( PHP_INT_SIZE >= 8 ) {
605 $ts = ( 1000 * $sec + $msec ) * 10000 + (
int)$offset + $delta;
606 $id_bin = str_pad( decbin( $ts % ( 2 ** 60 ) ), 60,
'0', STR_PAD_LEFT );
607 } elseif ( extension_loaded(
'gmp' ) ) {
608 $ts = gmp_add( gmp_mul( (
string)$sec,
'1000' ), (
string)$msec );
609 $ts = gmp_add( gmp_mul( $ts,
'10000' ), $offset );
610 $ts = gmp_add( $ts, (
string)$delta );
611 $ts = gmp_mod( $ts, gmp_pow(
'2',
'60' ) );
612 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60,
'0', STR_PAD_LEFT );
613 } elseif ( extension_loaded(
'bcmath' ) ) {
614 $ts = bcadd( bcmul( $sec, 1000 ), $msec );
615 $ts = bcadd( bcmul( $ts, 10000 ), $offset );
616 $ts = bcadd( $ts, $delta );
617 $ts = bcmod( $ts, bcpow( 2, 60 ) );
618 $id_bin = \Wikimedia\base_convert( $ts, 10, 2, 60 );
620 throw new RuntimeException(
'bcmath or gmp extension required for 32 bit machines.' );
629 if ( $this->loaded ) {
633 $this->loaded =
true;
636 if ( is_file( $this->nodeIdFile ) ) {
637 $nodeId = file_get_contents( $this->nodeIdFile );
640 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
641 AtEase::suppressWarnings();
642 if ( PHP_OS_FAMILY ===
'Windows' ) {
644 $csv = trim( ( $this->shellCallback )(
'getmac /NH /FO CSV' ) );
645 $line = substr( $csv, 0, strcspn( $csv,
"\n" ) );
646 $info = str_getcsv(
$line );
647 $nodeId = isset( $info[0] ) ? str_replace(
'-',
'', $info[0] ) :
'';
648 } elseif ( is_executable(
'/sbin/ifconfig' ) ) {
651 preg_match(
'/\s([0-9a-f]{2}(?::[0-9a-f]{2}){5})\s/',
652 ( $this->shellCallback )(
'/sbin/ifconfig -a' ), $m );
653 $nodeId = isset( $m[1] ) ? str_replace(
':',
'', $m[1] ) :
'';
655 AtEase::restoreWarnings();
656 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
657 $nodeId = bin2hex( random_bytes( 12 / 2 ) );
658 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 );
660 file_put_contents( $this->nodeIdFile, $nodeId );
662 $this->nodeId32 = \Wikimedia\base_convert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
663 $this->nodeId48 = \Wikimedia\base_convert( $nodeId, 16, 2, 48 );
696 foreach ( $this->fileHandles as
$path => $handle ) {
697 if ( $handle !==
null ) {
700 if ( is_file(
$path ) ) {
703 unset( $this->fileHandles[
$path] );
705 if ( is_file( $this->nodeIdFile ) ) {
706 unlink( $this->nodeIdFile );
728 array_map(
'fclose', array_filter( $this->fileHandles ) );