|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors |
| 7 | + * SPDX-License-Identifier: AGPL-3.0-only |
| 8 | + */ |
| 9 | + |
| 10 | +namespace OC\Snowflake; |
| 11 | + |
| 12 | +use OCP\ITempManager; |
| 13 | +use Override; |
| 14 | + |
| 15 | +class FileSequence implements ISequence { |
| 16 | + /** Number of files to use */ |
| 17 | + private const NB_FILES = 20; |
| 18 | + /** Lock filename format **/ |
| 19 | + private const LOCK_FILE_FORMAT = 'seq-%03d.lock'; |
| 20 | + /** Delete sequences after SEQUENCE_TTL seconds **/ |
| 21 | + private const SEQUENCE_TTL = 30; |
| 22 | + |
| 23 | + private string $workDir; |
| 24 | + |
| 25 | + public function __construct( |
| 26 | + ITempManager $tempManager, |
| 27 | + ) { |
| 28 | + $this->workDir = $tempManager->getTemporaryFolder('.snowflakes'); |
| 29 | + } |
| 30 | + |
| 31 | + #[Override] |
| 32 | + public function isAvailable(): bool { |
| 33 | + return true; |
| 34 | + } |
| 35 | + |
| 36 | + #[Override] |
| 37 | + public function nextId(int $serverId, int $seconds, int $milliseconds): int { |
| 38 | + // Open lock file |
| 39 | + $filePath = $this->getFilePath($milliseconds % self::NB_FILES); |
| 40 | + $fp = fopen($filePath, 'c+'); |
| 41 | + if ($fp === false) { |
| 42 | + throw new \Exception('Unable to open sequence ID file: ' . $filePath); |
| 43 | + } |
| 44 | + if (!flock($fp, LOCK_EX)) { |
| 45 | + throw new \Exception('Unable to acquire lock on sequence ID file: ' . $filePath); |
| 46 | + } |
| 47 | + |
| 48 | + // Read content |
| 49 | + $content = (string)fgets($fp); |
| 50 | + $locks = $content === '' |
| 51 | + ? [] |
| 52 | + : json_decode($content, true, 3, JSON_THROW_ON_ERROR); |
| 53 | + |
| 54 | + // Generate new ID |
| 55 | + if (isset($locks[$seconds])) { |
| 56 | + if (isset($locks[$seconds][$milliseconds])) { |
| 57 | + ++$locks[$seconds][$milliseconds]; |
| 58 | + } else { |
| 59 | + $locks[$seconds][$milliseconds] = 0; |
| 60 | + } |
| 61 | + } else { |
| 62 | + $locks[$seconds] = [ |
| 63 | + $milliseconds => 0 |
| 64 | + ]; |
| 65 | + } |
| 66 | + |
| 67 | + // Clean old sequence IDs |
| 68 | + $cleanBefore = $seconds - self::SEQUENCE_TTL; |
| 69 | + $locks = array_filter($locks, static function ($key) use ($cleanBefore) { |
| 70 | + return $key >= $cleanBefore; |
| 71 | + }, ARRAY_FILTER_USE_KEY); |
| 72 | + |
| 73 | + // Write data |
| 74 | + ftruncate($fp, 0); |
| 75 | + $content = json_encode($locks, JSON_THROW_ON_ERROR); |
| 76 | + rewind($fp); |
| 77 | + fwrite($fp, $content); |
| 78 | + fsync($fp); |
| 79 | + |
| 80 | + // Release lock |
| 81 | + fclose($fp); |
| 82 | + |
| 83 | + return $locks[$seconds][$milliseconds]; |
| 84 | + } |
| 85 | + |
| 86 | + private function getFilePath(int $fileId): string { |
| 87 | + return $this->workDir . sprintf(self::LOCK_FILE_FORMAT, $fileId); |
| 88 | + } |
| 89 | +} |
0 commit comments