|
|
<?php
|
|
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
|
|
use App\Models\CloudStorageBackend;
|
|
|
use App\Models\CloudStorageReplica;
|
|
|
|
|
|
/**
|
|
|
* Transactional registry for object-storage failure domains.
|
|
|
*
|
|
|
* This service owns configuration and health only. It never copies or deletes
|
|
|
* provider objects.
|
|
|
* Historical or failed rows remain addressable for exact reconciliation;
|
|
|
* only two backends may be active for new writes at the same time.
|
|
|
*/
|
|
|
final class CloudObjectStorageBackendRegistry
|
|
|
{
|
|
|
private const CREDENTIAL_PURPOSE = 'object-storage-backend-credentials';
|
|
|
private const MAX_ACTIVE_BACKENDS = 2;
|
|
|
|
|
|
/** @return list<array<string,mixed>> */
|
|
|
public static function listView(): array
|
|
|
{
|
|
|
return CloudStorageBackend::query()->where('admin_state', '<>', 'retired')
|
|
|
->orderBy('write_priority')->orderBy('id')->get()
|
|
|
->map(static fn (CloudStorageBackend $backend): array => self::dto($backend))
|
|
|
->values()->all();
|
|
|
}
|
|
|
|
|
|
/** @return array<string,int> */
|
|
|
public static function summary(): array
|
|
|
{
|
|
|
$backends = CloudStorageBackend::query()
|
|
|
->where('admin_state', '<>', 'retired')->get();
|
|
|
return [
|
|
|
'configured_backends' => $backends->count(),
|
|
|
'active_backends' => $backends->where('admin_state', 'active')->count(),
|
|
|
'healthy_backends' => $backends->where('health_state', 'healthy')->count(),
|
|
|
'writable_backends' => $backends->filter(
|
|
|
static fn (CloudStorageBackend $backend): bool => self::isWritable($backend)
|
|
|
)->count(),
|
|
|
];
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
public static function create(array $input, int $actorUserId): array
|
|
|
{
|
|
|
self::assertActor($actorUserId);
|
|
|
$spec = self::validatedSpec($input, true);
|
|
|
$connection = (new CloudStorageBackend())->getConnection();
|
|
|
$backend = $connection->transaction(static function () use (
|
|
|
$connection,
|
|
|
$spec
|
|
|
): CloudStorageBackend {
|
|
|
self::lockCatalog($connection);
|
|
|
$rows = CloudStorageBackend::query()->where('admin_state', '<>', 'retired')
|
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
|
if ($rows->contains(static fn (CloudStorageBackend $row): bool =>
|
|
|
hash_equals((string) $row->identity_sha256, $spec['identity_sha256']))) {
|
|
|
throw new CloudError('相同 Endpoint、Bucket 和前缀的对象存储已存在', 409);
|
|
|
}
|
|
|
|
|
|
$now = time();
|
|
|
$backend = new CloudStorageBackend();
|
|
|
$backend->backend_key = bin2hex(random_bytes(16));
|
|
|
self::applySpec($backend, $spec);
|
|
|
$backend->config_revision = 1;
|
|
|
$backend->tested_revision = 0;
|
|
|
$backend->admin_state = 'draft';
|
|
|
$backend->health_state = 'unknown';
|
|
|
$backend->consecutive_failures = 0;
|
|
|
$backend->consecutive_successes = 0;
|
|
|
$backend->last_error_code = '';
|
|
|
$backend->last_tested_at = 0;
|
|
|
$backend->last_healthy_at = 0;
|
|
|
$backend->next_probe_at = 0;
|
|
|
$backend->created_at = $now;
|
|
|
$backend->updated_at = $now;
|
|
|
$backend->save();
|
|
|
return $backend;
|
|
|
});
|
|
|
return self::dto($backend);
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
public static function update(
|
|
|
int $backendId,
|
|
|
array $input,
|
|
|
int $expectedRevision,
|
|
|
int $actorUserId
|
|
|
): array {
|
|
|
self::assertActor($actorUserId);
|
|
|
self::assertId($backendId);
|
|
|
self::assertRevision($expectedRevision);
|
|
|
$connection = (new CloudStorageBackend())->getConnection();
|
|
|
$backend = $connection->transaction(static function () use (
|
|
|
$connection,
|
|
|
$backendId,
|
|
|
$input,
|
|
|
$expectedRevision
|
|
|
): CloudStorageBackend {
|
|
|
self::lockCatalog($connection);
|
|
|
$backend = CloudStorageBackend::query()->whereKey($backendId)
|
|
|
->lockForUpdate()->first();
|
|
|
if (!$backend instanceof CloudStorageBackend
|
|
|
|| (string) $backend->admin_state === 'retired') {
|
|
|
throw new CloudError('对象存储后端不存在', 404);
|
|
|
}
|
|
|
self::assertExpectedRevision($backend, $expectedRevision);
|
|
|
$spec = self::validatedSpec($input, false, $backend);
|
|
|
$identityChanged = !hash_equals(
|
|
|
(string) $backend->identity_sha256,
|
|
|
$spec['identity_sha256']
|
|
|
);
|
|
|
if ($identityChanged && CloudStorageReplica::query()
|
|
|
->where('backend_id', $backend->id)->exists()) {
|
|
|
throw new CloudError('已有对象副本引用该后端,不能修改 Endpoint、Bucket、前缀或寻址方式', 409);
|
|
|
}
|
|
|
if ($identityChanged && CloudStorageBackend::query()
|
|
|
->where('id', '<>', $backend->id)
|
|
|
->where('identity_sha256', $spec['identity_sha256'])
|
|
|
->where('admin_state', '<>', 'retired')->exists()) {
|
|
|
throw new CloudError('相同 Endpoint、Bucket 和前缀的对象存储已存在', 409);
|
|
|
}
|
|
|
|
|
|
$runtimeChanged = self::runtimeChanged($backend, $spec);
|
|
|
$oldRevision = (int) $backend->config_revision;
|
|
|
$wasTested = (int) $backend->tested_revision === $oldRevision;
|
|
|
self::applySpec($backend, $spec);
|
|
|
$backend->config_revision = $oldRevision + 1;
|
|
|
if ($runtimeChanged) {
|
|
|
$backend->tested_revision = 0;
|
|
|
$backend->health_state = 'unknown';
|
|
|
$backend->consecutive_successes = 0;
|
|
|
$backend->last_error_code = '';
|
|
|
$backend->next_probe_at = 0;
|
|
|
$backend->admin_state = CloudStorageReplica::query()
|
|
|
->where('backend_id', $backend->id)->exists()
|
|
|
? 'read_only' : 'draft';
|
|
|
} elseif ($wasTested) {
|
|
|
$backend->tested_revision = $oldRevision + 1;
|
|
|
}
|
|
|
$backend->updated_at = time();
|
|
|
$backend->save();
|
|
|
return $backend;
|
|
|
});
|
|
|
return self::dto($backend);
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
public static function test(
|
|
|
int $backendId,
|
|
|
int $expectedRevision,
|
|
|
int $actorUserId,
|
|
|
?CloudObjectStorageS3Client $client = null
|
|
|
): array {
|
|
|
self::assertActor($actorUserId);
|
|
|
self::assertId($backendId);
|
|
|
self::assertRevision($expectedRevision);
|
|
|
$backend = self::find($backendId);
|
|
|
self::assertExpectedRevision($backend, $expectedRevision);
|
|
|
$runtime = self::runtimeFromBackend($backend);
|
|
|
try {
|
|
|
($client ?? new CloudObjectStorageS3Client())->headBucket(
|
|
|
$runtime['config'],
|
|
|
$runtime['credentials']
|
|
|
);
|
|
|
} catch (CloudObjectStorageTestError $error) {
|
|
|
self::recordTestFailure($backendId, $expectedRevision, $error->publicCode);
|
|
|
throw new CloudError($error->getMessage(), 502);
|
|
|
}
|
|
|
|
|
|
$connection = $backend->getConnection();
|
|
|
$backend = $connection->transaction(static function () use (
|
|
|
$backendId,
|
|
|
$expectedRevision
|
|
|
): CloudStorageBackend {
|
|
|
$locked = CloudStorageBackend::query()->whereKey($backendId)
|
|
|
->lockForUpdate()->firstOrFail();
|
|
|
self::assertExpectedRevision($locked, $expectedRevision,
|
|
|
'连接测试期间配置已改变,请重新测试');
|
|
|
$now = time();
|
|
|
$locked->tested_revision = $expectedRevision;
|
|
|
$locked->health_state = 'healthy';
|
|
|
$locked->consecutive_failures = 0;
|
|
|
$locked->consecutive_successes = (int) $locked->consecutive_successes + 1;
|
|
|
$locked->last_error_code = '';
|
|
|
$locked->last_tested_at = $now;
|
|
|
$locked->last_healthy_at = $now;
|
|
|
$locked->next_probe_at = $now + 300;
|
|
|
$locked->updated_at = $now;
|
|
|
$locked->save();
|
|
|
return $locked;
|
|
|
});
|
|
|
return self::dto($backend);
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
public static function activate(int $backendId, int $expectedRevision, int $actorUserId): array
|
|
|
{
|
|
|
return self::transition($backendId, $expectedRevision, $actorUserId,
|
|
|
['draft', 'disabled', 'read_only'], 'active', true);
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
public static function drain(int $backendId, int $expectedRevision, int $actorUserId): array
|
|
|
{
|
|
|
return self::transition($backendId, $expectedRevision, $actorUserId,
|
|
|
['active', 'read_only'], 'draining', false);
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
public static function resume(int $backendId, int $expectedRevision, int $actorUserId): array
|
|
|
{
|
|
|
return self::transition($backendId, $expectedRevision, $actorUserId,
|
|
|
['draining'], 'active', true);
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
public static function disable(int $backendId, int $expectedRevision, int $actorUserId): array
|
|
|
{
|
|
|
return self::transition($backendId, $expectedRevision, $actorUserId,
|
|
|
['draft', 'active', 'read_only', 'draining', 'disabled'],
|
|
|
'disabled', false);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Server-side runtime. Credentials and provider identity never enter a DTO.
|
|
|
* Disabled/draining backends remain usable for exact historical reads and
|
|
|
* deletes; requireHealthy only checks current connectivity evidence.
|
|
|
*
|
|
|
* @return array{config:array<string,mixed>,credentials:array{access_key_id:string,secret_access_key:string},revision:int,backend_id:int}
|
|
|
*/
|
|
|
public static function runtime(int $backendId, bool $requireHealthy = true): array
|
|
|
{
|
|
|
self::assertId($backendId);
|
|
|
$backend = self::find($backendId);
|
|
|
if ((string) $backend->admin_state === 'retired') {
|
|
|
throw new CloudError('对象存储后端已退役', 503);
|
|
|
}
|
|
|
if ($requireHealthy && !self::hasCurrentHealth($backend)) {
|
|
|
throw new CloudError('对象存储后端尚未通过当前配置的连接验证', 503);
|
|
|
}
|
|
|
return self::runtimeFromBackend($backend);
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
private static function transition(
|
|
|
int $backendId,
|
|
|
int $expectedRevision,
|
|
|
int $actorUserId,
|
|
|
array $allowed,
|
|
|
string $target,
|
|
|
bool $requireHealthy
|
|
|
): array {
|
|
|
self::assertActor($actorUserId);
|
|
|
self::assertId($backendId);
|
|
|
self::assertRevision($expectedRevision);
|
|
|
$connection = (new CloudStorageBackend())->getConnection();
|
|
|
$backend = $connection->transaction(static function () use (
|
|
|
$connection,
|
|
|
$backendId,
|
|
|
$expectedRevision,
|
|
|
$allowed,
|
|
|
$target,
|
|
|
$requireHealthy
|
|
|
): CloudStorageBackend {
|
|
|
self::lockCatalog($connection);
|
|
|
$backends = CloudStorageBackend::query()
|
|
|
->where('admin_state', '<>', 'retired')
|
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
|
$backend = $backends->first(static fn (
|
|
|
CloudStorageBackend $row
|
|
|
): bool => (int) $row->id === $backendId);
|
|
|
if (!$backend instanceof CloudStorageBackend) {
|
|
|
throw new CloudError('对象存储后端不存在', 404);
|
|
|
}
|
|
|
self::assertExpectedRevision($backend, $expectedRevision);
|
|
|
if (!in_array((string) $backend->admin_state, $allowed, true)) {
|
|
|
throw new CloudError('对象存储后端当前状态不允许此操作', 409);
|
|
|
}
|
|
|
if ($requireHealthy && !self::hasCurrentHealth($backend)) {
|
|
|
throw new CloudError('请先通过当前配置的连接测试', 409);
|
|
|
}
|
|
|
if ($target === 'active') {
|
|
|
$otherActive = $backends->filter(static fn (
|
|
|
CloudStorageBackend $row
|
|
|
): bool => (int) $row->id !== $backendId
|
|
|
&& (string) $row->admin_state === 'active')->count();
|
|
|
if ($otherActive >= self::MAX_ACTIVE_BACKENDS) {
|
|
|
throw new CloudError(
|
|
|
'同时最多启用两个对象存储后端,请先排空或停用一个后端',
|
|
|
409
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
$oldRevision = (int) $backend->config_revision;
|
|
|
$wasTested = (int) $backend->tested_revision === $oldRevision;
|
|
|
$backend->config_revision = $oldRevision + 1;
|
|
|
if ($wasTested) {
|
|
|
$backend->tested_revision = $oldRevision + 1;
|
|
|
}
|
|
|
$backend->admin_state = $target;
|
|
|
$backend->updated_at = time();
|
|
|
$backend->save();
|
|
|
return $backend;
|
|
|
});
|
|
|
return self::dto($backend);
|
|
|
}
|
|
|
|
|
|
private static function recordTestFailure(int $backendId, int $expectedRevision, string $code): void
|
|
|
{
|
|
|
$connection = (new CloudStorageBackend())->getConnection();
|
|
|
$connection->transaction(static function () use (
|
|
|
$backendId,
|
|
|
$expectedRevision,
|
|
|
$code
|
|
|
): void {
|
|
|
$backend = CloudStorageBackend::query()->whereKey($backendId)
|
|
|
->lockForUpdate()->firstOrFail();
|
|
|
self::assertExpectedRevision($backend, $expectedRevision,
|
|
|
'连接测试期间配置已改变,请重新测试');
|
|
|
$backend->tested_revision = 0;
|
|
|
$backend->health_state = in_array($code, [
|
|
|
'endpoint_unreachable', 'service_unavailable', 'rate_limited',
|
|
|
], true) ? 'unreachable' : 'degraded';
|
|
|
$backend->consecutive_failures = (int) $backend->consecutive_failures + 1;
|
|
|
$backend->consecutive_successes = 0;
|
|
|
$backend->last_error_code = $code;
|
|
|
$backend->last_tested_at = time();
|
|
|
$backend->next_probe_at = time() + min(
|
|
|
3600,
|
|
|
60 * (2 ** min(5, (int) $backend->consecutive_failures - 1))
|
|
|
);
|
|
|
if ((string) $backend->admin_state === 'active') {
|
|
|
$backend->admin_state = 'read_only';
|
|
|
}
|
|
|
$backend->updated_at = time();
|
|
|
$backend->save();
|
|
|
});
|
|
|
}
|
|
|
|
|
|
private static function find(int $backendId): CloudStorageBackend
|
|
|
{
|
|
|
$backend = CloudStorageBackend::query()->whereKey($backendId)->first();
|
|
|
if (!$backend instanceof CloudStorageBackend) {
|
|
|
throw new CloudError('对象存储后端不存在', 404);
|
|
|
}
|
|
|
return $backend;
|
|
|
}
|
|
|
|
|
|
/** Serialize backend-count and immutable-identity mutations. */
|
|
|
private static function lockCatalog($connection): void
|
|
|
{
|
|
|
$mutex = $connection->table('cloud_storage_backend_catalog_mutex')
|
|
|
->where('id', 1)->lockForUpdate()->first(['id']);
|
|
|
if ($mutex === null) {
|
|
|
throw new CloudError('对象存储后端目录尚未初始化', 503);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
private static function dto(CloudStorageBackend $backend): array
|
|
|
{
|
|
|
$state = (string) $backend->admin_state;
|
|
|
$healthy = self::hasCurrentHealth($backend);
|
|
|
$errors = [
|
|
|
'endpoint_unreachable' => '无法连接 Endpoint,请检查证书、DNS 和防火墙。',
|
|
|
'region_mismatch' => 'Bucket 区域不匹配。',
|
|
|
'auth_or_permission_denied' => '凭据或 Bucket 权限验证失败。',
|
|
|
'bucket_not_found' => 'Bucket 不存在或不可访问。',
|
|
|
'rate_limited' => '对象存储暂时限制请求。',
|
|
|
'service_unavailable' => '对象存储服务暂时不可用。',
|
|
|
'request_rejected' => '对象存储拒绝兼容性检查。',
|
|
|
];
|
|
|
$lastError = (string) $backend->last_error_code;
|
|
|
return [
|
|
|
'id' => (int) $backend->id,
|
|
|
'backend_key' => (string) $backend->backend_key,
|
|
|
'name' => (string) $backend->name,
|
|
|
'driver' => 's3',
|
|
|
'endpoint' => (string) $backend->endpoint,
|
|
|
'region' => (string) $backend->region,
|
|
|
'bucket' => (string) $backend->bucket,
|
|
|
'prefix' => (string) $backend->prefix,
|
|
|
'path_style' => (bool) $backend->path_style,
|
|
|
'failure_domain' => (string) $backend->failure_domain,
|
|
|
'write_priority' => (int) $backend->write_priority,
|
|
|
'admin_state' => $state,
|
|
|
'health_state' => (string) $backend->health_state,
|
|
|
'ready' => $healthy,
|
|
|
'configured' => true,
|
|
|
'credentials_configured' => trim((string) $backend->sealed_credentials) !== '',
|
|
|
'revision' => (int) $backend->config_revision,
|
|
|
'tested_revision' => (int) $backend->tested_revision,
|
|
|
'last_error_code' => $lastError,
|
|
|
'last_error' => $errors[$lastError] ?? '',
|
|
|
'last_tested_at' => (int) $backend->last_tested_at,
|
|
|
'last_tested_at_text' => (int) $backend->last_tested_at > 0
|
|
|
? date('Y-m-d H:i:s', (int) $backend->last_tested_at) : '',
|
|
|
'can_edit' => $state !== 'retired',
|
|
|
'can_test' => $state !== 'retired',
|
|
|
'can_activate' => in_array($state, ['draft', 'disabled', 'read_only'], true)
|
|
|
&& $healthy,
|
|
|
'can_drain' => in_array($state, ['active', 'read_only'], true),
|
|
|
'can_resume' => $state === 'draining' && $healthy,
|
|
|
'can_disable' => $state !== 'retired' && $state !== 'disabled',
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function isWritable(CloudStorageBackend $backend): bool
|
|
|
{
|
|
|
return (string) $backend->admin_state === 'active'
|
|
|
&& self::hasCurrentHealth($backend);
|
|
|
}
|
|
|
|
|
|
private static function hasCurrentHealth(CloudStorageBackend $backend): bool
|
|
|
{
|
|
|
return (int) $backend->config_revision > 0
|
|
|
&& (int) $backend->tested_revision === (int) $backend->config_revision
|
|
|
&& (string) $backend->health_state === 'healthy';
|
|
|
}
|
|
|
|
|
|
/** @return array{config:array<string,mixed>,credentials:array{access_key_id:string,secret_access_key:string},revision:int,backend_id:int} */
|
|
|
private static function runtimeFromBackend(CloudStorageBackend $backend): array
|
|
|
{
|
|
|
$credentials = CloudSecrets::decrypt(
|
|
|
(string) $backend->sealed_credentials,
|
|
|
self::CREDENTIAL_PURPOSE
|
|
|
);
|
|
|
$access = $credentials['access_key_id'] ?? null;
|
|
|
$secret = $credentials['secret_access_key'] ?? null;
|
|
|
if (!is_string($access) || !is_string($secret)) {
|
|
|
throw new CloudError('对象存储访问凭据内容无效', 503);
|
|
|
}
|
|
|
self::assertCredentials($access, $secret);
|
|
|
return [
|
|
|
'config' => [
|
|
|
'endpoint' => (string) $backend->endpoint,
|
|
|
'region' => (string) $backend->region,
|
|
|
'bucket' => (string) $backend->bucket,
|
|
|
'prefix' => (string) $backend->prefix,
|
|
|
'path_style' => (bool) $backend->path_style,
|
|
|
],
|
|
|
'credentials' => [
|
|
|
'access_key_id' => $access,
|
|
|
'secret_access_key' => $secret,
|
|
|
],
|
|
|
'revision' => (int) $backend->config_revision,
|
|
|
'backend_id' => (int) $backend->id,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
/** @return array<string,mixed> */
|
|
|
private static function validatedSpec(
|
|
|
array $input,
|
|
|
bool $requireCredentials,
|
|
|
?CloudStorageBackend $current = null
|
|
|
): array {
|
|
|
CloudInput::only($input, [
|
|
|
'name', 'endpoint', 'region', 'bucket', 'prefix', 'path_style',
|
|
|
'failure_domain', 'write_priority', 'access_key_id',
|
|
|
'secret_access_key',
|
|
|
]);
|
|
|
$name = self::name($input['name'] ?? ($current?->name ?? ''));
|
|
|
$endpoint = self::endpoint($input['endpoint'] ?? ($current?->endpoint ?? ''));
|
|
|
$region = self::region($input['region'] ?? ($current?->region ?? ''));
|
|
|
$bucket = self::bucket($input['bucket'] ?? ($current?->bucket ?? ''));
|
|
|
$prefix = self::objectPrefix($input['prefix'] ?? ($current?->prefix ?? ''));
|
|
|
$pathStyle = array_key_exists('path_style', $input)
|
|
|
? self::boolean($input['path_style'], '请选择 S3 寻址方式')
|
|
|
: (bool) ($current?->path_style ?? false);
|
|
|
if (!$pathStyle && self::endpointHostIsIp($endpoint)) {
|
|
|
throw new CloudError('IP 地址 Endpoint 只能使用路径寻址');
|
|
|
}
|
|
|
$failureDomain = self::failureDomain(
|
|
|
$input['failure_domain'] ?? ($current?->failure_domain ?? '')
|
|
|
);
|
|
|
$writePriority = self::writePriority(
|
|
|
$input['write_priority'] ?? ($current?->write_priority ?? 100)
|
|
|
);
|
|
|
$access = is_string($input['access_key_id'] ?? null)
|
|
|
? trim((string) $input['access_key_id']) : '';
|
|
|
$secret = is_string($input['secret_access_key'] ?? null)
|
|
|
? (string) $input['secret_access_key'] : '';
|
|
|
if (($access === '') !== ($secret === '')) {
|
|
|
throw new CloudError('Access Key ID 和 Secret Access Key 必须同时填写');
|
|
|
}
|
|
|
if ($access !== '') {
|
|
|
self::assertCredentials($access, $secret);
|
|
|
$sealed = CloudSecrets::encrypt([
|
|
|
'access_key_id' => $access,
|
|
|
'secret_access_key' => $secret,
|
|
|
], self::CREDENTIAL_PURPOSE);
|
|
|
} elseif ($current instanceof CloudStorageBackend) {
|
|
|
$sealed = (string) $current->sealed_credentials;
|
|
|
self::runtimeFromBackend($current);
|
|
|
} elseif ($requireCredentials) {
|
|
|
throw new CloudError('首次保存对象存储必须填写 Access Key 和 Secret Key');
|
|
|
} else {
|
|
|
throw new CloudError('对象存储访问凭据尚未配置', 503);
|
|
|
}
|
|
|
return [
|
|
|
'name' => $name,
|
|
|
'endpoint' => $endpoint,
|
|
|
'region' => $region,
|
|
|
'bucket' => $bucket,
|
|
|
'prefix' => $prefix,
|
|
|
'path_style' => $pathStyle,
|
|
|
'failure_domain' => $failureDomain,
|
|
|
'write_priority' => $writePriority,
|
|
|
'sealed_credentials' => $sealed,
|
|
|
'identity_sha256' => self::identityHash(
|
|
|
$endpoint,
|
|
|
$bucket,
|
|
|
$prefix,
|
|
|
$pathStyle
|
|
|
),
|
|
|
];
|
|
|
}
|
|
|
|
|
|
/** @param array<string,mixed> $spec */
|
|
|
private static function applySpec(CloudStorageBackend $backend, array $spec): void
|
|
|
{
|
|
|
$backend->identity_sha256 = $spec['identity_sha256'];
|
|
|
$backend->name = $spec['name'];
|
|
|
$backend->driver = 's3';
|
|
|
$backend->endpoint = $spec['endpoint'];
|
|
|
$backend->region = $spec['region'];
|
|
|
$backend->bucket = $spec['bucket'];
|
|
|
$backend->prefix = $spec['prefix'];
|
|
|
$backend->path_style = $spec['path_style'] ? 1 : 0;
|
|
|
$backend->failure_domain = $spec['failure_domain'];
|
|
|
$backend->sealed_credentials = $spec['sealed_credentials'];
|
|
|
$backend->write_priority = $spec['write_priority'];
|
|
|
}
|
|
|
|
|
|
/** @param array<string,mixed> $spec */
|
|
|
private static function runtimeChanged(CloudStorageBackend $backend, array $spec): bool
|
|
|
{
|
|
|
return (string) $backend->endpoint !== $spec['endpoint']
|
|
|
|| (string) $backend->region !== $spec['region']
|
|
|
|| (string) $backend->bucket !== $spec['bucket']
|
|
|
|| (string) $backend->prefix !== $spec['prefix']
|
|
|
|| (bool) $backend->path_style !== $spec['path_style']
|
|
|
|| !hash_equals((string) $backend->sealed_credentials,
|
|
|
(string) $spec['sealed_credentials']);
|
|
|
}
|
|
|
|
|
|
private static function identityHash(
|
|
|
string $endpoint,
|
|
|
string $bucket,
|
|
|
string $prefix,
|
|
|
bool $pathStyle
|
|
|
): string {
|
|
|
return hash('sha256', json_encode([
|
|
|
'driver' => 's3',
|
|
|
'endpoint' => $endpoint,
|
|
|
'bucket' => $bucket,
|
|
|
'prefix' => $prefix,
|
|
|
'path_style' => $pathStyle,
|
|
|
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
|
|
|
}
|
|
|
|
|
|
private static function assertExpectedRevision(
|
|
|
CloudStorageBackend $backend,
|
|
|
int $expected,
|
|
|
string $message = '对象存储配置已被修改,请刷新页面后重试'
|
|
|
): void {
|
|
|
if ((int) $backend->config_revision !== $expected) {
|
|
|
throw new CloudError($message, 409);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function assertActor(int $actorUserId): void
|
|
|
{
|
|
|
if ($actorUserId < 1) {
|
|
|
throw new CloudError('管理员身份无效', 403);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function assertId(int $backendId): void
|
|
|
{
|
|
|
if ($backendId < 1) {
|
|
|
throw new CloudError('对象存储后端不存在', 404);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function assertRevision(int $revision): void
|
|
|
{
|
|
|
if ($revision < 1) {
|
|
|
throw new CloudError('对象存储配置版本无效,请刷新页面后重试', 409);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function name($value): string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
throw new CloudError('对象存储名称格式无效');
|
|
|
}
|
|
|
$value = trim($value);
|
|
|
if ($value === '' || mb_strlen($value, 'UTF-8') > 80
|
|
|
|| preg_match('//u', $value) !== 1
|
|
|
|| preg_match('/[\x00-\x1F\x7F]/u', $value) === 1) {
|
|
|
throw new CloudError('对象存储名称需为 1 至 80 个字符且不能包含控制字符');
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function endpoint($value): string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
throw new CloudError('Endpoint 格式无效');
|
|
|
}
|
|
|
$parts = parse_url(trim($value));
|
|
|
if (!is_array($parts)
|
|
|
|| strtolower((string) ($parts['scheme'] ?? '')) !== 'https'
|
|
|
|| !isset($parts['host']) || isset($parts['user'])
|
|
|
|| isset($parts['pass']) || isset($parts['query'])
|
|
|
|| isset($parts['fragment'])
|
|
|
|| !in_array((string) ($parts['path'] ?? ''), ['', '/'], true)) {
|
|
|
throw new CloudError('Endpoint 必须是仅包含主机和可选端口的 HTTPS 地址');
|
|
|
}
|
|
|
$host = strtolower(trim((string) $parts['host'], '[]'));
|
|
|
if ($host === '' || $host === 'localhost' || str_ends_with($host, '.localhost')) {
|
|
|
throw new CloudError('Endpoint 主机无效');
|
|
|
}
|
|
|
if (filter_var($host, FILTER_VALIDATE_IP)) {
|
|
|
if (self::blockedEndpointIp($host)) {
|
|
|
throw new CloudError('Endpoint 不能使用回环、链路本地、未指定或组播地址');
|
|
|
}
|
|
|
} else {
|
|
|
if (preg_match('/^[0-9.]+$/D', $host) === 1
|
|
|
|| strlen($host) > 253 || str_ends_with($host, '.')) {
|
|
|
throw new CloudError('Endpoint 主机名无效');
|
|
|
}
|
|
|
foreach (explode('.', $host) as $label) {
|
|
|
if (preg_match('/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/D', $label) !== 1) {
|
|
|
throw new CloudError('Endpoint 主机名无效');
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
$port = isset($parts['port']) ? (int) $parts['port'] : 443;
|
|
|
if ($port < 1 || $port > 65535) {
|
|
|
throw new CloudError('Endpoint 端口必须为 1 至 65535');
|
|
|
}
|
|
|
$authority = str_contains($host, ':') ? '[' . $host . ']' : $host;
|
|
|
if ($port !== 443) {
|
|
|
$authority .= ':' . $port;
|
|
|
}
|
|
|
return 'https://' . $authority;
|
|
|
}
|
|
|
|
|
|
private static function endpointHostIsIp(string $endpoint): bool
|
|
|
{
|
|
|
$host = parse_url($endpoint, PHP_URL_HOST);
|
|
|
return is_string($host)
|
|
|
&& filter_var(trim($host, '[]'), FILTER_VALIDATE_IP) !== false;
|
|
|
}
|
|
|
|
|
|
private static function blockedEndpointIp(string $host): bool
|
|
|
{
|
|
|
$packed = inet_pton($host);
|
|
|
if ($packed === false) {
|
|
|
return true;
|
|
|
}
|
|
|
if (strlen($packed) === 4) {
|
|
|
$octets = array_values(unpack('C4', $packed));
|
|
|
return $octets[0] === 0 || $octets[0] === 127
|
|
|
|| ($octets[0] === 169 && $octets[1] === 254)
|
|
|
|| $octets[0] >= 224;
|
|
|
}
|
|
|
$bytes = array_values(unpack('C16', $packed));
|
|
|
return $host === '::' || $host === '::1' || $bytes[0] === 0xff
|
|
|
|| ($bytes[0] === 0xfe && ($bytes[1] & 0xc0) === 0x80);
|
|
|
}
|
|
|
|
|
|
private static function region($value): string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
throw new CloudError('Region 格式无效');
|
|
|
}
|
|
|
$value = strtolower(trim($value));
|
|
|
if (preg_match('/^[a-z0-9][a-z0-9-]{0,62}$/D', $value) !== 1) {
|
|
|
throw new CloudError('Region 只能包含小写字母、数字和连字符,最多 63 位');
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function bucket($value): string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
throw new CloudError('Bucket 名称格式无效');
|
|
|
}
|
|
|
$value = strtolower(trim($value));
|
|
|
if (strlen($value) < 3 || strlen($value) > 63
|
|
|
|| preg_match('/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/D', $value) !== 1
|
|
|
|| str_contains($value, '..') || str_contains($value, '.-')
|
|
|
|| str_contains($value, '-.') || filter_var($value, FILTER_VALIDATE_IP)) {
|
|
|
throw new CloudError('Bucket 名称需符合 S3 DNS 命名规则(3 至 63 位)');
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function objectPrefix($value): string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
throw new CloudError('对象前缀格式无效');
|
|
|
}
|
|
|
$value = trim($value, " \t\n\r\0\x0B/");
|
|
|
if ($value === '') {
|
|
|
return '';
|
|
|
}
|
|
|
if (strlen($value) > 255
|
|
|
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9._\/-]*$/D', $value) !== 1
|
|
|
|| str_contains($value, '//')) {
|
|
|
throw new CloudError('对象前缀只能包含英文、数字、点、下划线、连字符和斜线,最多 255 位');
|
|
|
}
|
|
|
foreach (explode('/', $value) as $segment) {
|
|
|
if ($segment === '.' || $segment === '..') {
|
|
|
throw new CloudError('对象前缀不能包含点路径段');
|
|
|
}
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function failureDomain($value): string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
throw new CloudError('故障域格式无效');
|
|
|
}
|
|
|
$value = strtolower(trim($value));
|
|
|
if ($value === ''
|
|
|
|| preg_match('/^[a-z0-9][a-z0-9_.:-]{0,79}$/D', $value) !== 1) {
|
|
|
throw new CloudError('故障域必须填写,且只能包含英文、数字、点、冒号、下划线和连字符,最多 80 位');
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function writePriority($value): int
|
|
|
{
|
|
|
if (is_int($value)) {
|
|
|
$priority = $value;
|
|
|
} elseif (is_string($value)
|
|
|
&& preg_match('/^(?:0|[1-9][0-9]{0,5})$/D', $value) === 1) {
|
|
|
$priority = (int) $value;
|
|
|
} else {
|
|
|
throw new CloudError('写入优先级格式无效');
|
|
|
}
|
|
|
if ($priority < 0 || $priority > 100000) {
|
|
|
throw new CloudError('写入优先级需为 0 至 100000');
|
|
|
}
|
|
|
return $priority;
|
|
|
}
|
|
|
|
|
|
private static function assertCredentials(string $access, string $secret): void
|
|
|
{
|
|
|
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{2,127}$/D', $access) !== 1) {
|
|
|
throw new CloudError('Access Key ID 需为 3 至 128 位英文、数字、点、下划线或连字符');
|
|
|
}
|
|
|
if (strlen($secret) < 8 || strlen($secret) > 256
|
|
|
|| trim($secret) !== $secret
|
|
|
|| preg_match('/[\x00-\x1F\x7F]/', $secret) === 1) {
|
|
|
throw new CloudError('Secret Access Key 需为 8 至 256 位且不能包含首尾空格或控制字符');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static function boolean($value, string $message): bool
|
|
|
{
|
|
|
$parsed = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
|
|
if ($parsed === null) {
|
|
|
throw new CloudError($message);
|
|
|
}
|
|
|
return $parsed;
|
|
|
}
|
|
|
}
|