| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\RequestTimeout\Detail; |
| 4 |
|
| 5 |
use Wikimedia\RequestTimeout\RequestTimeout; |
| 6 |
|
| 7 |
/** |
| 8 |
* A fallback implementation used when Excimer is not available |
| 9 |
*/ |
| 10 |
class BasicRequestTimeout extends RequestTimeout { |
| 11 |
/** @var float */ |
| 12 |
private $limit; |
| 13 |
|
| 14 |
/** @var float */ |
| 15 |
private $startTime; |
| 16 |
|
| 17 |
/** @var int The next critical section ID to use */ |
| 18 |
private $nextCriticalId = 1; |
| 19 |
|
| 20 |
public function enterCriticalSection( $name, $emergencyLimit, $emergencyCallback ) { |
| 21 |
return $this->nextCriticalId++; |
| 22 |
} |
| 23 |
|
| 24 |
public function exitCriticalSection( $id ) { |
| 25 |
} |
| 26 |
|
| 27 |
/** |
| 28 |
* Get the elapsed CPU time. This can be used to estimate when the time |
| 29 |
* limit will expire. |
| 30 |
* |
| 31 |
* @return float |
| 32 |
*/ |
| 33 |
private function getCpuTime() { |
| 34 |
$r = getrusage(); |
| 35 |
return $r['ru_utime.tv_sec'] + $r['ru_stime.tv_sec'] |
| 36 |
+ ( $r['ru_utime.tv_usec'] + $r['ru_stime.tv_usec'] ) * 1e-6; |
| 37 |
} |
| 38 |
|
| 39 |
public function setWallTimeLimit( $limit ) { |
| 40 |
if ( $limit === INF ) { |
| 41 |
$limit = 0; |
| 42 |
} |
| 43 |
$this->limit = ceil( $limit ); |
| 44 |
$this->startTime = $this->getCpuTime(); |
| 45 |
set_time_limit( $this->limit ); |
| 46 |
} |
| 47 |
|
| 48 |
public function getWallTimeRemaining() { |
| 49 |
if ( $this->startTime !== null && $this->limit > 0 ) { |
| 50 |
return $this->limit - $this->getCpuTime() + $this->startTime; |
| 51 |
} else { |
| 52 |
return INF; |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
public function getWallTimeLimit() { |
| 57 |
if ( $this->limit > 0 ) { |
| 58 |
return $this->limit; |
| 59 |
} else { |
| 60 |
return INF; |
| 61 |
} |
| 62 |
} |
| 63 |
} |