25use InvalidArgumentException;
27use Wikimedia\Assert\Assert;
28use Wikimedia\AtEase\AtEase;
29use Wikimedia\Timestamp\ConvertibleTimestamp;
77 if ( !strlen( $tempDirectory ) ) {
78 throw new InvalidArgumentException(
"No temp directory provided" );
80 $this->tmpDir = $tempDirectory;
81 $this->nodeIdFile = $tempDirectory .
'/' . self::FILE_PREFIX .
'-UID-nodeid';
84 $this->lockFile88 = $tempDirectory .
'/' . self::FILE_PREFIX .
'-UID-88';
85 $this->lockFile128 = $tempDirectory .
'/' . self::FILE_PREFIX .
'-UID-128';
86 $this->lockFileUUID = $tempDirectory .
'/' . self::FILE_PREFIX .
'-UUID-128';
108 Assert::parameterType(
'integer',
$base,
'$base' );
109 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
110 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
113 $info[
'offsetCounter'] %= 1024;
125 if ( isset( $info[
'time'] ) ) {
126 $time = $info[
'time'];
127 $counter = $info[
'offsetCounter'];
129 list( $time, $counter ) = $info;
134 $id_bin .= str_pad( decbin( $counter ), 10,
'0', STR_PAD_LEFT );
138 if ( strlen( $id_bin ) !== 88 ) {
139 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
160 Assert::parameterType(
'integer',
$base,
'$base' );
161 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
162 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
164 $info = $this->
getTimeAndDelay(
'lockFile128', 16384, 1048576, 1048576 );
165 $info[
'offsetCounter'] %= 1048576;
177 if ( isset( $info[
'time'] ) ) {
178 $time = $info[
'time'];
179 $counter = $info[
'offsetCounter'];
180 $clkSeq = $info[
'clkSeq'];
182 list( $time, $counter, $clkSeq ) = $info;
187 $id_bin .= str_pad( decbin( $counter ), 20,
'0', STR_PAD_LEFT );
189 $id_bin .= str_pad( decbin( $clkSeq ), 14,
'0', STR_PAD_LEFT );
193 if ( strlen( $id_bin ) !== 128 ) {
194 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
218 $clkSeq_bin = \Wikimedia\base_convert( $info[
'clkSeq'], 10, 2, 14 );
221 $id_bin = substr( $time_bin, 28, 32 );
223 $id_bin .= substr( $time_bin, 12, 16 );
227 $id_bin .= substr( $time_bin, 0, 12 );
231 $id_bin .= substr( $clkSeq_bin, 0, 6 );
233 $id_bin .= substr( $clkSeq_bin, 6, 8 );
237 if ( strlen( $id_bin ) !== 128 ) {
238 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
240 $hex = \Wikimedia\base_convert( $id_bin, 2, 16, 32 );
241 return sprintf(
'%s-%s-%s-%s-%s',
243 substr( $hex, 0, 8 ),
245 substr( $hex, 8, 4 ),
247 substr( $hex, 12, 4 ),
249 substr( $hex, 16, 4 ),
251 substr( $hex, 20, 12 )
262 return str_replace(
'-',
'', $this->
newUUIDv1() );
272 $hex = bin2hex( random_bytes( 32 / 2 ) );
274 return sprintf(
'%s-%s-%s-%s-%s',
276 substr( $hex, 0, 8 ),
278 substr( $hex, 8, 4 ),
280 '4' . substr( $hex, 12, 3 ),
282 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
284 substr( $hex, 19, 12 )
295 return str_replace(
'-',
'', $this->
newUUIDv4() );
338 '/^([0-9a-f]{8})-([0-9a-f]{4})-(1[0-9a-f]{3})-([89ab][0-9a-f]{3})-([0-9a-f]{12})$/',
342 throw new InvalidArgumentException(
"Invalid UUIDv1 {$uuid}" );
345 $timestamp = hexdec( substr( $components[3], 1 ) . $components[2] . $components[1] );
348 $unixTime = ( $timestamp - 0x01b21dd213814000 ) / 1e7;
350 return ConvertibleTimestamp::convert( $format, $unixTime );
368 if ( $bits < 16 || $bits > 48 ) {
369 throw new RuntimeException(
"Requested bit size ($bits) is out of range." );
377 ( $flags & self::QUICK_VOLATILE ) &&
382 if ( $counter ===
false ) {
383 throw new RuntimeException(
'Unable to set value to ' . get_class(
$cache ) );
388 if ( $counter ===
null ) {
389 $path = $this->tmpDir .
'/' . self::FILE_PREFIX .
'-' . rawurlencode( $bucket ) .
'-48';
391 if ( isset( $this->fileHandles[
$path] ) ) {
392 $handle = $this->fileHandles[
$path];
394 $handle = fopen(
$path,
'cb+' );
395 $this->fileHandles[
$path] = $handle ?:
null;
398 if ( $handle ===
false ) {
399 throw new RuntimeException(
"Could not open '{$path}'." );
401 if ( !flock( $handle, LOCK_EX ) ) {
403 throw new RuntimeException(
"Could not acquire '{$path}'." );
407 $counter = floor( (
float)trim( fgets( $handle ) ) ) + $count;
409 ftruncate( $handle, 0 );
411 fwrite( $handle, fmod( $counter, 2 ** 48 ) );
414 flock( $handle, LOCK_UN );
418 $divisor = 2 ** $bits;
419 $currentId = floor( $counter - $count );
420 for ( $i = 0; $i < $count; ++$i ) {
421 $ids[] = fmod( ++$currentId, $divisor );
444 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
446 if ( isset( $this->fileHandles[$lockFile] ) ) {
447 $handle = $this->fileHandles[$lockFile];
449 $handle = fopen( $this->$lockFile,
'cb+' );
450 $this->fileHandles[$lockFile] = $handle ?:
null;
453 if ( $handle ===
false ) {
454 throw new RuntimeException(
"Could not open '{$this->$lockFile}'." );
456 if ( !flock( $handle, LOCK_EX ) ) {
458 throw new RuntimeException(
"Could not acquire '{$this->$lockFile}'." );
503 $msecCounterSize = $counterSize * 1000;
508 $data = explode(
' ', fgets( $handle ) );
510 if ( count( $data ) === 4 ) {
512 $clkSeq = (int)$data[0] % $clockSeqSize;
513 $prevSec = (int)$data[1];
516 $randOffset = (int)$data[3] % $counterSize;
523 if ( $sec ===
false ) {
527 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
529 $randOffset = mt_rand( 0, $offsetSize - 1 );
530 trigger_error(
"Clock was set back; sequence number incremented." );
531 } elseif ( $sec === $prevSec ) {
534 $msecCounter = (int)$data[2] % $msecCounterSize;
536 if ( ++$msecCounter >= $msecCounterSize ) {
538 flock( $handle, LOCK_UN );
539 throw new RuntimeException(
"Counter overflow for timestamp value." );
544 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
547 $randOffset = mt_rand( 0, $offsetSize - 1 );
551 ftruncate( $handle, 0 );
553 fwrite( $handle,
"{$clkSeq} {$sec} {$msecCounter} {$randOffset}" );
555 flock( $handle, LOCK_UN );
558 $msec = (int)( $msecCounter / 1000 );
559 $counter = $msecCounter % 1000;
562 'time' => [ $sec, $msec ],
563 'counter' => $counter,
565 'offset' => $randOffset,
566 'offsetCounter' => $counter + $randOffset,
578 $start = microtime(
true );
582 if ( $ct >= $time ) {
586 }
while ( ( microtime(
true ) - $start ) <= 0.010 );
597 list( $sec, $msec ) = $time;
598 $ts = 1000 * $sec + $msec;
599 if ( $ts > 2 ** 52 ) {
600 throw new RuntimeException( __METHOD__ .
601 ': sorry, this function doesn\'t work after the year 144680' );
604 return substr( \
Wikimedia\base_convert( $ts, 10, 2, 46 ), -46 );
614 list( $sec, $msec ) = $time;
615 $offset =
'122192928000000000';
616 if ( PHP_INT_SIZE >= 8 ) {
617 $ts = ( 1000 * $sec + $msec ) * 10000 + (
int)$offset + $delta;
618 $id_bin = str_pad( decbin( $ts % ( 2 ** 60 ) ), 60,
'0', STR_PAD_LEFT );
619 } elseif ( extension_loaded(
'gmp' ) ) {
620 $ts = gmp_add( gmp_mul( (
string)$sec,
'1000' ), (
string)$msec );
621 $ts = gmp_add( gmp_mul( $ts,
'10000' ), $offset );
622 $ts = gmp_add( $ts, (
string)$delta );
623 $ts = gmp_mod( $ts, gmp_pow(
'2',
'60' ) );
624 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60,
'0', STR_PAD_LEFT );
625 } elseif ( extension_loaded(
'bcmath' ) ) {
626 $ts = bcadd( bcmul( $sec, 1000 ), $msec );
627 $ts = bcadd( bcmul( $ts, 10000 ), $offset );
628 $ts = bcadd( $ts, $delta );
629 $ts = bcmod( $ts, bcpow( 2, 60 ) );
630 $id_bin = \Wikimedia\base_convert( $ts, 10, 2, 60 );
632 throw new RuntimeException(
'bcmath or gmp extension required for 32 bit machines.' );
641 if ( $this->loaded ) {
645 $this->loaded =
true;
648 if ( is_file( $this->nodeIdFile ) ) {
649 $nodeId = file_get_contents( $this->nodeIdFile );
652 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
653 AtEase::suppressWarnings();
654 if ( PHP_OS_FAMILY ===
'Windows' ) {
656 $csv = trim( ( $this->shellCallback )(
'getmac /NH /FO CSV' ) );
657 $line = substr( $csv, 0, strcspn( $csv,
"\n" ) );
658 $info = str_getcsv(
$line );
659 $nodeId = isset( $info[0] ) ? str_replace(
'-',
'', $info[0] ) :
'';
660 } elseif ( is_executable(
'/sbin/ifconfig' ) ) {
663 preg_match(
'/\s([0-9a-f]{2}(?::[0-9a-f]{2}){5})\s/',
664 ( $this->shellCallback )(
'/sbin/ifconfig -a' ), $m );
665 $nodeId = isset( $m[1] ) ? str_replace(
':',
'', $m[1] ) :
'';
667 AtEase::restoreWarnings();
668 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
669 $nodeId = bin2hex( random_bytes( 12 / 2 ) );
670 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 );
672 file_put_contents( $this->nodeIdFile, $nodeId );
674 $this->nodeId32 = \Wikimedia\base_convert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
675 $this->nodeId48 = \Wikimedia\base_convert( $nodeId, 16, 2, 48 );
708 foreach ( $this->fileHandles as
$path => $handle ) {
709 if ( $handle !==
null ) {
712 if ( is_file(
$path ) ) {
715 unset( $this->fileHandles[
$path] );
717 if ( is_file( $this->nodeIdFile ) ) {
718 unlink( $this->nodeIdFile );
739 array_map(
'fclose', array_filter( $this->fileHandles ) );
Class representing a cache/ephemeral data store.
incrWithInit( $key, $exptime, $value=1, $init=null, $flags=0)
Increase the value of the given key (no TTL change) if it exists or create it otherwise.
A BagOStuff object with no objects in it.