You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudStorageReadRouter.php

91 lines
3.1 KiB
PHP

<?php
namespace App\Services\Cloud;
/** Selects one verified replica without changing placement or replaying I/O. */
final class CloudStorageReadRouter
{
/**
* @param array<string,mixed> $artifact
* @param list<array<string,mixed>> $candidates Replica fields plus a
* nested `backend` array.
* @return array<string,mixed>
*/
public static function select(array $artifact, array $candidates): array
{
$size = $artifact['size_bytes'] ?? null;
$sha256 = $artifact['sha256'] ?? null;
if (!is_int($size) || $size < 1 || !is_string($sha256)
|| preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1) {
throw new \InvalidArgumentException(
'Storage artifact identity is invalid'
);
}
$eligible = [];
foreach ($candidates as $candidate) {
$backend = $candidate['backend'] ?? null;
if (!is_array($backend)
|| ($candidate['state'] ?? null) !== 'ready'
|| ($candidate['size_bytes'] ?? null) !== $size
|| !is_string($candidate['sha256'] ?? null)
|| !hash_equals($sha256, $candidate['sha256'])
|| !is_int($candidate['verified_at'] ?? null)
|| $candidate['verified_at'] < 1) {
continue;
}
$admin = $backend['admin_state'] ?? null;
$health = $backend['health_state'] ?? null;
if (!in_array($admin,
['active', 'read_only', 'draining', 'disabled'], true)
|| !in_array($health,
['healthy', 'degraded', 'unknown'], true)) {
continue;
}
$id = $candidate['id'] ?? null;
$backendId = $candidate['backend_id'] ?? null;
$priority = $backend['write_priority'] ?? null;
if (!is_int($id) || $id < 1 || !is_int($backendId)
|| $backendId < 1 || !is_int($priority)
|| $priority < 0) {
continue;
}
$candidate['_route_rank'] = [
self::healthRank($health),
self::adminRank($admin),
($candidate['role'] ?? '') === 'primary' ? 0 : 1,
$priority,
$backendId,
$id,
];
$eligible[] = $candidate;
}
if ($eligible === []) {
throw new CloudError('对象存储副本当前不可读取', 503);
}
usort($eligible, static fn (array $left, array $right): int =>
$left['_route_rank'] <=> $right['_route_rank']);
unset($eligible[0]['_route_rank']);
return $eligible[0];
}
private static function healthRank(string $health): int
{
return match ($health) {
'healthy' => 0,
'degraded' => 1,
default => 2,
};
}
private static function adminRank(string $state): int
{
return match ($state) {
'active' => 0,
'read_only', 'draining' => 1,
default => 2,
};
}
}