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/CloudStorageProtectionSumma...

111 lines
4.0 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudStorageArtifact;
/**
* Read-only projection of immutable-object replica coverage.
*
* Coverage is derived from verified ready replicas instead of operation rows.
* This keeps the administrator overview accurate while a copy operation is
* retrying, reconciling or waiting for a replacement backend.
*/
final class CloudStorageProtectionSummaryService
{
/** @return array<string,int> */
public static function summary(?int $now = null): array
{
$now ??= time();
$rows = CloudStorageArtifact::query()
->from('cloud_storage_artifacts as artifacts')
->leftJoin('cloud_storage_replicas as replicas', static function ($join): void {
$join->on('replicas.artifact_id', '=', 'artifacts.id')
->where('replicas.state', '=', 'ready')
->whereColumn(
'replicas.size_bytes',
'=',
'artifacts.size_bytes'
)
->whereColumn(
'replicas.sha256',
'=',
'artifacts.sha256'
)
->where('replicas.verified_at', '>', 0);
})
->leftJoin(
'cloud_storage_backends as backends',
'backends.id',
'=',
'replicas.backend_id'
)
->whereNotIn('artifacts.state', [
'retiring', 'delete_attention', 'deleted',
])
->groupBy(
'artifacts.id',
'artifacts.desired_copies',
'artifacts.required_copies',
'artifacts.created_at'
)
->get([
'artifacts.id',
'artifacts.desired_copies',
'artifacts.required_copies',
'artifacts.created_at',
CloudStorageArtifact::query()->getQuery()->raw(
"COUNT(DISTINCT CASE WHEN "
. "backends.admin_state IN ('active','read_only') "
. "AND backends.health_state IN "
. "('healthy','degraded','unknown') "
. 'THEN replicas.id END) AS ready_copies'
),
CloudStorageArtifact::query()->getQuery()->raw(
"COUNT(DISTINCT CASE WHEN "
. "backends.admin_state IN ('active','read_only') "
. "AND backends.health_state IN "
. "('healthy','degraded','unknown') "
. "AND TRIM(backends.failure_domain) <> '' "
. 'THEN LOWER(TRIM(backends.failure_domain)) END) '
. 'AS ready_domains'
),
]);
$protected = 0;
$degraded = 0;
$backlog = 0;
$oldestCreatedAt = null;
foreach ($rows as $row) {
$ready = (int) ($row->ready_copies ?? 0);
$desired = (int) $row->desired_copies;
$required = (int) $row->required_copies;
$coverage = $required > 1
? min($ready, (int) ($row->ready_domains ?? 0))
: $ready;
if ($coverage >= $desired) {
$protected++;
continue;
}
$backlog++;
if ($coverage >= $required) {
$degraded++;
}
$createdAt = (int) $row->created_at;
if ($oldestCreatedAt === null || $createdAt < $oldestCreatedAt) {
$oldestCreatedAt = $createdAt;
}
}
return [
'protected_artifact_count' => $protected,
'degraded_artifact_count' => $degraded,
'replication_backlog_count' => $backlog,
'oldest_replication_age_seconds' => $oldestCreatedAt === null
? 0
: max(0, $now - $oldestCreatedAt),
];
}
}