-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathDistributedMutexTest.php
374 lines (326 loc) · 12 KB
/
DistributedMutexTest.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
<?php
declare(strict_types=1);
namespace Malkusch\Lock\Tests\Mutex;
use Malkusch\Lock\Exception\LockAcquireException;
use Malkusch\Lock\Exception\LockAcquireTimeoutException;
use Malkusch\Lock\Exception\LockReleaseException;
use Malkusch\Lock\Exception\MutexException;
use Malkusch\Lock\Mutex\AbstractSpinlockMutex;
use Malkusch\Lock\Mutex\AbstractSpinlockWithTokenMutex;
use Malkusch\Lock\Mutex\DistributedMutex;
use Malkusch\Lock\Util\LockUtil;
use phpmock\environment\SleepEnvironmentBuilder;
use phpmock\MockEnabledException;
use phpmock\phpunit\PHPMock;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Predis\PredisException;
use Psr\Log\LoggerInterface;
class DistributedMutexTest extends TestCase
{
use PHPMock;
#[\Override]
protected function setUp(): void
{
parent::setUp();
$sleepBuilder = new SleepEnvironmentBuilder();
$sleepBuilder->addNamespace(__NAMESPACE__);
$sleepBuilder->addNamespace('Malkusch\Lock\Mutex');
$sleepBuilder->addNamespace('Malkusch\Lock\Util');
$sleep = $sleepBuilder->build();
try {
$sleep->enable();
$this->registerForTearDown($sleep);
} catch (MockEnabledException $e) {
// workaround for burn testing
\assert($e->getMessage() === 'microtime is already enabled. Call disable() on the existing mock.');
}
}
/**
* @param int $count The amount of redis APIs
*
* @return DistributedMutex&MockObject
*/
private function createDistributedMutexMock(int $count, float $acquireTimeout = 1, float $expireTimeout = \INF): DistributedMutex
{
$mutexes = array_map(
function (int $i) {
$mutex = $this->getMockBuilder(AbstractSpinlockWithTokenMutex::class)
->setConstructorArgs(['test', \INF])
->onlyMethods(['acquireWithToken', 'releaseWithToken'])
->getMock();
$mutex
->method('acquireWithToken')
->with(self::anything(), \INF)
->willReturn('x' . $i);
$mutex
->method('releaseWithToken')
->with(self::anything(), 'x' . $i)
->willReturn(true);
return $mutex;
},
range(0, $count - 1)
);
return $this->getMockBuilder(DistributedMutex::class)
->setConstructorArgs([$mutexes, $acquireTimeout, $expireTimeout])
->onlyMethods(['acquireMutex', 'releaseMutex'])
->getMock();
}
/**
* Tests acquire() fails because too few servers are available.
*
* @param int $count The total count of servers
* @param int $available The count of available servers
*
* @dataProvider provideMinorityCases
*/
#[DataProvider('provideMinorityCases')]
public function testTooFewServerToAcquire(int $count, int $available): void
{
$mutex = $this->createDistributedMutexMock($count);
$i = 0;
$mutex->expects(self::atMost((int) floor($count / 2) + $count - $available))
->method('acquireMutex')
->willReturnCallback(static function () use (&$i, $available) {
if ($i++ < $available) {
return true;
}
throw new LockAcquireException();
});
$this->expectException(LockAcquireException::class);
$this->expectExceptionCode(MutexException::CODE_REDLOCK_NOT_ENOUGH_SERVERS);
$mutex->synchronized(static function () {
self::fail();
});
}
/**
* Tests synchronized() does work if the majority of servers is up.
*
* @param int $count The total count of servers
* @param int $available The count of available servers
*
* @dataProvider provideMajorityCases
*/
#[DataProvider('provideMajorityCases')]
public function testFaultTolerance(int $count, int $available): void
{
$mutex = $this->createDistributedMutexMock($count);
$mutex->expects(self::exactly($available))
->method('releaseMutex')
->willReturn(true);
$i = 0;
$mutex->expects(self::exactly($count))
->method('acquireMutex')
->willReturnCallback(static function () use (&$i, $available) {
if ($i++ < $available) {
return true;
}
throw new LockAcquireException();
});
$mutex->synchronized(static function () {});
}
/**
* Tests too few keys could be acquired.
*
* @param int $count The total count of servers
* @param int $available The count of available servers
*
* @dataProvider provideMinorityCases
*/
#[DataProvider('provideMinorityCases')]
public function testAcquireTooFewKeys(int $count, int $available): void
{
$mutex = $this->createDistributedMutexMock($count);
$i = 0;
$mutex->expects(self::any())
->method('acquireMutex')
->willReturnCallback(static function () use (&$i, $available) {
return ++$i <= $available;
});
$this->expectException(LockAcquireTimeoutException::class);
$this->expectExceptionMessage('Lock acquire timeout of 1.0 seconds has been exceeded');
$mutex->synchronized(static function () {
self::fail();
});
}
/**
* Tests acquiring keys takes too long.
*
* @param int $count The total count of servers
* @param float $timeout In seconds
* @param float $delay In seconds
*
* @dataProvider provideAcquireTimeoutsCases
*/
#[DataProvider('provideAcquireTimeoutsCases')]
public function testAcquireTimeouts(int $count, float $timeout, float $delay): void
{
$mutex = $this->createDistributedMutexMock($count, $timeout, $timeout);
$mutex->expects(self::exactly($count))
->method('releaseMutex')
->willReturn(true);
$mutex->expects(self::exactly($count))
->method('acquireMutex')
->willReturnCallback(static function () use ($delay) {
usleep((int) ($delay * 1e6));
return true;
});
$this->expectException(LockAcquireTimeoutException::class);
$this->expectExceptionMessage('Lock acquire timeout of ' . LockUtil::getInstance()->formatTimeout($timeout) . ' seconds has been exceeded');
$mutex->synchronized(static function () {
self::fail();
});
}
/**
* @return iterable<list<mixed>>
*/
public static function provideAcquireTimeoutsCases(): iterable
{
yield [1, 1.2, 1.201];
yield [2, 20.4, 10.201];
}
/**
* Tests synchronized() works if the majority of keys was acquired.
*
* @param int $count The total count of servers
* @param int $available The count of available servers
*
* @dataProvider provideMajorityCases
*/
#[DataProvider('provideMajorityCases')]
public function testAcquireWithMajority(int $count, int $available): void
{
$mutex = $this->createDistributedMutexMock($count);
$mutex->expects(self::exactly($available))
->method('releaseMutex')
->willReturn(true);
$i = 0;
$mutex->expects(self::exactly($count))
->method('acquireMutex')
->willReturnCallback(static function () use (&$i, $available) {
return ++$i <= $available;
});
$mutex->synchronized(static function () {});
}
/**
* Provides test cases with enough.
*
* @return iterable<list<mixed>>
*/
public static function provideMajorityCases(): iterable
{
yield [1, 1];
yield [2, 2];
yield [3, 2];
yield [3, 3];
yield [4, 3];
yield [5, 3];
}
/**
* Tests releasing fails because too few servers are available.
*
* @param int $count The total count of servers
* @param int $available The count of available servers
*
* @dataProvider provideMinorityCases
*/
#[DataProvider('provideMinorityCases')]
public function testTooFewServersToRelease(int $count, int $available): void
{
$mutex = $this->createDistributedMutexMock($count);
$mutex->expects(self::exactly($count))
->method('acquireMutex')
->willReturn(true);
$i = 0;
$mutex->expects(self::exactly($count))
->method('releaseMutex')
->willReturnCallback(static function () use (&$i, $available) {
if ($i++ < $available) {
return true;
}
throw new LockReleaseException();
});
$this->expectException(LockReleaseException::class);
$mutex->synchronized(static function () {});
}
/**
* Tests releasing too few keys.
*
* @param int $count The total count of servers
* @param int $available The count of available servers
*
* @dataProvider provideMinorityCases
*/
#[DataProvider('provideMinorityCases')]
public function testReleaseTooFewKeys(int $count, int $available): void
{
$mutex = $this->createDistributedMutexMock($count);
$mutex->expects(self::exactly($count))
->method('acquireMutex')
->willReturn(true);
$i = 0;
$mutex->expects(self::exactly($count))
->method('releaseMutex')
->willReturnCallback(static function () use (&$i, $available) {
return ++$i <= $available;
});
$this->expectException(LockReleaseException::class);
$mutex->synchronized(static function () {});
}
/**
* Provides test cases with too few.
*
* @return iterable<list<mixed>>
*/
public static function provideMinorityCases(): iterable
{
yield [1, 0];
yield [2, 0];
yield [2, 1];
yield [3, 0];
yield [3, 1];
yield [4, 0];
yield [4, 1];
yield [4, 2];
yield [5, 2];
yield [6, 2];
yield [6, 3];
}
public function testAcquireMutexLogger(): void
{
$mutex = $this->createDistributedMutexMock(3);
$logger = $this->createMock(LoggerInterface::class);
$mutex->setLogger($logger);
$mutex->expects(self::exactly(2))
->method('acquireMutex')
->with(self::isInstanceOf(AbstractSpinlockMutex::class), 'distributed', 1.0, \INF)
->willThrowException($this->createMock(/* PredisException::class */ LockAcquireException::class));
$logger->expects(self::exactly(2))
->method('warning')
->with('Could not set {key} = {token} at server #{index}', self::anything());
$this->expectException(LockAcquireException::class);
$this->expectExceptionMessage('It is not possible to acquire a lock because at least half of the servers are not available');
$mutex->synchronized(static function () {
self::fail();
});
}
public function testReleaseMutexLogger(): void
{
$mutex = $this->createDistributedMutexMock(3);
$logger = $this->createMock(LoggerInterface::class);
$mutex->setLogger($logger);
$mutex->expects(self::exactly(3))
->method('acquireMutex')
->willReturn(true);
$mutex->expects(self::exactly(3))
->method('releaseMutex')
->with(self::isInstanceOf(AbstractSpinlockMutex::class), 'distributed', \INF)
->willThrowException($this->createMock(/* PredisException::class */ LockReleaseException::class));
$logger->expects(self::exactly(3))
->method('warning')
->with('Could not unset {key} = {token} at server #{index}', self::anything());
$this->expectException(LockReleaseException::class);
$mutex->synchronized(static function () {});
}
}