forked from symfony/lock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lock.php
275 lines (240 loc) · 8.93 KB
/
Lock.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Lock;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use Symfony\Component\Lock\Exception\InvalidArgumentException;
use Symfony\Component\Lock\Exception\LockAcquiringException;
use Symfony\Component\Lock\Exception\LockConflictedException;
use Symfony\Component\Lock\Exception\LockExpiredException;
use Symfony\Component\Lock\Exception\LockReleasingException;
/**
* Lock is the default implementation of the LockInterface.
*
* @author Jérémy Derussé <[email protected]>
*/
final class Lock implements SharedLockInterface, LoggerAwareInterface
{
use LoggerAwareTrait;
private $store;
private $key;
private $ttl;
private $autoRelease;
private $dirty = false;
/**
* @param float|null $ttl Maximum expected lock duration in seconds
* @param bool $autoRelease Whether to automatically release the lock or not when the lock instance is destroyed
*/
public function __construct(Key $key, PersistingStoreInterface $store, float $ttl = null, bool $autoRelease = true)
{
$this->store = $store;
$this->key = $key;
$this->ttl = $ttl;
$this->autoRelease = $autoRelease;
$this->logger = new NullLogger();
}
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
/**
* Automatically releases the underlying lock when the object is destructed.
*/
public function __destruct()
{
if (!$this->autoRelease || !$this->dirty || !$this->isAcquired()) {
return;
}
$this->release();
}
/**
* {@inheritdoc}
*/
public function acquire(bool $blocking = false): bool
{
$this->key->resetLifetime();
try {
if ($blocking) {
if (!$this->store instanceof BlockingStoreInterface) {
while (true) {
try {
$this->store->save($this->key);
break;
} catch (LockConflictedException $e) {
usleep((100 + random_int(-10, 10)) * 1000);
}
}
} else {
$this->store->waitAndSave($this->key);
}
} else {
$this->store->save($this->key);
}
$this->dirty = true;
$this->logger->debug('Successfully acquired the "{resource}" lock.', ['resource' => $this->key]);
if ($this->ttl) {
$this->refresh();
}
if ($this->key->isExpired()) {
try {
$this->release();
} catch (\Exception $e) {
// swallow exception to not hide the original issue
}
throw new LockExpiredException(sprintf('Failed to store the "%s" lock.', $this->key));
}
return true;
} catch (LockConflictedException $e) {
$this->dirty = false;
$this->logger->info('Failed to acquire the "{resource}" lock. Someone else already acquired the lock.', ['resource' => $this->key]);
if ($blocking) {
throw $e;
}
return false;
} catch (\Exception $e) {
$this->logger->notice('Failed to acquire the "{resource}" lock.', ['resource' => $this->key, 'exception' => $e]);
throw new LockAcquiringException(sprintf('Failed to acquire the "%s" lock.', $this->key), 0, $e);
}
}
/**
* {@inheritdoc}
*/
public function acquireRead(bool $blocking = false): bool
{
$this->key->resetLifetime();
try {
if (!$this->store instanceof SharedLockStoreInterface) {
$this->logger->debug('Store does not support ReadLocks, fallback to WriteLock.', ['resource' => $this->key]);
return $this->acquire($blocking);
}
if ($blocking) {
if (!$this->store instanceof BlockingSharedLockStoreInterface) {
while (true) {
try {
$this->store->saveRead($this->key);
break;
} catch (LockConflictedException $e) {
usleep((100 + random_int(-10, 10)) * 1000);
}
}
} else {
$this->store->waitAndSaveRead($this->key);
}
} else {
$this->store->saveRead($this->key);
}
$this->dirty = true;
$this->logger->debug('Successfully acquired the "{resource}" lock for reading.', ['resource' => $this->key]);
if ($this->ttl) {
$this->refresh();
}
if ($this->key->isExpired()) {
try {
$this->release();
} catch (\Exception $e) {
// swallow exception to not hide the original issue
}
throw new LockExpiredException(sprintf('Failed to store the "%s" lock.', $this->key));
}
return true;
} catch (LockConflictedException $e) {
$this->dirty = false;
$this->logger->info('Failed to acquire the "{resource}" lock. Someone else already acquired the lock.', ['resource' => $this->key]);
if ($blocking) {
throw $e;
}
return false;
} catch (\Exception $e) {
$this->logger->notice('Failed to acquire the "{resource}" lock.', ['resource' => $this->key, 'exception' => $e]);
throw new LockAcquiringException(sprintf('Failed to acquire the "%s" lock.', $this->key), 0, $e);
}
}
/**
* {@inheritdoc}
*/
public function refresh(float $ttl = null)
{
if (null === $ttl) {
$ttl = $this->ttl;
}
if (!$ttl) {
throw new InvalidArgumentException('You have to define an expiration duration.');
}
try {
$this->key->resetLifetime();
$this->store->putOffExpiration($this->key, $ttl);
$this->dirty = true;
if ($this->key->isExpired()) {
try {
$this->release();
} catch (\Exception $e) {
// swallow exception to not hide the original issue
}
throw new LockExpiredException(sprintf('Failed to put off the expiration of the "%s" lock within the specified time.', $this->key));
}
$this->logger->debug('Expiration defined for "{resource}" lock for "{ttl}" seconds.', ['resource' => $this->key, 'ttl' => $ttl]);
} catch (LockConflictedException $e) {
$this->dirty = false;
$this->logger->notice('Failed to define an expiration for the "{resource}" lock, someone else acquired the lock.', ['resource' => $this->key]);
throw $e;
} catch (\Exception $e) {
$this->logger->notice('Failed to define an expiration for the "{resource}" lock.', ['resource' => $this->key, 'exception' => $e]);
throw new LockAcquiringException(sprintf('Failed to define an expiration for the "%s" lock.', $this->key), 0, $e);
}
}
/**
* {@inheritdoc}
*/
public function isAcquired(): bool
{
return $this->dirty = $this->store->exists($this->key);
}
/**
* {@inheritdoc}
*/
public function release()
{
try {
try {
$this->store->delete($this->key);
$this->dirty = false;
} catch (LockReleasingException $e) {
throw $e;
} catch (\Exception $e) {
throw new LockReleasingException(sprintf('Failed to release the "%s" lock.', $this->key), 0, $e);
}
if ($this->store->exists($this->key)) {
throw new LockReleasingException(sprintf('Failed to release the "%s" lock, the resource is still locked.', $this->key));
}
} catch (LockReleasingException $e) {
$this->logger->notice('Failed to release the "{resource}" lock.', ['resource' => $this->key]);
throw $e;
}
}
/**
* {@inheritdoc}
*/
public function isExpired(): bool
{
return $this->key->isExpired();
}
/**
* {@inheritdoc}
*/
public function getRemainingLifetime(): ?float
{
return $this->key->getRemainingLifetime();
}
}