|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Malkusch\Lock\Mutex; |
| 6 | + |
| 7 | +use Malkusch\Lock\Exception\LockAcquireException; |
| 8 | +use Malkusch\Lock\Exception\LockReleaseException; |
| 9 | +use Malkusch\Lock\Util\LockUtil; |
| 10 | +use Psr\Log\LoggerAwareInterface; |
| 11 | +use Psr\Log\LoggerAwareTrait; |
| 12 | +use Psr\Log\NullLogger; |
| 13 | + |
| 14 | +/** |
| 15 | + * Distributed mutex based on the Redlock algorithm. |
| 16 | + * |
| 17 | + * @template TClient of object |
| 18 | + * |
| 19 | + * @see http://redis.io/topics/distlock |
| 20 | + */ |
| 21 | +abstract class AbstractRedlockMutex extends AbstractSpinlockMutex implements LoggerAwareInterface |
| 22 | +{ |
| 23 | + use LoggerAwareTrait; |
| 24 | + |
| 25 | + /** @var string The random value token for key identification */ |
| 26 | + private $token; |
| 27 | + |
| 28 | + /** @var array<int, TClient> */ |
| 29 | + private $clients; |
| 30 | + |
| 31 | + /** |
| 32 | + * Sets the Redis APIs. |
| 33 | + * |
| 34 | + * The Redis APIs needs to be connected. I.e. Redis::connect() was |
| 35 | + * called already. |
| 36 | + * |
| 37 | + * @param array<int, TClient> $clients |
| 38 | + * @param float $timeout The timeout in seconds a lock expires |
| 39 | + * |
| 40 | + * @throws \LengthException The timeout must be greater than 0 |
| 41 | + */ |
| 42 | + public function __construct(array $clients, string $name, float $timeout = 3) |
| 43 | + { |
| 44 | + parent::__construct($name, $timeout); |
| 45 | + |
| 46 | + $this->clients = $clients; |
| 47 | + $this->logger = new NullLogger(); |
| 48 | + } |
| 49 | + |
| 50 | + #[\Override] |
| 51 | + protected function acquire(string $key, float $expire): bool |
| 52 | + { |
| 53 | + // 1. This differs from the specification to avoid an overflow on 32-Bit systems. |
| 54 | + $time = microtime(true); |
| 55 | + |
| 56 | + // 2. |
| 57 | + $acquired = 0; |
| 58 | + $errored = 0; |
| 59 | + $this->token = LockUtil::getInstance()->makeRandomToken(); |
| 60 | + $exception = null; |
| 61 | + foreach ($this->clients as $index => $client) { |
| 62 | + try { |
| 63 | + if ($this->add($client, $key, $this->token, $expire)) { |
| 64 | + ++$acquired; |
| 65 | + } |
| 66 | + } catch (LockAcquireException $exception) { |
| 67 | + // todo if there is only one redis server, throw immediately. |
| 68 | + $context = [ |
| 69 | + 'key' => $key, |
| 70 | + 'index' => $index, |
| 71 | + 'token' => $this->token, |
| 72 | + 'exception' => $exception, |
| 73 | + ]; |
| 74 | + $this->logger->warning('Could not set {key} = {token} at server #{index}', $context); |
| 75 | + |
| 76 | + ++$errored; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + // 3. |
| 81 | + $elapsedTime = microtime(true) - $time; |
| 82 | + $isAcquired = $this->isMajority($acquired) && $elapsedTime <= $expire; |
| 83 | + |
| 84 | + if ($isAcquired) { |
| 85 | + // 4. |
| 86 | + return true; |
| 87 | + } |
| 88 | + |
| 89 | + // 5. |
| 90 | + $this->release($key); |
| 91 | + |
| 92 | + // In addition to RedLock it's an exception if too many servers fail. |
| 93 | + if (!$this->isMajority(count($this->clients) - $errored)) { |
| 94 | + assert($exception !== null); // The last exception for some context. |
| 95 | + |
| 96 | + throw new LockAcquireException( |
| 97 | + 'It\'s not possible to acquire a lock because at least half of the Redis server are not available', |
| 98 | + LockAcquireException::REDIS_NOT_ENOUGH_SERVERS, |
| 99 | + $exception |
| 100 | + ); |
| 101 | + } |
| 102 | + |
| 103 | + return false; |
| 104 | + } |
| 105 | + |
| 106 | + #[\Override] |
| 107 | + protected function release(string $key): bool |
| 108 | + { |
| 109 | + /* |
| 110 | + * All Redis commands must be analyzed before execution to determine which keys the command will operate on. In |
| 111 | + * order for this to be true for EVAL, keys must be passed explicitly. |
| 112 | + * |
| 113 | + * @link https://redis.io/commands/set |
| 114 | + */ |
| 115 | + $script = 'if redis.call("get", KEYS[1]) == ARGV[1] then |
| 116 | + return redis.call("del", KEYS[1]) |
| 117 | + else |
| 118 | + return 0 |
| 119 | + end |
| 120 | + '; |
| 121 | + $released = 0; |
| 122 | + foreach ($this->clients as $index => $client) { |
| 123 | + try { |
| 124 | + if ($this->evalScript($client, $script, 1, [$key, $this->token])) { |
| 125 | + ++$released; |
| 126 | + } |
| 127 | + } catch (LockReleaseException $e) { |
| 128 | + // todo throw if there is only one redis server |
| 129 | + $context = [ |
| 130 | + 'key' => $key, |
| 131 | + 'index' => $index, |
| 132 | + 'token' => $this->token, |
| 133 | + 'exception' => $e, |
| 134 | + ]; |
| 135 | + $this->logger->warning('Could not unset {key} = {token} at server #{index}', $context); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + return $this->isMajority($released); |
| 140 | + } |
| 141 | + |
| 142 | + /** |
| 143 | + * Returns if a count is the majority of all servers. |
| 144 | + * |
| 145 | + * @return bool True if the count is the majority |
| 146 | + */ |
| 147 | + private function isMajority(int $count): bool |
| 148 | + { |
| 149 | + return $count > count($this->clients) / 2; |
| 150 | + } |
| 151 | + |
| 152 | + /** |
| 153 | + * Sets the key only if such key doesn't exist at the server yet. |
| 154 | + * |
| 155 | + * @param TClient $client |
| 156 | + * @param float $expire The TTL seconds |
| 157 | + * |
| 158 | + * @return bool True if the key was set |
| 159 | + */ |
| 160 | + abstract protected function add($client, string $key, string $value, float $expire): bool; |
| 161 | + |
| 162 | + /** |
| 163 | + * @param TClient $client |
| 164 | + * @param string $script The Lua script |
| 165 | + * @param int $numkeys The number of values in $arguments that represent Redis key names |
| 166 | + * @param list<mixed> $arguments Keys and values |
| 167 | + * |
| 168 | + * @return mixed The script result, or false if executing failed |
| 169 | + * |
| 170 | + * @throws LockReleaseException An unexpected error happened |
| 171 | + */ |
| 172 | + abstract protected function evalScript($client, string $script, int $numkeys, array $arguments); |
| 173 | +} |
0 commit comments