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/CloudTemplateRemoteFetcher.php

77 lines
2.3 KiB
PHP

<?php
namespace App\Services\Cloud;
use GuzzleHttp\ClientInterface;
/** Cloud-template policy adapter for secure remote artifact acquisition. */
final class CloudTemplateRemoteFetcher
{
private const TEMPORARY_PREFIX = 'virt-cloud-template-';
private const STALE_FILE_SECONDS = 86400;
private CloudRemoteArtifactFetcher $fetcher;
/** @param null|callable(string):list<string> $resolver */
public function __construct(
?ClientInterface $http = null,
?callable $resolver = null
) {
$this->fetcher = new CloudRemoteArtifactFetcher(
'云镜像',
1048576,
4294967296,
self::TEMPORARY_PREFIX,
$http,
$resolver
);
}
/** @return array{path:string,size_bytes:int,sha256:string} */
public function fetch(string $url, string $expectedSha256 = ''): array
{
return $this->fetcher->fetch($url, $expectedSha256);
}
/**
* Reap one crash-orphaned download without touching a live request.
* A fetch has a 15-minute absolute HTTP deadline, so the 24-hour age
* fence is deliberately much larger than every legitimate acquisition.
*/
public static function cleanupOneStaleFile(?int $now = null): bool
{
$now ??= time();
if ($now < self::STALE_FILE_SECONDS) {
throw new \InvalidArgumentException(
'Template temporary-file cleanup clock is invalid'
);
}
$directory = realpath(sys_get_temp_dir());
if (!is_string($directory) || !is_dir($directory)) {
return false;
}
$paths = glob(
$directory . DIRECTORY_SEPARATOR . self::TEMPORARY_PREFIX . '*',
GLOB_NOSORT
);
if (!is_array($paths) || $paths === []) {
return false;
}
sort($paths, SORT_STRING);
foreach ($paths as $path) {
if (!is_string($path) || is_link($path) || !is_file($path)) {
continue;
}
$modified = @filemtime($path);
if (!is_int($modified)
|| $modified > $now - self::STALE_FILE_SECONDS) {
continue;
}
if (@unlink($path)) {
return true;
}
}
return false;
}
}