Concurrency::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 1
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 1
rs 10
1
<?php declare(strict_types=1);
2
3
/**
4
 * ownCloud - Music app
5
 *
6
 * This file is licensed under the Affero General Public License version 3 or
7
 * later. See the COPYING file.
8
 *
9
 * @author Pauli Järvinen <[email protected]>
10
 * @copyright Pauli Järvinen 2026
11
 */
12
13
namespace OCA\Music\Utility;
14
15
use OCA\Music\AppFramework\Core\Logger;
16
use OCA\Music\Db\Cache;
17
18
class Concurrency {
19
	private const SEMAPHORE_KEY_BASE = 0xa5e63947; // arbitrarily selected 32-bit base value
20
21
	public function __construct(private Cache $cache, private Logger $logger) {
22
	}
23
24
	public function mutexReserve(string $userId, string $key) : false|\SysvSemaphore {
25
		if (!\extension_loaded('sysvsem')) {
26
			$this->logger->warning('PHP extension sysvsem should be installed to guarantee correct behavior');
27
			return false;
28
		}
29
30
		$mutexKey = self::SEMAPHORE_KEY_BASE + $this->cache->forcedGetId($userId, "mutex_key.$key");
31
		$mutex = \sem_get($mutexKey);
32
33
		if ($mutex !== false) {
34
			\sem_acquire($mutex);
35
		} else {
36
			$this->logger->warning('Failed to acquire the semaphore');
37
		}
38
39
		return $mutex;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $mutex could return the type resource which is incompatible with the type-hinted return SysvSemaphore|false. Consider adding an additional type-check to rule them out.
Loading history...
40
	}
41
42
	public function mutexRelease(false|\SysvSemaphore $mutex) : void {
43
		if ($mutex !== false) {
44
			\sem_release($mutex);
45
		}
46
	}
47
}