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'];
146 $id_bin .= str_pad( decbin( $counter ), 10,
'0', STR_PAD_LEFT );
150 if ( strlen( $id_bin ) !== 88 ) {
151 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
172 Assert::parameterType(
'integer',
$base,
'$base' );
173 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
174 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
177 $info = $gen->getTimeAndDelay(
'lockFile128', 16384, 1048576, 1048576 );
178 $info[
'offsetCounter'] = $info[
'offsetCounter'] % 1048576;
180 return Wikimedia\base_convert( $gen->getTimestampedID128( $info ), 2,
$base );
190 if ( isset( $info[
'time'] ) ) {
191 $time = $info[
'time'];
192 $counter = $info[
'offsetCounter'];
193 $clkSeq = $info[
'clkSeq'];
202 $id_bin .= str_pad( decbin( $counter ), 20,
'0', STR_PAD_LEFT );
204 $id_bin .= str_pad( decbin( $clkSeq ), 14,
'0', STR_PAD_LEFT );
208 if ( strlen( $id_bin ) !== 128 ) {
209 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
227 return $gen->getUUIDv1( $gen->getTimeAndDelay(
'lockFileUUID', 16384, 5000, 5001 ) );
238 return str_replace(
'-',
'', self::newUUIDv1() );
246 $clkSeq_bin = Wikimedia\base_convert( $info[
'clkSeq'], 10, 2, 14 );
249 $id_bin = substr( $time_bin, 28, 32 );
251 $id_bin .= substr( $time_bin, 12, 16 );
255 $id_bin .= substr( $time_bin, 0, 12 );
259 $id_bin .= substr( $clkSeq_bin, 0, 6 );
261 $id_bin .= substr( $clkSeq_bin, 6, 8 );
265 if ( strlen( $id_bin ) !== 128 ) {
266 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
268 $hex = Wikimedia\base_convert( $id_bin, 2, 16, 32 );
269 return sprintf(
'%s-%s-%s-%s-%s',
271 substr( $hex, 0, 8 ),
273 substr( $hex, 8, 4 ),
275 substr( $hex, 12, 4 ),
277 substr( $hex, 16, 4 ),
279 substr( $hex, 20, 12 )
295 return sprintf(
'%s-%s-%s-%s-%s',
297 substr( $hex, 0, 8 ),
299 substr( $hex, 8, 4 ),
301 '4' . substr( $hex, 12, 3 ),
303 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
305 substr( $hex, 19, 12 )
317 return str_replace(
'-',
'', self::newUUIDv4( $flags ) );
333 return current( self::newSequentialPerNodeIDs( $bucket, $bits, 1, $flags ) );
349 return $gen->getSequentialPerNodeIDs( $bucket, $bits, $count, $flags );
367 if ( $bits < 16 || $bits > 48 ) {
368 throw new RuntimeException(
"Requested bit size ($bits) is out of range." );
376 if ( ( $flags & self::QUICK_VOLATILE ) && !
wfIsCLI() ) {
377 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
380 $counter =
$cache->incrWithInit( $bucket, $cache::TTL_INDEFINITE, $count, $count );
381 if ( $counter ===
false ) {
382 throw new RuntimeException(
'Unable to set value to ' . get_class(
$cache ) );
387 if ( $counter ===
null ) {
388 $path =
wfTempDir() .
'/mw-' . __CLASS__ .
'-' . rawurlencode( $bucket ) .
'-48';
390 if ( isset( $this->fileHandles[$path] ) ) {
391 $handle = $this->fileHandles[
$path];
393 $handle = fopen( $path,
'cb+' );
394 $this->fileHandles[
$path] = $handle ?:
null;
397 if ( $handle ===
false ) {
398 throw new RuntimeException(
"Could not open '{$path}'." );
400 if ( !flock( $handle, LOCK_EX ) ) {
402 throw new RuntimeException(
"Could not acquire '{$path}'." );
406 $counter = floor( trim( fgets( $handle ) ) ) + $count;
408 ftruncate( $handle, 0 );
410 fwrite( $handle, fmod( $counter, 2 ** 48 ) );
413 flock( $handle, LOCK_UN );
417 $divisor = 2 ** $bits;
418 $currentId = floor( $counter - $count );
419 for ( $i = 0; $i < $count; ++$i ) {
420 $ids[] = fmod( ++$currentId, $divisor );
443 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
445 if ( isset( $this->fileHandles[$lockFile] ) ) {
446 $handle = $this->fileHandles[$lockFile];
448 $handle = fopen( $this->$lockFile,
'cb+' );
449 $this->fileHandles[$lockFile] = $handle ?:
null;
452 if ( $handle ===
false ) {
453 throw new RuntimeException(
"Could not open '{$this->$lockFile}'." );
455 if ( !flock( $handle, LOCK_EX ) ) {
457 throw new RuntimeException(
"Could not acquire '{$this->$lockFile}'." );
502 $msecCounterSize = $counterSize * 1000;
507 $data = explode(
' ', fgets( $handle ) );
509 if ( count( $data ) === 4 ) {
511 $clkSeq = (int)$data[0] % $clockSeqSize;
512 $prevSec = (int)$data[1];
515 $randOffset = (int)$data[3] % $counterSize;
522 if ( $sec ===
false ) {
526 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
528 $randOffset = mt_rand( 0, $offsetSize - 1 );
529 trigger_error(
"Clock was set back; sequence number incremented." );
530 } elseif ( $sec === $prevSec ) {
533 $msecCounter = (int)$data[2] % $msecCounterSize;
535 if ( ++$msecCounter >= $msecCounterSize ) {
537 flock( $handle, LOCK_UN );
538 throw new RuntimeException(
"Counter overflow for timestamp value." );
543 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
546 $randOffset = mt_rand( 0, $offsetSize - 1 );
550 ftruncate( $handle, 0 );
552 fwrite( $handle,
"{$clkSeq} {$sec} {$msecCounter} {$randOffset}" );
554 flock( $handle, LOCK_UN );
557 $msec = (int)( $msecCounter / 1000 );
558 $counter = $msecCounter % 1000;
561 'time' => [ $sec, $msec ],
562 'counter' => $counter,
564 'offset' => $randOffset,
565 'offsetCounter' => $counter + $randOffset,
577 $start = microtime(
true );
581 if ( $ct >=
$time ) {
585 }
while ( ( microtime(
true ) - $start ) <= 0.010 );
597 $ts = 1000 * $sec + $msec;
598 if ( $ts > 2 ** 52 ) {
599 throw new RuntimeException( __METHOD__ .
600 ': sorry, this function doesn\'t work after the year 144680' );
603 return substr(
Wikimedia\base_convert( $ts, 10, 2, 46 ), -46 );
614 $offset =
'122192928000000000';
615 if ( PHP_INT_SIZE >= 8 ) {
616 $ts = ( 1000 * $sec + $msec ) * 10000 + (
int)$offset + $delta;
617 $id_bin = str_pad( decbin( $ts % ( 2 ** 60 ) ), 60,
'0', STR_PAD_LEFT );
618 } elseif ( extension_loaded(
'gmp' ) ) {
619 $ts = gmp_add( gmp_mul( (
string)$sec,
'1000' ), (
string)$msec );
620 $ts = gmp_add( gmp_mul( $ts,
'10000' ), $offset );
621 $ts = gmp_add( $ts, (
string)$delta );
622 $ts = gmp_mod( $ts, gmp_pow(
'2',
'60' ) );
623 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60,
'0', STR_PAD_LEFT );
624 } elseif ( extension_loaded(
'bcmath' ) ) {
625 $ts = bcadd( bcmul( $sec, 1000 ), $msec );
626 $ts = bcadd( bcmul( $ts, 10000 ), $offset );
627 $ts = bcadd( $ts, $delta );
628 $ts = bcmod( $ts, bcpow( 2, 60 ) );
629 $id_bin = Wikimedia\base_convert( $ts, 10, 2, 60 );
631 throw new RuntimeException(
'bcmath or gmp extension required for 32 bit machines.' );
650 foreach ( $this->fileHandles as $path => $handle ) {
651 if ( $handle !==
null ) {
654 if ( is_file( $path ) ) {
657 unset( $this->fileHandles[$path] );
659 if ( is_file( $this->nodeIdFile ) ) {
660 unlink( $this->nodeIdFile );
680 $gen->deleteCacheFiles();
684 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.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
see documentation in includes Linker php for Linker::makeImageLink & $time
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))