Skip to content

Commit

Permalink
MDL-41106 Cleaning up expired elements in session cache store
Browse files Browse the repository at this point in the history
- Always make sure the elements in cache are sorted so we need to remove only elements in the beginning of array
- Remove expired elements from session store to free memory
- Minor bug fixes

Conflicts:
	cache/stores/session/lib.php
	cache/stores/session/tests/session_test.php
  • Loading branch information
marinaglancy authored and Sam Hemelryk committed Aug 18, 2013
1 parent a0933c5 commit 4e9ccab
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion cache/stores/session/lib.php
Expand Up @@ -192,6 +192,7 @@ public function initialise(cache_definition $definition) {
$this->storeid = $definition->generate_definition_hash();
$this->store = &self::register_store_id($definition->get_id());
$this->ttl = $definition->get_ttl();
$this->check_ttl();
}

/**
Expand Down Expand Up @@ -223,6 +224,9 @@ public function get($key) {
return $this->store[$key][0];
} else if ($this->store[$key][1] >= (cache::now() - $this->ttl)) {
return $this->store[$key][0];
} else {
// Element is present but has expired.
$this->check_ttl();
}
}
return false;
Expand All @@ -244,16 +248,23 @@ public function get_many($keys) {
$maxtime = cache::now() - $this->ttl;
}

$hasexpiredelements = false;
foreach ($keys as $key) {
$return[$key] = false;
if (isset($this->store[$key])) {
if ($this->ttl == 0) {
$return[$key] = $this->store[$key][0];
} else if ($this->store[$key][1] >= $maxtime) {
$return[$key] = $this->store[$key][0];
} else {
$hasexpiredelements = true;
}
}
}
if ($hasexpiredelements) {
// There are some elements that are present but have expired.
$this->check_ttl();
}
return $return;
}

Expand All @@ -264,7 +275,7 @@ public function get_many($keys) {
* @param mixed $data The data to set.
* @return bool True if the operation was a success false otherwise.
*/
public function set($key, $data, $testmaxsize = true) {
public function set($key, $data) {
if ($this->ttl === 0) {
$this->store[$key] = array($data, 0);
} else {
Expand Down Expand Up @@ -432,12 +443,37 @@ public function my_name() {
return $this->name;
}

/**
* Removes expired elements.
* @return int number of removed elements
*/
protected function check_ttl() {
if ($this->ttl == 0) {
return 0;
}
$maxtime = cache::now() - $this->ttl;
$c = 0;
for ($value = reset($this->store); $value !== false; $value = next($this->store)) {
if ($value[1] >= $maxtime) {
// We know that elements are sorted by ttl so no need to continue;
break;
}
$c++;
}
if ($c) {
// Remove first $c elements as they are expired.
$this->store = array_slice($this->store, $c, null, true);
}
return $c;
}

/**
* Finds all of the keys being stored in the cache store instance.
*
* @return array
*/
public function find_all() {
$this->check_ttl();
return array_keys($this->store);
}

Expand Down

0 comments on commit 4e9ccab

Please sign in to comment.