Skip to content

Commit

Permalink
Merge pull request #8006 from vanilla/feature/Add-Cachelock-BaseModel
Browse files Browse the repository at this point in the history
Implement Mutual exclusion functionality on the Vanilla's Base Model
  • Loading branch information
cchabilall83 committed Nov 20, 2018
2 parents 3bd428e + cec492f commit e09fbb0
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions library/core/class.model.php
Original file line number Diff line number Diff line change
Expand Up @@ -961,4 +961,49 @@ public static function editContentTimeout($data, &$timeLeft = 0) {

return $canEdit;
}

/**
* Locks a resource so that it can only be accessed one at a time.
*
* @param string $lockKey Cache key to be assigned.
* @param int $gracePeriod Period of time the key will stay valid.
* @return bool Whether a master key has been assigned.
*/
protected static function buildCacheLock(string $lockKey, int $gracePeriod = 60): bool {
// If caching isn't enabled bail out
$cacheEnabled = Gdn_Cache::activeEnabled();
if (!$cacheEnabled) {
return true;
}

/**
* Attempt to add lock using our process ID. A failure likely means the
* cache key already exists, which would mean the lock is already in place.
*/
$instanceKey = getmypid();
$added = Gdn::cache()->add($lockKey, $instanceKey, [
Gdn_Cache::FEATURE_EXPIRY => $gracePeriod
]);
if ($added) {
return true;
} else {
return ($instanceKey === Gdn::cache()->get($lockKey));
}
}

/**
* Releases a locked resource so that it can be used again.
*
* @param string $lockKey Cache key to be assigned.
* @return bool Whether a master key has been released.
*/
protected function releaseCacheLock(string $lockKey): bool {
// If caching isn't enabled bail out
$cacheEnabled = Gdn_Cache::activeEnabled();
if (!$cacheEnabled) {
return true;
}
$keyReleased = Gdn::cache()->remove($lockKey);
return $keyReleased;
}
}

0 comments on commit e09fbb0

Please sign in to comment.