Skip to content

Commit

Permalink
Configure memory eviction factor
Browse files Browse the repository at this point in the history
  • Loading branch information
Magomogo committed May 19, 2020
1 parent 9e0b5f2 commit 98b9e68
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
44 changes: 39 additions & 5 deletions src/Stash/Driver/Ephemeral.php
Expand Up @@ -43,9 +43,21 @@ class Ephemeral extends AbstractDriver
*/
protected $memoryLimit = 0;

/**
* How aggressive to perform eviction in case of memory limit violation.
* Should be positive float less than 1.
*
* @var float
*/
private $memoryLimitEvictionFactor;

public function getDefaultOptions()
{
return ['maxItems' => 0, 'memoryLimit' => 0];
return [
'maxItems' => 0,
'memoryLimit' => 0,
'memoryLimitEvictionFactor' => 0.25,
];
}

/**
Expand All @@ -60,6 +72,7 @@ protected function setOptions(array $options = array())

$this->maxItems = self::positiveIntegerOption($options, 'maxItems');
$this->memoryLimit = self::positiveIntegerOption($options, 'memoryLimit');
$this->memoryLimitEvictionFactor = self::factorOption($options, 'memoryLimitEvictionFactor');

if ($this->maxItems > 0 && count($this->store) > $this->maxItems) {
$this->evict(count($this->store) - $this->maxItems);
Expand Down Expand Up @@ -121,10 +134,12 @@ public function storeData($key, $data, $expiration)

if ($this->memoryLimit > 0) {
while (count($this->store) && memory_get_usage() > $this->memoryLimit) {
$numItemsToKeep = count($this->store) * .25;
$this->store = $numItemsToKeep > 10
? array_slice($this->store, $numItemsToKeep, null, true)
: [];
$offset = max(
ceil(count($this->store) * $this->memoryLimitEvictionFactor),
1
);

$this->store = array_slice($this->store, $offset, null, true);
}
}

Expand Down Expand Up @@ -183,4 +198,23 @@ protected static function positiveIntegerOption(array $options, $optionName)

return $optionValue;
}

/**
* @param array $options
* @param string $optionName
* @return int
* @throws Stash\Exception\InvalidArgumentException
*/
protected static function factorOption(array $options, $optionName)
{
$optionValue = $options[$optionName];

if (!is_float($optionValue) || $optionValue < 0 || $optionValue > 1) {
throw new Stash\Exception\InvalidArgumentException(
$optionName . ' must be a factor 0..1'
);
}

return $optionValue;
}
}
10 changes: 10 additions & 0 deletions tests/Stash/Test/Driver/EphemeralTest.php
Expand Up @@ -157,6 +157,16 @@ public function testSettingInvalidMemoryLimitThrows()
]);
}

/**
* @expectedException \Stash\Exception\InvalidArgumentException
*/
public function testSettingInvalidMemoryLimitEvictionFactorThrows()
{
new $this->driverClass([
'memoryLimitEvictionFactor' => 98,
]);
}

public function testEvictionCausedByMemoryLimit()
{
$expire = time() + 100;
Expand Down

0 comments on commit 98b9e68

Please sign in to comment.