1
0

ShardDefinition.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Robin Appelman <robin@icewind.nl>
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\DB\QueryBuilder\Sharded;
  8. use OCP\DB\QueryBuilder\Sharded\IShardMapper;
  9. /**
  10. * Configuration for a shard setup
  11. */
  12. class ShardDefinition {
  13. // we reserve the bottom byte of the primary key for the initial shard, so the total shard count is limited to what we can fit there
  14. public const MAX_SHARDS = 256;
  15. public const PRIMARY_KEY_MASK = 0x7F_FF_FF_FF_FF_FF_FF_00;
  16. public const PRIMARY_KEY_SHARD_MASK = 0x00_00_00_00_00_00_00_FF;
  17. // since we reserve 1 byte for the shard index, we only have 56 bits of primary key space
  18. public const MAX_PRIMARY_KEY = PHP_INT_MAX >> 8;
  19. /**
  20. * @param string $table
  21. * @param string $primaryKey
  22. * @param string $shardKey
  23. * @param string[] $companionKeys
  24. * @param IShardMapper $shardMapper
  25. * @param string[] $companionTables
  26. * @param array $shards
  27. */
  28. public function __construct(
  29. public string $table,
  30. public string $primaryKey,
  31. public array $companionKeys,
  32. public string $shardKey,
  33. public IShardMapper $shardMapper,
  34. public array $companionTables = [],
  35. public array $shards = [],
  36. ) {
  37. if (count($this->shards) >= self::MAX_SHARDS) {
  38. throw new \Exception('Only allowed maximum of ' . self::MAX_SHARDS . ' shards allowed');
  39. }
  40. }
  41. public function hasTable(string $table): bool {
  42. if ($this->table === $table) {
  43. return true;
  44. }
  45. return in_array($table, $this->companionTables);
  46. }
  47. public function getShardForKey(int $key): int {
  48. return $this->shardMapper->getShardForKey($key, count($this->shards));
  49. }
  50. public function getAllShards(): array {
  51. return array_keys($this->shards);
  52. }
  53. public function isKey(string $column): bool {
  54. return $column === $this->primaryKey || in_array($column, $this->companionKeys);
  55. }
  56. }