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

82 lines
3.3 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudTemplateImportIntent;
use App\Models\CloudTemplateImportPart;
/** Provides administrator-safe projections of import intent state. */
final class CloudTemplateImportReadModel
{
public function active(array $actor): array
{
self::assertAdministrator($actor);
$rows = CloudTemplateImportIntent::query()
->whereNotIn('state', ['ready', 'cancelled'])
->orderByDesc('created_at')->limit(50)->get();
return ['intents' => $rows->map(
static fn (CloudTemplateImportIntent $row): array => self::project($row)
)->all()];
}
public function one(string $id, array $actor): array
{
self::assertAdministrator($actor);
$id = CloudTemplateImportId::parse($id);
$intent = CloudTemplateImportIntent::find($id);
if ($intent === null) {
throw new CloudError('云镜像导入记录不存在', 404);
}
return ['intent' => self::project($intent)];
}
/** @return array<string,mixed> */
public static function project(CloudTemplateImportIntent $intent): array
{
$parts = CloudTemplateImportPart::query()
->where('intent_id', (string) $intent->id)
->orderBy('part_number')->get()->map(
static fn (CloudTemplateImportPart $part): array => [
'part_number' => (int) $part->part_number,
'size_bytes' => (int) $part->size_bytes,
]
)->all();
$capabilities = CloudTemplateImportStateMachine::capabilities($intent);
return [
'id' => (string) $intent->id,
'source_kind' => (string) $intent->source_kind,
'name' => (string) $intent->name,
'os_family' => (string) $intent->os_family,
'os_version' => (string) $intent->os_version,
'source_filename' => (string) $intent->source_filename,
'source_size_bytes' => (int) $intent->source_size_bytes,
'source_last_modified' => (int) $intent->source_last_modified,
'source_sha256' => (string) $intent->source_sha256,
'template_id' => (string) $intent->template_id,
'state' => (string) $intent->state,
'uploaded_parts' => count($parts),
'uploaded_bytes' => array_sum(array_column($parts, 'size_bytes')),
'parts' => $parts,
'part_count' => (int) $intent->multipart_part_count,
'part_size_bytes' => (int) $intent->multipart_part_size_bytes,
'can_resume' => $capabilities['can_resume'],
'can_cancel' => $capabilities['can_cancel'],
'task_id' => $intent->active_job_id === null
? null : (int) $intent->active_job_id,
'error_code' => (string) $intent->error_code,
'expires_at' => (int) $intent->expires_at,
'completed_at' => $intent->completed_at === null
? null : (int) $intent->completed_at,
'created_at' => (int) $intent->created_at,
'updated_at' => (int) $intent->updated_at,
];
}
private static function assertAdministrator(array $actor): void
{
if (($actor['is_admin'] ?? false) !== true) {
throw new CloudError('需要管理员权限', 403);
}
}
}