feat(storage): add resilient replica worker
parent
982cbf0b68
commit
f8c35863ba
@ -0,0 +1,25 @@
|
||||
[Unit]
|
||||
Description=Virt Cloud object storage replica worker
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=apache
|
||||
Group=apache
|
||||
WorkingDirectory=/home/virt-cloud/web
|
||||
ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudStorageReplicaWorker
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
LimitCORE=0
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectHome=false
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=-/home/virt-cloud/runtime/php
|
||||
ReadWritePaths=-/home/virt-cloud/web/storage
|
||||
TimeoutStopSec=30
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Services\Cloud\CloudRuntimeHeartbeat;
|
||||
use App\Services\Cloud\CloudStorageReplicaWorkerService;
|
||||
|
||||
/** Independent worker so large object copies cannot block VM lifecycle jobs. */
|
||||
final class CloudStorageReplicaWorker
|
||||
{
|
||||
public static function run(
|
||||
array $argv = [],
|
||||
?CloudRuntimeHeartbeat $heartbeat = null
|
||||
): int
|
||||
{
|
||||
$once = in_array('--once', $argv, true);
|
||||
$heartbeat ??= CloudRuntimeHeartbeat::start(
|
||||
'storage_replica',
|
||||
$once
|
||||
);
|
||||
$unresolved = false;
|
||||
try {
|
||||
$worker = new CloudStorageReplicaWorkerService();
|
||||
do {
|
||||
$errors = [];
|
||||
$heartbeat->busy('storage_replica_tick');
|
||||
try {
|
||||
$worked = $worker->tick();
|
||||
$errors = $worker->observationErrors();
|
||||
} catch (\Throwable $error) {
|
||||
$errors[] = 'storage_replica_failed';
|
||||
$heartbeat->error('storage_replica_failed');
|
||||
fwrite(
|
||||
STDERR,
|
||||
'storage replica worker temporarily unavailable: '
|
||||
. get_class($error) . PHP_EOL
|
||||
);
|
||||
if ($once) {
|
||||
return 1;
|
||||
}
|
||||
$worked = false;
|
||||
}
|
||||
if ($errors === []) {
|
||||
// An idle poll proves only that the process is alive. It
|
||||
// must not erase a prior copy/reconciliation warning; a
|
||||
// later item has to complete cleanly before the worker is
|
||||
// projected healthy again.
|
||||
if ($worked) {
|
||||
$unresolved = false;
|
||||
$heartbeat->success();
|
||||
} elseif (!$unresolved) {
|
||||
$heartbeat->success();
|
||||
}
|
||||
} else {
|
||||
// Error details remain in durable operation records. The
|
||||
// public heartbeat exposes only this bounded category.
|
||||
$unresolved = true;
|
||||
$heartbeat->error('storage_replica_failed');
|
||||
}
|
||||
if (!$once && !$worked) {
|
||||
usleep(1000000);
|
||||
}
|
||||
} while (!$once);
|
||||
} catch (\Throwable $error) {
|
||||
$heartbeat->error('storage_replica_failed');
|
||||
throw $error;
|
||||
} finally {
|
||||
$heartbeat->stopped();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudStorageArtifact;
|
||||
use App\Models\CloudStorageBackend;
|
||||
use App\Models\CloudStorageOperation;
|
||||
use App\Models\CloudStorageReplica;
|
||||
|
||||
/**
|
||||
* Administrator recovery surface for stable multipart identity conflicts.
|
||||
*
|
||||
* It exposes no object key, upload id or provider capability. Retrying only
|
||||
* re-opens the original durable copy operation for read-only reconciliation.
|
||||
*/
|
||||
final class CloudStorageReplicaAttentionService
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public static function listView(array $input = []): array
|
||||
{
|
||||
CloudInput::only($input, ['page', 'per_page']);
|
||||
$page = self::boundedInt($input['page'] ?? 1, 1, 100000);
|
||||
$perPage = self::boundedInt($input['per_page'] ?? 20, 1, 50);
|
||||
$base = CloudStorageOperation::query()
|
||||
->where('kind', 'copy')
|
||||
->where('phase', 'terminal')
|
||||
->where('outcome', 'failed')
|
||||
->where('effect_resolution', 'unknown')
|
||||
->where('effect_may_have_applied', 1)
|
||||
->where('safe_to_resubmit', 0)
|
||||
->whereIn(
|
||||
'error_code',
|
||||
CloudStorageArtifactService::replicaAttentionErrors()
|
||||
);
|
||||
$total = (clone $base)->count();
|
||||
$operations = $base->orderByDesc('terminal_at')
|
||||
->orderByDesc('id')
|
||||
->offset(($page - 1) * $perPage)
|
||||
->limit($perPage)
|
||||
->get();
|
||||
$artifactIds = $operations->pluck('artifact_id')->unique()->all();
|
||||
$backendIds = $operations->pluck('target_backend_id')
|
||||
->merge($operations->pluck('source_backend_id'))
|
||||
->filter()->unique()->all();
|
||||
$artifacts = CloudStorageArtifact::query()
|
||||
->whereIn('id', $artifactIds)->get()->keyBy('id');
|
||||
$backends = CloudStorageBackend::query()
|
||||
->whereIn('id', $backendIds)->get()->keyBy('id');
|
||||
$replicas = CloudStorageReplica::query()
|
||||
->whereIn('artifact_id', $artifactIds)->get();
|
||||
$sourceReplicas = [];
|
||||
foreach ($replicas as $replica) {
|
||||
$sourceReplicas[(int) $replica->artifact_id
|
||||
. ':' . (int) $replica->backend_id] = $replica;
|
||||
}
|
||||
$items = [];
|
||||
foreach ($operations as $operation) {
|
||||
$artifact = $artifacts->get((int) $operation->artifact_id);
|
||||
$backend = $backends->get((int) $operation->target_backend_id);
|
||||
$source = $sourceReplicas[(int) $operation->artifact_id
|
||||
. ':' . (int) $operation->source_backend_id] ?? null;
|
||||
$target = $sourceReplicas[(int) $operation->artifact_id
|
||||
. ':' . (int) $operation->target_backend_id] ?? null;
|
||||
$canRetry = $artifact instanceof CloudStorageArtifact
|
||||
&& !in_array((string) $artifact->state,
|
||||
['retiring', 'delete_attention', 'deleted'], true)
|
||||
&& $source instanceof CloudStorageReplica
|
||||
&& (string) $source->state === 'ready'
|
||||
&& (int) $source->size_bytes === (int) $artifact->size_bytes
|
||||
&& hash_equals(
|
||||
(string) $artifact->sha256,
|
||||
(string) $source->sha256
|
||||
)
|
||||
&& $target instanceof CloudStorageReplica
|
||||
&& (string) $target->state === 'degraded'
|
||||
&& hash_equals(
|
||||
(string) $operation->error_code,
|
||||
(string) $target->error_code
|
||||
);
|
||||
$items[] = [
|
||||
'operation_id' => (string) $operation->operation_id,
|
||||
'artifact_id' => (int) $operation->artifact_id,
|
||||
'artifact_kind' => $artifact instanceof CloudStorageArtifact
|
||||
? (string) $artifact->kind : 'unknown',
|
||||
'artifact_state' => $artifact instanceof CloudStorageArtifact
|
||||
? (string) $artifact->state : 'missing',
|
||||
'backend_id' => (int) $operation->target_backend_id,
|
||||
'backend_name' => $backend instanceof CloudStorageBackend
|
||||
? (string) $backend->name : '未知后端',
|
||||
'error_code' => (string) $operation->error_code,
|
||||
'error_text' => self::errorText(
|
||||
(string) $operation->error_code
|
||||
),
|
||||
'attention_at' => (int) ($operation->terminal_at ?? 0),
|
||||
'can_retry' => $canRetry,
|
||||
];
|
||||
}
|
||||
$pages = max(1, (int) ceil($total / $perPage));
|
||||
return [
|
||||
'summary' => ['count' => $total],
|
||||
'items' => $items,
|
||||
'pagination' => [
|
||||
'page' => $page,
|
||||
'per_page' => $perPage,
|
||||
'total' => $total,
|
||||
'total_pages' => $pages,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{operation_id:string,phase:string} */
|
||||
public static function retry(string $operationId): array
|
||||
{
|
||||
CloudStorageArtifactService::reopenReplicaAttention(
|
||||
$operationId,
|
||||
time()
|
||||
);
|
||||
return [
|
||||
'operation_id' => $operationId,
|
||||
'phase' => 'reconciling',
|
||||
];
|
||||
}
|
||||
|
||||
private static function boundedInt($value, int $minimum, int $maximum): int
|
||||
{
|
||||
$validated = filter_var($value, FILTER_VALIDATE_INT, [
|
||||
'options' => [
|
||||
'min_range' => $minimum,
|
||||
'max_range' => $maximum,
|
||||
],
|
||||
]);
|
||||
if ($validated === false) {
|
||||
throw new CloudError('对象副本人工核对分页参数无效', 422);
|
||||
}
|
||||
return (int) $validated;
|
||||
}
|
||||
|
||||
private static function errorText(string $errorCode): string
|
||||
{
|
||||
return match ($errorCode) {
|
||||
'replica_multipart_identity_ambiguous' =>
|
||||
'同一对象键存在多个分段上传会话',
|
||||
'replica_multipart_identity_mismatch' =>
|
||||
'记录的分段上传会话与远端不一致',
|
||||
'replica_multipart_identity_untrusted' =>
|
||||
'远端分段上传会话无法归属到原操作',
|
||||
default => '分段上传身份需要人工核对',
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,355 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Services\Config;
|
||||
|
||||
/** Executes the capability-only Go mover without a shell or inherited secrets. */
|
||||
final class CloudStorageReplicaHelper
|
||||
{
|
||||
private const MAX_REQUEST_BYTES = 2097152;
|
||||
private const MAX_RECEIPT_BYTES = 65536;
|
||||
private const DEFAULT_PATH = '/home/virt-cloud/bin/virt-cloud-storage-replicator';
|
||||
|
||||
/** @var null|\Closure(array<string,mixed>):array<string,mixed> */
|
||||
private readonly ?\Closure $testInvoker;
|
||||
|
||||
/** @param null|callable(array<string,mixed>):array<string,mixed> $testInvoker */
|
||||
public function __construct(
|
||||
private readonly ?string $binaryPath = null,
|
||||
?callable $testInvoker = null
|
||||
) {
|
||||
$this->testInvoker = $testInvoker === null
|
||||
? null : \Closure::fromCallable($testInvoker);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $request @return array<string,mixed> */
|
||||
public function invoke(array $request): array
|
||||
{
|
||||
$protocol = $request['protocol'] ?? null;
|
||||
$operationId = $request['operation_id'] ?? null;
|
||||
if (!in_array($protocol,
|
||||
['object-replica-v1', 'object-replica-verify-v1'], true)
|
||||
|| !is_string($operationId)
|
||||
|| preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Storage replica helper request envelope is invalid'
|
||||
);
|
||||
}
|
||||
if ($this->testInvoker !== null) {
|
||||
return self::normalizeReceipt(
|
||||
($this->testInvoker)($request),
|
||||
$protocol,
|
||||
$operationId
|
||||
);
|
||||
}
|
||||
$payload = json_encode(
|
||||
$request,
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
||||
);
|
||||
if (strlen($payload) > self::MAX_REQUEST_BYTES) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Storage replica helper request is too large'
|
||||
);
|
||||
}
|
||||
$path = $this->binaryPath ?? (string) Config::get(
|
||||
'cloud_storage_replicator_path',
|
||||
self::DEFAULT_PATH
|
||||
);
|
||||
if (!str_starts_with($path, '/') || !is_file($path)
|
||||
|| !is_executable($path)) {
|
||||
return self::unknownReceipt(
|
||||
$protocol,
|
||||
$operationId,
|
||||
'replicator_unavailable'
|
||||
);
|
||||
}
|
||||
$pipes = [];
|
||||
$process = @proc_open(
|
||||
[$path],
|
||||
[
|
||||
0 => ['pipe', 'r'],
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
],
|
||||
$pipes,
|
||||
null,
|
||||
['LANG' => 'C', 'LC_ALL' => 'C'],
|
||||
['bypass_shell' => true]
|
||||
);
|
||||
if (!is_resource($process) || count($pipes) !== 3) {
|
||||
return self::unknownReceipt(
|
||||
$protocol,
|
||||
$operationId,
|
||||
'replicator_start_failed'
|
||||
);
|
||||
}
|
||||
$stdout = '';
|
||||
$stderrBytes = 0;
|
||||
$timedOut = false;
|
||||
$stdinFailed = false;
|
||||
$observedExit = null;
|
||||
$closedExit = -1;
|
||||
try {
|
||||
foreach ($pipes as $pipe) {
|
||||
stream_set_blocking($pipe, false);
|
||||
}
|
||||
$startedAt = microtime(true);
|
||||
$deadlineAt = is_int($request['deadline_at'] ?? null)
|
||||
? $request['deadline_at'] : time() + 60;
|
||||
$stopAt = min(
|
||||
$startedAt + 21605.0,
|
||||
max($startedAt + 1.0, (float) $deadlineAt + 5.0)
|
||||
);
|
||||
$offset = 0;
|
||||
$payloadBytes = strlen($payload);
|
||||
$stdinOpen = true;
|
||||
do {
|
||||
$remaining = $stopAt - microtime(true);
|
||||
if ($remaining <= 0) {
|
||||
$timedOut = true;
|
||||
self::terminateProcess($process);
|
||||
break;
|
||||
}
|
||||
|
||||
$read = [];
|
||||
if (is_resource($pipes[1]) && !feof($pipes[1])) {
|
||||
$read[] = $pipes[1];
|
||||
}
|
||||
if (is_resource($pipes[2]) && !feof($pipes[2])) {
|
||||
$read[] = $pipes[2];
|
||||
}
|
||||
$write = $stdinOpen && $offset < $payloadBytes
|
||||
? [$pipes[0]] : [];
|
||||
$except = [];
|
||||
if ($read !== [] || $write !== []) {
|
||||
$seconds = (int) floor(min($remaining, 0.1));
|
||||
$microseconds = (int) floor(
|
||||
(min($remaining, 0.1) - $seconds) * 1000000
|
||||
);
|
||||
$selected = @stream_select(
|
||||
$read,
|
||||
$write,
|
||||
$except,
|
||||
$seconds,
|
||||
max(1, $microseconds)
|
||||
);
|
||||
if ($selected === false) {
|
||||
$stdinFailed = true;
|
||||
self::terminateProcess($process);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
usleep((int) min(20000, max(1, $remaining * 1000000)));
|
||||
}
|
||||
|
||||
foreach ($read as $stream) {
|
||||
if ($stream === $pipes[1]) {
|
||||
$chunk = stream_get_contents(
|
||||
$stream,
|
||||
max(1, self::MAX_RECEIPT_BYTES + 1
|
||||
- strlen($stdout))
|
||||
);
|
||||
if (is_string($chunk)) {
|
||||
$stdout .= $chunk;
|
||||
}
|
||||
} else {
|
||||
$chunk = stream_get_contents(
|
||||
$stream,
|
||||
max(1, 65537 - $stderrBytes)
|
||||
);
|
||||
if (is_string($chunk)) {
|
||||
$stderrBytes += strlen($chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($write !== []) {
|
||||
$written = @fwrite(
|
||||
$pipes[0],
|
||||
substr($payload, $offset, 65536)
|
||||
);
|
||||
if ($written === false) {
|
||||
$stdinFailed = true;
|
||||
self::terminateProcess($process);
|
||||
break;
|
||||
}
|
||||
$offset += $written;
|
||||
}
|
||||
if ($stdinOpen && $offset === $payloadBytes) {
|
||||
fclose($pipes[0]);
|
||||
$stdinOpen = false;
|
||||
}
|
||||
|
||||
$status = proc_get_status($process);
|
||||
if (is_array($status)
|
||||
&& is_int($status['exitcode'] ?? null)
|
||||
&& $status['exitcode'] >= 0) {
|
||||
$observedExit = $status['exitcode'];
|
||||
}
|
||||
if (!is_array($status) || !($status['running'] ?? false)) {
|
||||
if ($offset !== $payloadBytes) {
|
||||
$stdinFailed = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (strlen($stdout) > self::MAX_RECEIPT_BYTES
|
||||
|| $stderrBytes > 65536) {
|
||||
self::terminateProcess($process);
|
||||
break;
|
||||
}
|
||||
} while (true);
|
||||
if (is_resource($pipes[1])) {
|
||||
$tail = stream_get_contents(
|
||||
$pipes[1],
|
||||
max(1, self::MAX_RECEIPT_BYTES + 1 - strlen($stdout))
|
||||
);
|
||||
if (is_string($tail)) {
|
||||
$stdout .= $tail;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
foreach ($pipes as $pipe) {
|
||||
if (is_resource($pipe)) {
|
||||
fclose($pipe);
|
||||
}
|
||||
}
|
||||
$closedExit = proc_close($process);
|
||||
}
|
||||
$exit = $closedExit >= 0 ? $closedExit : $observedExit;
|
||||
if ($stdinFailed || $timedOut
|
||||
|| strlen($stdout) > self::MAX_RECEIPT_BYTES
|
||||
|| $exit !== 0 || $stderrBytes > 65536) {
|
||||
return self::unknownReceipt(
|
||||
$protocol,
|
||||
$operationId,
|
||||
$stdinFailed ? 'replicator_stdin_failed'
|
||||
: ($timedOut ? 'replicator_timeout'
|
||||
: 'replicator_invalid_exit')
|
||||
);
|
||||
}
|
||||
try {
|
||||
$receipt = json_decode(
|
||||
$stdout,
|
||||
true,
|
||||
64,
|
||||
JSON_THROW_ON_ERROR
|
||||
);
|
||||
} catch (\JsonException) {
|
||||
return self::unknownReceipt(
|
||||
$protocol,
|
||||
$operationId,
|
||||
'replicator_invalid_receipt'
|
||||
);
|
||||
}
|
||||
if (!is_array($receipt)) {
|
||||
return self::unknownReceipt(
|
||||
$protocol,
|
||||
$operationId,
|
||||
'replicator_invalid_receipt'
|
||||
);
|
||||
}
|
||||
return self::normalizeReceipt($receipt, $protocol, $operationId);
|
||||
}
|
||||
|
||||
/** A failed or timed-out pipe exchange must not leave the helper alive. */
|
||||
private static function terminateProcess($process): void
|
||||
{
|
||||
@proc_terminate($process, 15);
|
||||
usleep(100000);
|
||||
$status = @proc_get_status($process);
|
||||
if (is_array($status) && ($status['running'] ?? false)) {
|
||||
@proc_terminate($process, 9);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $receipt @return array<string,mixed> */
|
||||
private static function normalizeReceipt(
|
||||
array $receipt,
|
||||
string $protocol,
|
||||
string $operationId
|
||||
): array {
|
||||
$allowed = [
|
||||
'protocol', 'operation_id', 'outcome', 'effect_resolution',
|
||||
'size_bytes', 'sha256', 'etag', 'version_id', 'error_code',
|
||||
];
|
||||
if (array_diff(array_keys($receipt), $allowed) !== []
|
||||
|| ($receipt['protocol'] ?? null) !== $protocol
|
||||
|| ($receipt['operation_id'] ?? null) !== $operationId
|
||||
|| !in_array($receipt['outcome'] ?? null,
|
||||
['succeeded', 'failed'], true)
|
||||
|| !in_array($receipt['effect_resolution'] ?? null,
|
||||
['applied', 'not_applied', 'unknown'], true)) {
|
||||
return self::unknownReceipt(
|
||||
$protocol,
|
||||
$operationId,
|
||||
'replicator_invalid_receipt'
|
||||
);
|
||||
}
|
||||
if ($receipt['outcome'] === 'succeeded') {
|
||||
$versionId = $receipt['version_id'] ?? '';
|
||||
if ($receipt['effect_resolution'] !== 'applied'
|
||||
|| (isset($receipt['error_code'])
|
||||
&& $receipt['error_code'] !== '')
|
||||
|| !is_int($receipt['size_bytes'] ?? null)
|
||||
|| $receipt['size_bytes'] < 1
|
||||
|| !is_string($receipt['sha256'] ?? null)
|
||||
|| preg_match('/^[a-f0-9]{64}$/D', $receipt['sha256']) !== 1
|
||||
|| !self::providerIdentity($receipt['etag'] ?? null, 256)
|
||||
|| !self::providerVersionIdentity(
|
||||
$versionId,
|
||||
1024
|
||||
)) {
|
||||
return self::unknownReceipt(
|
||||
$protocol,
|
||||
$operationId,
|
||||
'replicator_invalid_receipt'
|
||||
);
|
||||
}
|
||||
$receipt['version_id'] = $versionId;
|
||||
$receipt['error_code'] = '';
|
||||
} else {
|
||||
$code = $receipt['error_code'] ?? null;
|
||||
if (!in_array($receipt['effect_resolution'],
|
||||
['not_applied', 'unknown'], true)
|
||||
|| !is_string($code)
|
||||
|| preg_match('/^[a-z][a-z0-9_]{0,95}$/D', $code) !== 1) {
|
||||
return self::unknownReceipt(
|
||||
$protocol,
|
||||
$operationId,
|
||||
'replicator_invalid_receipt'
|
||||
);
|
||||
}
|
||||
}
|
||||
return $receipt;
|
||||
}
|
||||
|
||||
private static function providerIdentity($value, int $maximum): bool
|
||||
{
|
||||
return is_string($value) && $value !== ''
|
||||
&& strlen($value) <= $maximum
|
||||
&& preg_match('/[\x00-\x1f\x7f]/', $value) !== 1;
|
||||
}
|
||||
|
||||
private static function providerVersionIdentity(
|
||||
$value,
|
||||
int $maximum
|
||||
): bool {
|
||||
return is_string($value) && strlen($value) <= $maximum
|
||||
&& preg_match('/[\x00-\x1f\x7f]/', $value) !== 1;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private static function unknownReceipt(
|
||||
string $protocol,
|
||||
string $operationId,
|
||||
string $code
|
||||
): array {
|
||||
return [
|
||||
'protocol' => $protocol,
|
||||
'operation_id' => $operationId,
|
||||
'outcome' => 'failed',
|
||||
'effect_resolution' => 'unknown',
|
||||
'error_code' => $code,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,660 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudStorageBackend;
|
||||
|
||||
/**
|
||||
* Streams a pinned immutable replica and reconciles ambiguous completion from
|
||||
* read-only evidence. Capability URLs exist only inside this process.
|
||||
*/
|
||||
final class CloudStorageReplicaWorkerService
|
||||
{
|
||||
private const CAPABILITY_SECONDS = 21600;
|
||||
private const RECONCILE_DELAY = 60;
|
||||
|
||||
/** @var \Closure(int,bool):array<string,mixed> */
|
||||
private readonly \Closure $runtimeResolver;
|
||||
|
||||
/** @var \Closure():int */
|
||||
private readonly \Closure $clock;
|
||||
|
||||
/** @var list<string> */
|
||||
private array $errors = [];
|
||||
|
||||
/**
|
||||
* @param null|callable(int,bool):array<string,mixed> $runtimeResolver
|
||||
* @param null|callable():int $clock
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly ?CloudStorageReplicaHelper $helper = null,
|
||||
private readonly ?CloudObjectStorageS3Client $client = null,
|
||||
?callable $runtimeResolver = null,
|
||||
?callable $clock = null
|
||||
) {
|
||||
$this->runtimeResolver = $runtimeResolver === null
|
||||
? static fn (int $backendId, bool $healthy): array =>
|
||||
CloudObjectStorageBackendRegistry::runtime($backendId, $healthy)
|
||||
: \Closure::fromCallable($runtimeResolver);
|
||||
$this->clock = $clock === null
|
||||
? static fn (): int => time()
|
||||
: \Closure::fromCallable($clock);
|
||||
}
|
||||
|
||||
public function tick(): bool
|
||||
{
|
||||
$this->errors = [];
|
||||
$now = ($this->clock)();
|
||||
$work = CloudStorageArtifactService::claimReplicaWork($now);
|
||||
if ($work === null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
if (($work['mode'] ?? null) === 'dispatch') {
|
||||
$this->dispatch($work, $now);
|
||||
} else {
|
||||
$this->reconcile($work, $now);
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
$this->errors[] = 'storage_replica_tick_failed';
|
||||
try {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'storage_replica_tick_failed',
|
||||
is_array($work['metadata'] ?? null)
|
||||
? $work['metadata'] : []
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
// The durable lease remains the recovery fence. Never create
|
||||
// a replacement operation after an uncertain settlement.
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function observationErrors(): array
|
||||
{
|
||||
return $this->errors;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $work */
|
||||
private function dispatch(array $work, int $startedAt): void
|
||||
{
|
||||
if (!$this->validSource($work)) {
|
||||
$this->defer($work, 'replica_source_not_ready', 60);
|
||||
return;
|
||||
}
|
||||
$target = CloudStorageBackend::query()
|
||||
->whereKey((int) $work['target_backend_id'])->first();
|
||||
if (!$target instanceof CloudStorageBackend
|
||||
|| (string) $target->admin_state !== 'active'
|
||||
|| (string) $target->health_state !== 'healthy'
|
||||
|| (int) $target->tested_revision !== (int) $target->config_revision) {
|
||||
$this->defer($work, 'replica_target_not_writable', 300);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$sourceRuntime = ($this->runtimeResolver)(
|
||||
(int) $work['source_backend_id'],
|
||||
false
|
||||
);
|
||||
$targetRuntime = ($this->runtimeResolver)(
|
||||
(int) $work['target_backend_id'],
|
||||
true
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
$this->defer($work, 'replica_runtime_unavailable', 300);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$plan = $this->s3()->beginMultipartPlan(
|
||||
$targetRuntime['config'],
|
||||
$targetRuntime['credentials'],
|
||||
(string) $work['target_object_key'],
|
||||
(int) $work['size_bytes'],
|
||||
self::CAPABILITY_SECONDS
|
||||
);
|
||||
} catch (CloudObjectStorageTransferError $error) {
|
||||
if (!$error->effectMayHaveApplied) {
|
||||
$this->rescheduleNotApplied($work, $error->publicCode);
|
||||
return;
|
||||
}
|
||||
$this->markUnknown($work, $error->publicCode, []);
|
||||
return;
|
||||
} catch (\Throwable) {
|
||||
$this->markUnknown($work, 'replica_multipart_start_unknown', []);
|
||||
return;
|
||||
}
|
||||
|
||||
$metadata = [
|
||||
'upload_id' => (string) $plan['upload_id'],
|
||||
'part_size_bytes' => (int) $plan['part_size_bytes'],
|
||||
'part_count' => count($plan['part_urls']),
|
||||
'maximum_size_bytes' => (int) $plan['maximum_size_bytes'],
|
||||
'multipart_absence_confirmations' => 0,
|
||||
'multipart_presence_confirmations' => 0,
|
||||
];
|
||||
CloudStorageArtifactService::markReplicaAwaitingReceipt(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$metadata,
|
||||
($this->clock)()
|
||||
);
|
||||
$this->invokeTransfer(
|
||||
$work,
|
||||
$startedAt,
|
||||
$sourceRuntime,
|
||||
$targetRuntime,
|
||||
$plan,
|
||||
$metadata
|
||||
);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $work */
|
||||
private function reconcile(array $work, int $startedAt): void
|
||||
{
|
||||
$metadata = is_array($work['metadata'] ?? null)
|
||||
? $work['metadata'] : [];
|
||||
try {
|
||||
$runtime = ($this->runtimeResolver)(
|
||||
(int) $work['target_backend_id'],
|
||||
false
|
||||
);
|
||||
$identity = $this->s3()->inspectObject(
|
||||
$runtime['config'],
|
||||
$runtime['credentials'],
|
||||
(string) $work['target_object_key']
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replica_inspection_unavailable',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
if ($identity === null) {
|
||||
$this->reconcileAbsence(
|
||||
$work,
|
||||
$runtime,
|
||||
$metadata,
|
||||
$startedAt
|
||||
);
|
||||
return;
|
||||
}
|
||||
if ((int) $identity['size_bytes'] !== (int) $work['size_bytes']) {
|
||||
$this->errors[] = 'replica_identity_mismatch';
|
||||
CloudStorageArtifactService::failReplicaAppliedMismatch(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
'replica_identity_mismatch',
|
||||
($this->clock)()
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
$url = $this->s3()->presignedVersionedGet(
|
||||
$runtime['config'],
|
||||
$runtime['credentials'],
|
||||
(string) $work['target_object_key'],
|
||||
(string) $identity['version_id'],
|
||||
self::CAPABILITY_SECONDS
|
||||
);
|
||||
$receipt = $this->mover()->invoke([
|
||||
'protocol' => 'object-replica-verify-v1',
|
||||
'operation_id' => (string) $work['operation_id'],
|
||||
'deadline_at' => $startedAt + self::CAPABILITY_SECONDS,
|
||||
'get_url' => $url,
|
||||
'size_bytes' => (int) $work['size_bytes'],
|
||||
'sha256' => (string) $work['sha256'],
|
||||
]);
|
||||
} catch (\Throwable) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replica_verify_unavailable',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
$this->settleReceipt($work, $receipt, $metadata, $identity);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $work
|
||||
* @param array<string,mixed> $runtime
|
||||
* @param array<string,mixed> $metadata
|
||||
*/
|
||||
private function reconcileAbsence(
|
||||
array $work,
|
||||
array $runtime,
|
||||
array $metadata,
|
||||
int $startedAt
|
||||
): void {
|
||||
try {
|
||||
$matches = $this->s3()->findMultipartUploadsByExactObjectKey(
|
||||
$runtime['config'],
|
||||
$runtime['credentials'],
|
||||
(string) $work['target_object_key']
|
||||
);
|
||||
} catch (CloudObjectStorageTransferError $error) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
$error->publicCode,
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
} catch (\Throwable) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replica_multipart_lookup_unknown',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (count($matches) > 1) {
|
||||
$this->markMultipartAttention(
|
||||
$work,
|
||||
'replica_multipart_identity_ambiguous',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (count($matches) === 1) {
|
||||
$match = $matches[0];
|
||||
if (isset($metadata['upload_id'])) {
|
||||
if (!hash_equals(
|
||||
(string) $metadata['upload_id'],
|
||||
(string) $match['upload_id']
|
||||
)) {
|
||||
$this->markMultipartAttention(
|
||||
$work,
|
||||
'replica_multipart_identity_mismatch',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
$metadata['multipart_presence_confirmations'] = min(
|
||||
2,
|
||||
(int) ($metadata['multipart_presence_confirmations'] ?? 0)
|
||||
+ 1
|
||||
);
|
||||
if ($metadata['multipart_presence_confirmations'] < 2) {
|
||||
// The exact session and absent object must remain stable
|
||||
// across two leases before replaying idempotent UploadPart
|
||||
// calls against that same upload_id.
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replica_multipart_present_unconfirmed',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!$this->adoptableMultipart($work, $match, $startedAt)
|
||||
|| !$this->validSource($work)) {
|
||||
$this->markMultipartAttention(
|
||||
$work,
|
||||
'replica_multipart_identity_untrusted',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
$sourceRuntime = ($this->runtimeResolver)(
|
||||
(int) $work['source_backend_id'],
|
||||
false
|
||||
);
|
||||
$plan = $this->s3()->resumeMultipartUpload(
|
||||
$runtime['config'],
|
||||
$runtime['credentials'],
|
||||
(string) $work['target_object_key'],
|
||||
(string) $match['upload_id'],
|
||||
(int) $work['size_bytes'],
|
||||
($this->clock)(),
|
||||
self::CAPABILITY_SECONDS
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replica_multipart_resume_unknown',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
$adopted = [
|
||||
'upload_id' => (string) $plan['upload_id'],
|
||||
'part_size_bytes' => (int) $plan['part_size_bytes'],
|
||||
'part_count' => count($plan['part_urls']),
|
||||
'maximum_size_bytes' => (int) $plan['maximum_size_bytes'],
|
||||
'multipart_absence_confirmations' => 0,
|
||||
'multipart_presence_confirmations' => isset(
|
||||
$metadata['upload_id']
|
||||
) ? 2 : 0,
|
||||
'initiated_at' => (int) $match['initiated_at'],
|
||||
];
|
||||
CloudStorageArtifactService::markReplicaAwaitingReceipt(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$adopted,
|
||||
($this->clock)()
|
||||
);
|
||||
$this->invokeTransfer(
|
||||
$work,
|
||||
$startedAt,
|
||||
$sourceRuntime,
|
||||
$runtime,
|
||||
$plan,
|
||||
$adopted
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
$metadata['multipart_absence_confirmations'] = min(
|
||||
2,
|
||||
(int) ($metadata['multipart_absence_confirmations'] ?? 0) + 1
|
||||
);
|
||||
if ($metadata['multipart_absence_confirmations'] < 2) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replica_multipart_absent_unconfirmed',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
CloudStorageArtifactService::rescheduleReplicaAfterProof(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$metadata,
|
||||
($this->clock)(),
|
||||
self::RECONCILE_DELAY
|
||||
);
|
||||
$this->errors[] = 'replica_retry_scheduled';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $work
|
||||
* @param array<string,mixed> $receipt
|
||||
* @param array<string,mixed> $metadata
|
||||
* @param array<string,mixed>|null $observedIdentity
|
||||
*/
|
||||
private function settleReceipt(
|
||||
array $work,
|
||||
array $receipt,
|
||||
array $metadata,
|
||||
?array $observedIdentity
|
||||
): void {
|
||||
$now = ($this->clock)();
|
||||
if (($receipt['outcome'] ?? null) === 'succeeded'
|
||||
&& ($receipt['effect_resolution'] ?? null) === 'applied') {
|
||||
$observedVersion = (string) (
|
||||
$observedIdentity['version_id'] ?? ''
|
||||
);
|
||||
$receiptVersion = (string) ($receipt['version_id'] ?? '');
|
||||
$mixedVersionIdentity = ($observedVersion === '')
|
||||
!== ($receiptVersion === '');
|
||||
$identityChanged = $observedIdentity !== null
|
||||
&& ((int) ($observedIdentity['size_bytes'] ?? 0)
|
||||
!== (int) ($receipt['size_bytes'] ?? 0)
|
||||
|| (int) ($observedIdentity['size_bytes'] ?? 0)
|
||||
!== (int) $work['size_bytes']
|
||||
|| $mixedVersionIdentity
|
||||
|| !hash_equals(
|
||||
(string) ($observedIdentity['etag'] ?? ''),
|
||||
(string) ($receipt['etag'] ?? '')
|
||||
)
|
||||
|| ($observedVersion !== ''
|
||||
&& !hash_equals(
|
||||
$observedVersion,
|
||||
$receiptVersion
|
||||
)));
|
||||
if ($identityChanged) {
|
||||
$this->errors[] = 'replica_identity_changed';
|
||||
CloudStorageArtifactService::failReplicaAppliedMismatch(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
'replica_identity_changed',
|
||||
$now
|
||||
);
|
||||
return;
|
||||
}
|
||||
CloudStorageArtifactService::completeReplica(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$receipt,
|
||||
$now
|
||||
);
|
||||
return;
|
||||
}
|
||||
$code = is_string($receipt['error_code'] ?? null)
|
||||
? $receipt['error_code'] : 'replicator_invalid_receipt';
|
||||
if (($receipt['effect_resolution'] ?? null) === 'not_applied') {
|
||||
if ($observedIdentity !== null) {
|
||||
$this->errors[] = $code;
|
||||
CloudStorageArtifactService::failReplicaAppliedMismatch(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$code,
|
||||
$now
|
||||
);
|
||||
} else {
|
||||
$this->rescheduleNotApplied($work, $code);
|
||||
}
|
||||
return;
|
||||
}
|
||||
$this->markUnknown($work, $code, $metadata);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $work @param array<string,mixed> $metadata */
|
||||
private function markUnknown(
|
||||
array $work,
|
||||
string $errorCode,
|
||||
array $metadata
|
||||
): void {
|
||||
$this->errors[] = $errorCode;
|
||||
CloudStorageArtifactService::markReplicaUnknown(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$errorCode,
|
||||
($this->clock)(),
|
||||
self::RECONCILE_DELAY,
|
||||
$metadata
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bound stable multipart identity conflicts. Automatic reconciliation
|
||||
* stops after two observations; an administrator may then re-open this
|
||||
* same operation after correcting the provider-side sessions.
|
||||
*
|
||||
* @param array<string,mixed> $work
|
||||
* @param array<string,mixed> $metadata
|
||||
*/
|
||||
private function markMultipartAttention(
|
||||
array $work,
|
||||
string $errorCode,
|
||||
array $metadata
|
||||
): void {
|
||||
$previous = $metadata['multipart_attention_error_code'] ?? '';
|
||||
$confirmations = $previous === $errorCode
|
||||
? (int) ($metadata['multipart_attention_confirmations'] ?? 0) + 1
|
||||
: 1;
|
||||
$metadata['multipart_attention_error_code'] = $errorCode;
|
||||
$metadata['multipart_attention_confirmations'] = min(
|
||||
2,
|
||||
$confirmations
|
||||
);
|
||||
if ($metadata['multipart_attention_confirmations'] < 2) {
|
||||
$this->markUnknown($work, $errorCode, $metadata);
|
||||
return;
|
||||
}
|
||||
$this->errors[] = $errorCode;
|
||||
CloudStorageArtifactService::markReplicaAttention(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$errorCode,
|
||||
($this->clock)(),
|
||||
$metadata
|
||||
);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $work */
|
||||
private function defer(array $work, string $code, int $delay): void
|
||||
{
|
||||
$this->errors[] = $code;
|
||||
CloudStorageArtifactService::deferReplica(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$code,
|
||||
($this->clock)(),
|
||||
$delay
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A definite no-effect result means either multipart creation never
|
||||
* happened or the helper proved no object was committed and ended its
|
||||
* session. Re-open the same durable copy intent; never allocate a
|
||||
* replacement operation.
|
||||
*
|
||||
* @param array<string,mixed> $work
|
||||
*/
|
||||
private function rescheduleNotApplied(array $work, string $code): void
|
||||
{
|
||||
$this->errors[] = $code;
|
||||
CloudStorageArtifactService::rescheduleReplicaNotApplied(
|
||||
(string) $work['operation_id'],
|
||||
(string) $work['lease_token'],
|
||||
$code,
|
||||
($this->clock)(),
|
||||
self::RECONCILE_DELAY
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $work
|
||||
* @param array{upload_id:string,initiated_at:int} $match
|
||||
*/
|
||||
private function adoptableMultipart(
|
||||
array $work,
|
||||
array $match,
|
||||
int $now
|
||||
): bool {
|
||||
$createdAt = $work['operation_created_at'] ?? null;
|
||||
$availableAt = $work['operation_available_at'] ?? null;
|
||||
$initiatedAt = $match['initiated_at'] ?? null;
|
||||
return is_int($createdAt)
|
||||
&& is_int($availableAt)
|
||||
&& is_int($initiatedAt)
|
||||
&& $initiatedAt >= max(1, $createdAt, $availableAt) - 300
|
||||
&& $initiatedAt <= $now + 60;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $work
|
||||
* @param array<string,mixed> $sourceRuntime
|
||||
* @param array<string,mixed> $targetRuntime
|
||||
* @param array<string,mixed> $plan
|
||||
* @param array<string,mixed> $metadata
|
||||
*/
|
||||
private function invokeTransfer(
|
||||
array $work,
|
||||
int $startedAt,
|
||||
array $sourceRuntime,
|
||||
array $targetRuntime,
|
||||
array $plan,
|
||||
array $metadata
|
||||
): void {
|
||||
try {
|
||||
$sourceURL = $this->s3()->presignedVersionedGet(
|
||||
$sourceRuntime['config'],
|
||||
$sourceRuntime['credentials'],
|
||||
(string) $work['source_object_key'],
|
||||
(string) $work['source_version_id'],
|
||||
self::CAPABILITY_SECONDS
|
||||
);
|
||||
$receipt = $this->mover()->invoke([
|
||||
'protocol' => 'object-replica-v1',
|
||||
'operation_id' => (string) $work['operation_id'],
|
||||
'deadline_at' => $startedAt + self::CAPABILITY_SECONDS,
|
||||
'source' => [
|
||||
'get_url' => $sourceURL,
|
||||
'size_bytes' => (int) $work['size_bytes'],
|
||||
'sha256' => (string) $work['sha256'],
|
||||
],
|
||||
'destination' => self::helperPlan($plan),
|
||||
]);
|
||||
} catch (\Throwable) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replicator_invalid_receipt',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
$identity = null;
|
||||
if (($receipt['outcome'] ?? null) === 'succeeded'
|
||||
&& ($receipt['effect_resolution'] ?? null) === 'applied') {
|
||||
try {
|
||||
$identity = $this->s3()->inspectObject(
|
||||
$targetRuntime['config'],
|
||||
$targetRuntime['credentials'],
|
||||
(string) $work['target_object_key']
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replica_completion_inspection_unavailable',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
if ($identity === null) {
|
||||
$this->markUnknown(
|
||||
$work,
|
||||
'replica_completion_object_absent',
|
||||
$metadata
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
$this->settleReceipt($work, $receipt, $metadata, $identity);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $work */
|
||||
private function validSource(array $work): bool
|
||||
{
|
||||
return ($work['source_state'] ?? null) === 'ready'
|
||||
&& is_int($work['size_bytes'] ?? null)
|
||||
&& $work['size_bytes'] > 0
|
||||
&& is_string($work['sha256'] ?? null)
|
||||
&& preg_match('/^[a-f0-9]{64}$/D', $work['sha256']) === 1
|
||||
&& is_string($work['source_version_id'] ?? null);
|
||||
}
|
||||
|
||||
private function s3(): CloudObjectStorageS3Client
|
||||
{
|
||||
return $this->client ?? new CloudObjectStorageS3Client();
|
||||
}
|
||||
|
||||
private function mover(): CloudStorageReplicaHelper
|
||||
{
|
||||
return $this->helper ?? new CloudStorageReplicaHelper();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $plan @return array<string,mixed> */
|
||||
private static function helperPlan(array $plan): array
|
||||
{
|
||||
return [
|
||||
'part_size_bytes' => (int) $plan['part_size_bytes'],
|
||||
'part_urls' => array_values($plan['part_urls']),
|
||||
'complete_url' => (string) $plan['complete_url'],
|
||||
'abort_url' => (string) $plan['abort_url'],
|
||||
'verify_url' => (string) $plan['verify_url'],
|
||||
'maximum_size_bytes' => (int) $plan['maximum_size_bytes'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,926 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudStorageArtifact;
|
||||
use App\Models\CloudStorageBackend;
|
||||
use App\Models\CloudStorageOperation;
|
||||
use App\Models\CloudStoragePublication;
|
||||
use App\Models\CloudStorageReplica;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudStorageArtifactService;
|
||||
use App\Services\Cloud\CloudObjectStorageS3Client;
|
||||
use App\Services\Cloud\CloudStorageReplicaHelper;
|
||||
use App\Services\Cloud\CloudStorageReplicaAttentionService;
|
||||
use App\Services\Cloud\CloudStorageReplicaWorkerService;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$expect = static function (callable $callback, int $status) use ($assert): void {
|
||||
try {
|
||||
$callback();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === $status,
|
||||
'Unexpected CloudError status: ' . $error->httpStatus);
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException('Expected CloudError was not raised.');
|
||||
};
|
||||
|
||||
$db = new Capsule();
|
||||
$db->addConnection(['driver' => 'sqlite', 'database' => ':memory:']);
|
||||
$db->setAsGlobal();
|
||||
$db->bootEloquent();
|
||||
$db->schema()->create('cloud_storage_backends', static function (Blueprint $t): void {
|
||||
$t->increments('id');
|
||||
$t->string('backend_key'); $t->string('identity_sha256');
|
||||
$t->string('name'); $t->string('driver'); $t->string('endpoint');
|
||||
$t->string('region'); $t->string('bucket'); $t->string('prefix');
|
||||
$t->boolean('path_style'); $t->string('failure_domain');
|
||||
$t->text('sealed_credentials'); $t->unsignedBigInteger('config_revision');
|
||||
$t->unsignedBigInteger('tested_revision'); $t->string('admin_state');
|
||||
$t->string('health_state'); $t->unsignedInteger('write_priority');
|
||||
$t->unsignedInteger('consecutive_failures')->default(0);
|
||||
$t->unsignedInteger('consecutive_successes')->default(0);
|
||||
$t->string('last_error_code')->default('');
|
||||
$t->unsignedBigInteger('last_tested_at')->default(0);
|
||||
$t->unsignedBigInteger('last_healthy_at')->default(0);
|
||||
$t->unsignedBigInteger('next_probe_at')->default(0);
|
||||
$t->unsignedBigInteger('created_at'); $t->unsignedBigInteger('updated_at');
|
||||
});
|
||||
$db->schema()->create('cloud_storage_artifacts', static function (Blueprint $t): void {
|
||||
$t->increments('id'); $t->string('artifact_key')->unique();
|
||||
$t->string('kind'); $t->unsignedBigInteger('maximum_size_bytes');
|
||||
$t->unsignedBigInteger('size_bytes');
|
||||
$t->string('sha256'); $t->string('durability_policy');
|
||||
$t->unsignedTinyInteger('desired_copies');
|
||||
$t->unsignedTinyInteger('required_copies'); $t->string('state');
|
||||
$t->string('last_operation_id')->nullable();
|
||||
$t->unsignedBigInteger('verified_at');
|
||||
$t->unsignedBigInteger('created_at'); $t->unsignedBigInteger('updated_at');
|
||||
});
|
||||
$db->schema()->create('cloud_storage_replicas', static function (Blueprint $t): void {
|
||||
$t->increments('id'); $t->string('replica_key')->unique();
|
||||
$t->unsignedBigInteger('artifact_id'); $t->unsignedBigInteger('backend_id');
|
||||
$t->string('role'); $t->string('object_key');
|
||||
$t->string('object_version_id')->default('');
|
||||
$t->string('object_etag')->default('');
|
||||
$t->unsignedBigInteger('size_bytes')->default(0); $t->string('sha256')->default('');
|
||||
$t->string('state'); $t->string('publish_operation_id')->nullable();
|
||||
$t->string('delete_operation_id')->nullable();
|
||||
$t->unsignedInteger('delete_generation')->default(0);
|
||||
$t->unsignedInteger('delete_cycle_attempts')->default(0);
|
||||
$t->unsignedInteger('delete_presence_confirmations')->default(0);
|
||||
$t->unsignedBigInteger('delete_last_checked_at')->default(0);
|
||||
$t->unsignedBigInteger('delete_next_check_at')->default(0);
|
||||
$t->unsignedBigInteger('delete_attention_at')->nullable();
|
||||
$t->string('lease_token')->nullable(); $t->unsignedBigInteger('lease_until')->default(0);
|
||||
$t->string('error_code')->default(''); $t->unsignedBigInteger('verified_at')->default(0);
|
||||
$t->unsignedBigInteger('created_at'); $t->unsignedBigInteger('updated_at');
|
||||
});
|
||||
$db->schema()->create('cloud_storage_operations', static function (Blueprint $t): void {
|
||||
$t->increments('id'); $t->string('operation_id')->unique();
|
||||
$t->string('request_idempotency_key')->unique();
|
||||
$t->string('request_fingerprint'); $t->unsignedBigInteger('artifact_id');
|
||||
$t->unsignedBigInteger('replica_id')->nullable();
|
||||
$t->unsignedBigInteger('source_backend_id')->nullable();
|
||||
$t->unsignedBigInteger('target_backend_id')->nullable();
|
||||
$t->string('kind'); $t->string('phase'); $t->string('outcome')->nullable();
|
||||
$t->string('effect_resolution'); $t->boolean('effect_may_have_applied')->nullable();
|
||||
$t->boolean('safe_to_resubmit')->nullable(); $t->unsignedInteger('attempts');
|
||||
$t->string('lease_token')->nullable(); $t->unsignedBigInteger('lease_until');
|
||||
$t->unsignedBigInteger('available_at'); $t->unsignedBigInteger('next_check_at');
|
||||
$t->string('error_code'); $t->text('result_json')->nullable();
|
||||
$t->unsignedBigInteger('terminal_at')->nullable();
|
||||
$t->unsignedBigInteger('created_at'); $t->unsignedBigInteger('updated_at');
|
||||
});
|
||||
$db->schema()->create('cloud_storage_publications', static function (Blueprint $t): void {
|
||||
$t->increments('id'); $t->string('publication_key')->unique();
|
||||
$t->unsignedBigInteger('artifact_id')->unique();
|
||||
$t->unsignedBigInteger('backup_id')->nullable()->unique();
|
||||
$t->string('template_import_intent_id')->nullable()->unique();
|
||||
$t->string('rescue_template_id')->nullable()->unique();
|
||||
$t->string('state'); $t->unsignedInteger('attempts')->default(0);
|
||||
$t->unsignedBigInteger('available_at')->default(0);
|
||||
$t->string('lease_token')->nullable();
|
||||
$t->unsignedBigInteger('lease_until')->default(0);
|
||||
$t->string('last_error_code')->default('');
|
||||
$t->unsignedBigInteger('coverage_ready_at')->nullable();
|
||||
$t->unsignedBigInteger('finalized_at')->nullable();
|
||||
$t->unsignedBigInteger('created_at'); $t->unsignedBigInteger('updated_at');
|
||||
});
|
||||
|
||||
$now = time();
|
||||
foreach ([
|
||||
[1, 'provider-a', 10, 'primary'],
|
||||
[2, 'provider-b', 20, 'secondary'],
|
||||
] as [$id, $domain, $priority, $name]) {
|
||||
Capsule::table('cloud_storage_backends')->insert([
|
||||
'id' => $id, 'backend_key' => str_repeat((string) $id, 32),
|
||||
'identity_sha256' => str_repeat((string) $id, 64),
|
||||
'name' => $name, 'driver' => 's3',
|
||||
'endpoint' => 'https://' . $name . '.example.test',
|
||||
'region' => 'us-east-1', 'bucket' => $name . '-bucket',
|
||||
'prefix' => $name, 'path_style' => 1,
|
||||
'failure_domain' => $domain, 'sealed_credentials' => 'sealed',
|
||||
'config_revision' => 1, 'tested_revision' => 1,
|
||||
'admin_state' => 'active', 'health_state' => 'healthy',
|
||||
'write_priority' => $priority, 'consecutive_failures' => 0,
|
||||
'consecutive_successes' => 1, 'last_error_code' => '',
|
||||
'last_tested_at' => $now, 'last_healthy_at' => $now,
|
||||
'next_probe_at' => $now + 300, 'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
$requestKey = 'backup-publication-0001';
|
||||
$fingerprint = hash('sha256', 'fixture');
|
||||
$view = CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/fixture/system.qcow2', 4096,
|
||||
str_repeat('a', 64), $requestKey, $fingerprint,
|
||||
['backup_id' => 1]
|
||||
);
|
||||
$assert($view['can_publish'] && $view['backend_id'] === 1
|
||||
&& CloudStorageArtifact::count() === 1
|
||||
&& CloudStorageReplica::count() === 2
|
||||
&& CloudStorageOperation::where('kind', 'copy')->count() === 1,
|
||||
'Publication did not reserve one primary and one secondary operation.');
|
||||
$again = CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/fixture/system.qcow2', 4096,
|
||||
str_repeat('a', 64), $requestKey, $fingerprint,
|
||||
['backup_id' => 1]
|
||||
);
|
||||
$assert($again['operation_id'] === $view['operation_id']
|
||||
&& CloudStorageArtifact::count() === 1,
|
||||
'Idempotent publication allocated a second artifact.');
|
||||
$expect(static fn () => CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/other/system.qcow2', 4096,
|
||||
str_repeat('a', 64), $requestKey, hash('sha256', 'different'),
|
||||
['backup_id' => 1]
|
||||
), 409);
|
||||
$assert(CloudStorageArtifactService::claimReplicaWork(time()) === null,
|
||||
'Secondary copy became claimable before the primary was verified.');
|
||||
|
||||
CloudStorageArtifactService::markPrimaryDispatching($view['operation_id']);
|
||||
$expect(static fn () => CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$view['operation_id']
|
||||
), 409);
|
||||
$complete = CloudStorageArtifactService::completePrimary(
|
||||
$view['operation_id'],
|
||||
[
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('a', 64),
|
||||
'etag' => '"etag"', 'version_id' => '',
|
||||
]
|
||||
);
|
||||
$artifact = CloudStorageArtifact::firstOrFail();
|
||||
$primary = CloudStorageReplica::where('role', 'primary')->firstOrFail();
|
||||
$copy = CloudStorageOperation::where('kind', 'copy')->firstOrFail();
|
||||
$assert($complete['outcome'] === 'succeeded'
|
||||
&& (string) $artifact->state === 'available'
|
||||
&& (string) $primary->state === 'ready'
|
||||
&& (string) $copy->phase === 'accepted',
|
||||
'Primary settlement did not expose an async backup or retain copy work.');
|
||||
CloudStorageArtifactService::completePrimary($view['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('a', 64),
|
||||
'etag' => '"etag"', 'version_id' => '',
|
||||
]);
|
||||
$expect(static fn () => CloudStorageArtifactService::completePrimary(
|
||||
$view['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('a', 64),
|
||||
'etag' => '"different"', 'version_id' => '',
|
||||
]
|
||||
), 409);
|
||||
$publication = CloudStoragePublication::firstOrFail();
|
||||
$assert((string) $publication->state === 'ready_to_finalize'
|
||||
&& (int) $publication->coverage_ready_at > 0,
|
||||
'Required primary coverage did not release the durable finalizer signal.');
|
||||
|
||||
$claimed = CloudStorageArtifactService::claimReplicaWork(time());
|
||||
$assert(is_array($claimed) && $claimed['mode'] === 'dispatch'
|
||||
&& $claimed['source_version_id'] === '',
|
||||
'Versionless secondary copy was not leased from the durable operation.');
|
||||
$assert(CloudStorageArtifactService::claimReplicaWork(time() + 21600) === null,
|
||||
'A second worker reclaimed a copy before the helper deadline elapsed.');
|
||||
$metadata = [
|
||||
'upload_id' => 'upload-1', 'part_size_bytes' => 67108864,
|
||||
'part_count' => 1, 'maximum_size_bytes' => 4096,
|
||||
'absence_confirmations' => 0,
|
||||
];
|
||||
CloudStorageArtifactService::markReplicaAwaitingReceipt(
|
||||
$claimed['operation_id'], $claimed['lease_token'], $metadata, time()
|
||||
);
|
||||
$stored = (string) CloudStorageOperation::where(
|
||||
'operation_id', $claimed['operation_id']
|
||||
)->value('result_json');
|
||||
$assert(!str_contains($stored, 'http') && str_contains($stored, 'upload-1'),
|
||||
'Durable operation persisted a capability URL or lost its upload identity.');
|
||||
CloudStorageArtifactService::completeReplica(
|
||||
$claimed['operation_id'], $claimed['lease_token'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('a', 64),
|
||||
'etag' => '"secondary"', 'version_id' => '',
|
||||
], time()
|
||||
);
|
||||
CloudStorageArtifactService::completeReplica(
|
||||
$claimed['operation_id'], $claimed['lease_token'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('a', 64),
|
||||
'etag' => '"secondary"', 'version_id' => '',
|
||||
], time()
|
||||
);
|
||||
$expect(static fn () => CloudStorageArtifactService::completeReplica(
|
||||
$claimed['operation_id'], $claimed['lease_token'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('a', 64),
|
||||
'etag' => '"secondary"', 'version_id' => 'unexpected-version',
|
||||
], time()
|
||||
), 409);
|
||||
$assert((string) CloudStorageArtifact::firstOrFail()->state === 'protected'
|
||||
&& CloudStorageReplica::where('state', 'ready')->count() === 2,
|
||||
'Versionless secondary receipt did not protect the artifact.');
|
||||
|
||||
$agentView = CloudStorageArtifactService::beginAgentPublication(
|
||||
'backup', 'backups/agent/system.qcow2', 8192,
|
||||
'backup-publication-0002', hash('sha256', 'agent'),
|
||||
['backup_id' => 2]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching($agentView['operation_id']);
|
||||
CloudStorageArtifactService::completePrimary($agentView['operation_id'], [
|
||||
'size_bytes' => 6144, 'sha256' => str_repeat('c', 64),
|
||||
'etag' => '"agent"', 'version_id' => '',
|
||||
]);
|
||||
$agentArtifact = CloudStorageArtifact::whereKey(
|
||||
$agentView['artifact_id']
|
||||
)->firstOrFail();
|
||||
$assert((int) $agentArtifact->maximum_size_bytes === 8192
|
||||
&& (int) $agentArtifact->size_bytes === 6144
|
||||
&& (string) $agentArtifact->sha256 === str_repeat('c', 64),
|
||||
'Agent publication did not freeze its bounded receipt identity.');
|
||||
|
||||
$capturedRequest = null;
|
||||
$mock = new MockHandler([
|
||||
new Response(200, [], '<InitiateMultipartUploadResult>'
|
||||
. '<UploadId>worker-upload</UploadId>'
|
||||
. '</InitiateMultipartUploadResult>'),
|
||||
new Response(200, [
|
||||
'Content-Length' => '6144',
|
||||
'ETag' => '"worker"',
|
||||
]),
|
||||
]);
|
||||
$s3 = new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create($mock),
|
||||
]));
|
||||
$helper = new CloudStorageReplicaHelper(null,
|
||||
static function (array $request) use (&$capturedRequest): array {
|
||||
$capturedRequest = $request;
|
||||
return [
|
||||
'protocol' => $request['protocol'],
|
||||
'operation_id' => $request['operation_id'],
|
||||
'outcome' => 'succeeded',
|
||||
'effect_resolution' => 'applied',
|
||||
'size_bytes' => 6144,
|
||||
'sha256' => str_repeat('c', 64),
|
||||
'etag' => '"worker"',
|
||||
'version_id' => '',
|
||||
];
|
||||
}
|
||||
);
|
||||
$runtime = static fn (int $backendId, bool $healthy): array => [
|
||||
'config' => [
|
||||
'endpoint' => 'https://storage-' . $backendId . '.example.test',
|
||||
'region' => 'us-east-1', 'bucket' => 'bucket-' . $backendId,
|
||||
'path_style' => true, 'prefix' => '',
|
||||
],
|
||||
'credentials' => [
|
||||
'access_key_id' => 'access-key',
|
||||
'secret_access_key' => 'secret-key',
|
||||
],
|
||||
'revision' => 1, 'backend_id' => $backendId,
|
||||
];
|
||||
$worker = new CloudStorageReplicaWorkerService($helper, $s3, $runtime);
|
||||
$assert($worker->tick() && is_array($capturedRequest)
|
||||
&& $capturedRequest['protocol'] === 'object-replica-v1'
|
||||
&& !str_contains($capturedRequest['source']['get_url'], 'versionId='),
|
||||
'Replica worker did not stream a versionless exact-key source.');
|
||||
$agentCopy = CloudStorageOperation::where('artifact_id', $agentArtifact->id)
|
||||
->where('kind', 'copy')->firstOrFail();
|
||||
$assert((string) $agentCopy->phase === 'terminal'
|
||||
&& (string) $agentCopy->outcome === 'succeeded'
|
||||
&& !str_contains((string) $agentCopy->result_json, 'https://'),
|
||||
'Replica worker did not settle safely or persisted a capability URL.');
|
||||
|
||||
$unknownView = CloudStorageArtifactService::beginPublication(
|
||||
'template', 'cloud-templates/unknown/system.qcow2', 4096,
|
||||
str_repeat('e', 64), 'template-publication-0003',
|
||||
hash('sha256', 'unknown'), [
|
||||
'template_import_intent_id' => str_repeat('e', 32),
|
||||
]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$unknownView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::completePrimary($unknownView['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('e', 64),
|
||||
'etag' => '"unknown-primary"',
|
||||
'version_id' => '',
|
||||
]);
|
||||
$copyCalls = 0;
|
||||
$unknownHelper = new CloudStorageReplicaHelper(null,
|
||||
static function (array $request) use (&$copyCalls): array {
|
||||
$copyCalls++;
|
||||
return [
|
||||
'protocol' => $request['protocol'],
|
||||
// A mismatched receipt must become unknown, never success.
|
||||
'operation_id' => str_repeat('f', 32),
|
||||
'outcome' => 'succeeded', 'effect_resolution' => 'applied',
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('e', 64),
|
||||
'etag' => '"wrong-operation"', 'version_id' => '',
|
||||
];
|
||||
}
|
||||
);
|
||||
$unknownHTTP = new MockHandler([
|
||||
new Response(200, [], '<InitiateMultipartUploadResult>'
|
||||
. '<UploadId>unknown-upload</UploadId>'
|
||||
. '</InitiateMultipartUploadResult>'),
|
||||
new Response(404),
|
||||
new Response(200, [], '<ListMultipartUploadsResult>'
|
||||
. '<IsTruncated>false</IsTruncated>'
|
||||
. '</ListMultipartUploadsResult>'),
|
||||
new Response(404),
|
||||
new Response(200, [], '<ListMultipartUploadsResult>'
|
||||
. '<IsTruncated>false</IsTruncated>'
|
||||
. '</ListMultipartUploadsResult>'),
|
||||
]);
|
||||
$unknownWorker = new CloudStorageReplicaWorkerService(
|
||||
$unknownHelper,
|
||||
new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create($unknownHTTP),
|
||||
])),
|
||||
$runtime
|
||||
);
|
||||
$unknownWorker->tick();
|
||||
$unknownCopy = CloudStorageOperation::where(
|
||||
'artifact_id', $unknownView['artifact_id']
|
||||
)->where('kind', 'copy')->firstOrFail();
|
||||
$assert((string) $unknownCopy->phase === 'reconciling'
|
||||
&& (string) $unknownCopy->effect_resolution === 'unknown',
|
||||
'Mismatched helper receipt did not preserve unknown effect.');
|
||||
$unknownCopy->next_check_at = 0;
|
||||
$unknownCopy->save();
|
||||
$unknownWorker->tick();
|
||||
$unknownCopy->refresh();
|
||||
$unknownMetadata = json_decode((string) $unknownCopy->result_json, true);
|
||||
$assert($copyCalls === 1 && (string) $unknownCopy->phase === 'reconciling'
|
||||
&& ($unknownMetadata['multipart_absence_confirmations'] ?? null) === 1,
|
||||
'Unknown copy was replayed instead of read-only reconciliation.');
|
||||
$unknownCopy->next_check_at = 0;
|
||||
$unknownCopy->save();
|
||||
$unknownWorker->tick();
|
||||
$unknownCopy->refresh();
|
||||
$unknownPublication = CloudStoragePublication::where(
|
||||
'artifact_id', $unknownView['artifact_id']
|
||||
)->firstOrFail();
|
||||
$assert($copyCalls === 1 && (string) $unknownCopy->phase === 'accepted'
|
||||
&& (int) $unknownCopy->attempts === 1
|
||||
&& $unknownCopy->result_json === null
|
||||
&& in_array(
|
||||
'replica_retry_scheduled',
|
||||
$unknownWorker->observationErrors(),
|
||||
true
|
||||
)
|
||||
&& (string) $unknownPublication->state === 'waiting_protection',
|
||||
'Required-two copy was not safely rescheduled after read-only absence proof: '
|
||||
. json_encode([
|
||||
'calls' => $copyCalls, 'phase' => $unknownCopy->phase,
|
||||
'attempts' => $unknownCopy->attempts,
|
||||
'result' => $unknownCopy->result_json,
|
||||
'publication' => $unknownPublication->state,
|
||||
'error' => $unknownCopy->error_code,
|
||||
]));
|
||||
$unknownCopy->available_at = 253402300799;
|
||||
$unknownCopy->save();
|
||||
|
||||
$retryView = CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/retry/system.qcow2', 4096,
|
||||
str_repeat('f', 64), 'backup-publication-0005',
|
||||
hash('sha256', 'retry'), ['backup_id' => 5]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$retryView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::completePrimary($retryView['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('f', 64),
|
||||
'etag' => '"retry-primary"',
|
||||
'version_id' => '',
|
||||
]);
|
||||
$retryClaim = CloudStorageArtifactService::claimReplicaWork(time());
|
||||
$assert(is_array($retryClaim)
|
||||
&& (int) $retryClaim['artifact_id'] === (int) $retryView['artifact_id'],
|
||||
'Recoverable copy fixture was not claimable.');
|
||||
CloudStorageArtifactService::rescheduleReplicaNotApplied(
|
||||
$retryClaim['operation_id'],
|
||||
$retryClaim['lease_token'],
|
||||
'replica_source_download_failed',
|
||||
time(),
|
||||
60
|
||||
);
|
||||
$retryOperation = CloudStorageOperation::where(
|
||||
'operation_id', $retryClaim['operation_id']
|
||||
)->firstOrFail();
|
||||
$assert((string) $retryOperation->phase === 'accepted'
|
||||
&& $retryOperation->outcome === null
|
||||
&& $retryOperation->terminal_at === null
|
||||
&& $retryOperation->result_json === null,
|
||||
'Definite no-effect copy failure exhausted the only copy intent.');
|
||||
$retryOperation->available_at = 253402300799;
|
||||
$retryOperation->save();
|
||||
|
||||
$adoptView = CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/adopt/system.qcow2', 4096,
|
||||
str_repeat('1', 64), 'backup-publication-0006',
|
||||
hash('sha256', 'adopt'), ['backup_id' => 6]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$adoptView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::completePrimary($adoptView['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('1', 64),
|
||||
'etag' => '"adopt-primary"',
|
||||
'version_id' => '',
|
||||
]);
|
||||
$adoptCopy = CloudStorageOperation::where(
|
||||
'artifact_id', $adoptView['artifact_id']
|
||||
)->where('kind', 'copy')->firstOrFail();
|
||||
$adoptTarget = CloudStorageReplica::whereKey(
|
||||
(int) $adoptCopy->replica_id
|
||||
)->firstOrFail();
|
||||
$adoptCalls = 0;
|
||||
$adoptHelper = new CloudStorageReplicaHelper(null,
|
||||
static function (array $request) use (&$adoptCalls): array {
|
||||
$adoptCalls++;
|
||||
return [
|
||||
'protocol' => $request['protocol'],
|
||||
'operation_id' => $request['operation_id'],
|
||||
'outcome' => 'succeeded', 'effect_resolution' => 'applied',
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('1', 64),
|
||||
'etag' => '"adopted"', 'version_id' => '',
|
||||
];
|
||||
}
|
||||
);
|
||||
$adoptHTTP = new MockHandler([
|
||||
// The provider may create the session even though the response is lost.
|
||||
new Response(500),
|
||||
new Response(404),
|
||||
new Response(200, [], '<ListMultipartUploadsResult>'
|
||||
. '<IsTruncated>false</IsTruncated>'
|
||||
. '<Upload><Key>' . htmlspecialchars(
|
||||
(string) $adoptTarget->object_key,
|
||||
ENT_XML1 | ENT_QUOTES,
|
||||
'UTF-8'
|
||||
) . '</Key><UploadId>adopt-upload</UploadId><Initiated>'
|
||||
. gmdate('Y-m-d\\TH:i:s\\Z', time())
|
||||
. '</Initiated></Upload></ListMultipartUploadsResult>'),
|
||||
new Response(200, [
|
||||
'Content-Length' => '4096',
|
||||
'ETag' => '"adopted"',
|
||||
]),
|
||||
]);
|
||||
$adoptWorker = new CloudStorageReplicaWorkerService(
|
||||
$adoptHelper,
|
||||
new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create($adoptHTTP),
|
||||
])),
|
||||
$runtime
|
||||
);
|
||||
$adoptWorker->tick();
|
||||
$adoptCopy->refresh();
|
||||
$assert((string) $adoptCopy->phase === 'reconciling'
|
||||
&& $adoptCopy->result_json === '[]'
|
||||
&& $adoptCalls === 0,
|
||||
'Ambiguous multipart creation was replayed before read-only lookup.');
|
||||
$adoptCopy->next_check_at = 0;
|
||||
$adoptCopy->save();
|
||||
$adoptWorker->tick();
|
||||
$adoptCopy->refresh();
|
||||
$assert($adoptCalls === 1
|
||||
&& (string) $adoptCopy->phase === 'terminal'
|
||||
&& (string) $adoptCopy->outcome === 'succeeded',
|
||||
'One exact multipart session was not adopted exactly once.');
|
||||
|
||||
// Crash after the upload_id is durable but before helper startup. The same
|
||||
// open session is safe to resume only after two stable read-only observations;
|
||||
// no new multipart session or Abort is allowed.
|
||||
$resumeView = CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/resume/system.qcow2', 4096,
|
||||
str_repeat('2', 64), 'backup-publication-0007',
|
||||
hash('sha256', 'resume'), ['backup_id' => 7]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$resumeView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::completePrimary($resumeView['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('2', 64),
|
||||
'etag' => '"resume-primary"', 'version_id' => '',
|
||||
]);
|
||||
$resumeWork = CloudStorageArtifactService::claimReplicaWork(time());
|
||||
$assert(is_array($resumeWork), 'Resume crash fixture was not claimable.');
|
||||
CloudStorageArtifactService::markReplicaAwaitingReceipt(
|
||||
$resumeWork['operation_id'],
|
||||
$resumeWork['lease_token'],
|
||||
[
|
||||
'upload_id' => 'resume-upload',
|
||||
'part_size_bytes' => 67108864,
|
||||
'part_count' => 1,
|
||||
'maximum_size_bytes' => 4096,
|
||||
'multipart_absence_confirmations' => 0,
|
||||
'multipart_presence_confirmations' => 0,
|
||||
],
|
||||
time()
|
||||
);
|
||||
$resumeOperation = CloudStorageOperation::where(
|
||||
'operation_id', $resumeWork['operation_id']
|
||||
)->firstOrFail();
|
||||
$resumeOperation->lease_until = 0;
|
||||
$resumeOperation->save();
|
||||
$resumeTarget = CloudStorageReplica::whereKey(
|
||||
(int) $resumeOperation->replica_id
|
||||
)->firstOrFail();
|
||||
$resumeTarget->lease_until = 0;
|
||||
$resumeTarget->save();
|
||||
$resumeXML = '<ListMultipartUploadsResult><IsTruncated>false</IsTruncated>'
|
||||
. '<Upload><Key>' . htmlspecialchars(
|
||||
(string) $resumeTarget->object_key,
|
||||
ENT_XML1 | ENT_QUOTES,
|
||||
'UTF-8'
|
||||
) . '</Key><UploadId>resume-upload</UploadId><Initiated>'
|
||||
. gmdate('Y-m-d\\TH:i:s\\Z', time())
|
||||
. '</Initiated></Upload></ListMultipartUploadsResult>';
|
||||
$resumeHTTP = new MockHandler([
|
||||
new Response(404), new Response(200, [], $resumeXML),
|
||||
new Response(404), new Response(200, [], $resumeXML),
|
||||
new Response(200, [
|
||||
'Content-Length' => '4096', 'ETag' => '"resumed"',
|
||||
]),
|
||||
]);
|
||||
$resumeCalls = 0;
|
||||
$resumeHelper = new CloudStorageReplicaHelper(null,
|
||||
static function (array $request) use (&$resumeCalls): array {
|
||||
$resumeCalls++;
|
||||
return [
|
||||
'protocol' => $request['protocol'],
|
||||
'operation_id' => $request['operation_id'],
|
||||
'outcome' => 'succeeded', 'effect_resolution' => 'applied',
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('2', 64),
|
||||
'etag' => '"resumed"', 'version_id' => '',
|
||||
];
|
||||
}
|
||||
);
|
||||
$resumeWorker = new CloudStorageReplicaWorkerService(
|
||||
$resumeHelper,
|
||||
new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create($resumeHTTP),
|
||||
])),
|
||||
$runtime
|
||||
);
|
||||
$resumeWorker->tick();
|
||||
$resumeOperation->refresh();
|
||||
$resumeEvidence = json_decode((string) $resumeOperation->result_json, true);
|
||||
$assert($resumeCalls === 0
|
||||
&& ($resumeEvidence['multipart_presence_confirmations'] ?? 0) === 1,
|
||||
'A persisted multipart session resumed without two stable observations.');
|
||||
$resumeOperation->next_check_at = 0;
|
||||
$resumeOperation->save();
|
||||
$resumeWorker->tick();
|
||||
$resumeOperation->refresh();
|
||||
$assert($resumeCalls === 1
|
||||
&& (string) $resumeOperation->phase === 'terminal'
|
||||
&& (string) $resumeOperation->outcome === 'succeeded',
|
||||
'A stable persisted multipart session did not resume exactly once.');
|
||||
|
||||
// A successful helper receipt is not authoritative until target HEAD agrees
|
||||
// on both ETag and version identity.
|
||||
$mixedView = CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/mixed-version/system.qcow2', 4096,
|
||||
str_repeat('3', 64), 'backup-publication-0008',
|
||||
hash('sha256', 'mixed-version'), ['backup_id' => 8]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$mixedView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::completePrimary($mixedView['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('3', 64),
|
||||
'etag' => '"mixed-primary"', 'version_id' => '',
|
||||
]);
|
||||
$mixedHelper = new CloudStorageReplicaHelper(null,
|
||||
static fn (array $request): array => [
|
||||
'protocol' => $request['protocol'],
|
||||
'operation_id' => $request['operation_id'],
|
||||
'outcome' => 'succeeded', 'effect_resolution' => 'applied',
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('3', 64),
|
||||
'etag' => '"mixed"', 'version_id' => '',
|
||||
]
|
||||
);
|
||||
$mixedHTTP = new MockHandler([
|
||||
new Response(200, [], '<InitiateMultipartUploadResult>'
|
||||
. '<UploadId>mixed-upload</UploadId>'
|
||||
. '</InitiateMultipartUploadResult>'),
|
||||
new Response(200, [
|
||||
'Content-Length' => '4096', 'ETag' => '"mixed"',
|
||||
'x-amz-version-id' => 'versioned-object',
|
||||
]),
|
||||
]);
|
||||
$mixedWorker = new CloudStorageReplicaWorkerService(
|
||||
$mixedHelper,
|
||||
new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create($mixedHTTP),
|
||||
])),
|
||||
$runtime
|
||||
);
|
||||
$mixedWorker->tick();
|
||||
$mixedCopy = CloudStorageOperation::where(
|
||||
'artifact_id', $mixedView['artifact_id']
|
||||
)->where('kind', 'copy')->firstOrFail();
|
||||
$assert((string) $mixedCopy->phase === 'terminal'
|
||||
&& (string) $mixedCopy->outcome === 'failed'
|
||||
&& (string) $mixedCopy->error_code === 'replica_identity_changed',
|
||||
'Mixed versioned/versionless completion was accepted.');
|
||||
$assert(in_array(
|
||||
'replica_identity_changed',
|
||||
$mixedWorker->observationErrors(),
|
||||
true
|
||||
), 'A terminal identity mismatch was hidden from worker health.');
|
||||
CloudStorageArtifactService::failReplicaAppliedMismatch(
|
||||
(string) $mixedCopy->operation_id,
|
||||
str_repeat('0', 32),
|
||||
'replica_identity_changed',
|
||||
time()
|
||||
);
|
||||
$expect(static fn () =>
|
||||
CloudStorageArtifactService::failReplicaAppliedMismatch(
|
||||
(string) $mixedCopy->operation_id,
|
||||
str_repeat('0', 32),
|
||||
'replica_identity_changed_again',
|
||||
time()
|
||||
), 409);
|
||||
$expect(static fn () => CloudStorageArtifactService::failReplicaNotApplied(
|
||||
(string) $mixedCopy->operation_id,
|
||||
str_repeat('0', 32),
|
||||
'replica_identity_changed',
|
||||
time()
|
||||
), 409);
|
||||
|
||||
// Stable multipart identity ambiguity must stop automatic polling and expose
|
||||
// one administrator recovery entry for the original operation only.
|
||||
$attentionView = CloudStorageArtifactService::beginPublication(
|
||||
'template', 'cloud-templates/attention/system.qcow2', 4096,
|
||||
str_repeat('4', 64), 'template-publication-attention',
|
||||
hash('sha256', 'attention'), [
|
||||
'template_import_intent_id' => str_repeat('4', 32),
|
||||
]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$attentionView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::completePrimary($attentionView['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('4', 64),
|
||||
'etag' => '"attention-primary"', 'version_id' => '',
|
||||
]);
|
||||
$attentionCopy = CloudStorageOperation::where(
|
||||
'artifact_id', $attentionView['artifact_id']
|
||||
)->where('kind', 'copy')->firstOrFail();
|
||||
$attentionTarget = CloudStorageReplica::whereKey(
|
||||
(int) $attentionCopy->replica_id
|
||||
)->firstOrFail();
|
||||
$attentionKey = htmlspecialchars(
|
||||
(string) $attentionTarget->object_key,
|
||||
ENT_XML1 | ENT_QUOTES,
|
||||
'UTF-8'
|
||||
);
|
||||
$attentionSessions = '<ListMultipartUploadsResult>'
|
||||
. '<IsTruncated>false</IsTruncated>'
|
||||
. '<Upload><Key>' . $attentionKey . '</Key><UploadId>attention-a</UploadId>'
|
||||
. '<Initiated>' . gmdate('Y-m-d\\TH:i:s\\Z', time())
|
||||
. '</Initiated></Upload>'
|
||||
. '<Upload><Key>' . $attentionKey . '</Key><UploadId>attention-b</UploadId>'
|
||||
. '<Initiated>' . gmdate('Y-m-d\\TH:i:s\\Z', time())
|
||||
. '</Initiated></Upload></ListMultipartUploadsResult>';
|
||||
$attentionHTTP = new MockHandler([
|
||||
new Response(500),
|
||||
new Response(404), new Response(200, [], $attentionSessions),
|
||||
new Response(404), new Response(200, [], $attentionSessions),
|
||||
]);
|
||||
$attentionHelperCalls = 0;
|
||||
$attentionWorker = new CloudStorageReplicaWorkerService(
|
||||
new CloudStorageReplicaHelper(null,
|
||||
static function (array $request) use (&$attentionHelperCalls): array {
|
||||
$attentionHelperCalls++;
|
||||
throw new RuntimeException('Ambiguous upload must not start helper');
|
||||
}
|
||||
),
|
||||
new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => HandlerStack::create($attentionHTTP),
|
||||
])),
|
||||
$runtime
|
||||
);
|
||||
$attentionWorker->tick();
|
||||
$attentionCopy->refresh();
|
||||
$attentionCopy->next_check_at = 0;
|
||||
$attentionCopy->save();
|
||||
$attentionWorker->tick();
|
||||
$attentionCopy->refresh();
|
||||
$firstAttentionEvidence = json_decode(
|
||||
(string) $attentionCopy->result_json,
|
||||
true
|
||||
);
|
||||
$assert((string) $attentionCopy->phase === 'reconciling'
|
||||
&& ($firstAttentionEvidence['multipart_attention_confirmations'] ?? 0)
|
||||
=== 1,
|
||||
'First multipart ambiguity observation did not remain reconciling.');
|
||||
$attentionCopy->next_check_at = 0;
|
||||
$attentionCopy->save();
|
||||
$attentionWorker->tick();
|
||||
$attentionCopy->refresh();
|
||||
$attentionEvidence = json_decode((string) $attentionCopy->result_json, true);
|
||||
$attentionList = CloudStorageReplicaAttentionService::listView();
|
||||
$operationCountBeforeAttentionRetry = CloudStorageOperation::count();
|
||||
$assert($attentionHelperCalls === 0
|
||||
&& (string) $attentionCopy->phase === 'terminal'
|
||||
&& (string) $attentionCopy->outcome === 'failed'
|
||||
&& (string) $attentionCopy->effect_resolution === 'unknown'
|
||||
&& (bool) $attentionCopy->effect_may_have_applied
|
||||
&& !(bool) $attentionCopy->safe_to_resubmit
|
||||
&& ($attentionEvidence['multipart_attention_confirmations'] ?? 0) === 2
|
||||
&& ($attentionList['summary']['count'] ?? 0) === 1
|
||||
&& !str_contains(json_encode($attentionList), $attentionKey)
|
||||
&& !str_contains(json_encode($attentionList), 'attention-a')
|
||||
&& !str_contains(json_encode($attentionList), 'attention-b'),
|
||||
'Stable multipart ambiguity did not converge to administrator attention.');
|
||||
$attentionTarget->refresh();
|
||||
$attentionTarget->state = 'ready';
|
||||
$attentionTarget->size_bytes = 4096;
|
||||
$attentionTarget->sha256 = str_repeat('4', 64);
|
||||
$attentionTarget->verified_at = time();
|
||||
$attentionTarget->error_code = '';
|
||||
$attentionTarget->save();
|
||||
$staleAttentionList = CloudStorageReplicaAttentionService::listView();
|
||||
$assert(($staleAttentionList['items'][0]['can_retry'] ?? true) === false,
|
||||
'A stale attention operation remained retryable after target repair.');
|
||||
$expect(static fn () => CloudStorageReplicaAttentionService::retry(
|
||||
(string) $attentionCopy->operation_id
|
||||
), 409);
|
||||
$attentionTarget->state = 'degraded';
|
||||
$attentionTarget->error_code = 'replica_multipart_identity_ambiguous';
|
||||
$attentionTarget->save();
|
||||
CloudStorageReplicaAttentionService::retry(
|
||||
(string) $attentionCopy->operation_id
|
||||
);
|
||||
$attentionCopy->refresh();
|
||||
$reopenedEvidence = json_decode((string) $attentionCopy->result_json, true);
|
||||
$assert((string) $attentionCopy->phase === 'reconciling'
|
||||
&& (string) $attentionCopy->error_code === 'admin_reconcile_requested'
|
||||
&& ($reopenedEvidence['multipart_attention_confirmations'] ?? -1) === 0
|
||||
&& CloudStorageOperation::count() === $operationCountBeforeAttentionRetry,
|
||||
'Administrator retry replaced the original copy intent.');
|
||||
$attentionCopy->next_check_at = 253402300799;
|
||||
$attentionCopy->save();
|
||||
|
||||
// A definite no-effect failure is idempotent only for the exact same terminal
|
||||
// identity; conflicting late receipts must be rejected.
|
||||
$failedCopyView = CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/failed-copy/system.qcow2', 4096,
|
||||
str_repeat('5', 64), 'backup-publication-failed-copy',
|
||||
hash('sha256', 'failed-copy'), ['backup_id' => 9]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$failedCopyView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::completePrimary($failedCopyView['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('5', 64),
|
||||
'etag' => '"failed-copy-primary"', 'version_id' => '',
|
||||
]);
|
||||
$failedCopyClaim = CloudStorageArtifactService::claimReplicaWork(time());
|
||||
$assert(is_array($failedCopyClaim), 'Failed-copy fixture was not claimable.');
|
||||
CloudStorageArtifactService::failReplicaNotApplied(
|
||||
$failedCopyClaim['operation_id'],
|
||||
$failedCopyClaim['lease_token'],
|
||||
'replica_copy_rejected',
|
||||
time()
|
||||
);
|
||||
CloudStorageArtifactService::failReplicaNotApplied(
|
||||
$failedCopyClaim['operation_id'],
|
||||
$failedCopyClaim['lease_token'],
|
||||
'replica_copy_rejected',
|
||||
time()
|
||||
);
|
||||
$expect(static fn () => CloudStorageArtifactService::failReplicaNotApplied(
|
||||
$failedCopyClaim['operation_id'],
|
||||
$failedCopyClaim['lease_token'],
|
||||
'replica_copy_rejected_again',
|
||||
time()
|
||||
), 409);
|
||||
|
||||
$pendingView = CloudStorageArtifactService::beginAgentPublication(
|
||||
'backup', 'backups/pending/system.qcow2', 8192,
|
||||
'backup-publication-0004', hash('sha256', 'pending'),
|
||||
['backup_id' => 4]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$pendingView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::failPrimary(
|
||||
$pendingView['operation_id'],
|
||||
'not_applied',
|
||||
'primary_upload_rejected'
|
||||
);
|
||||
CloudStorageArtifactService::failPrimary(
|
||||
$pendingView['operation_id'],
|
||||
'not_applied',
|
||||
'primary_upload_rejected'
|
||||
);
|
||||
$expect(static fn () => CloudStorageArtifactService::failPrimary(
|
||||
$pendingView['operation_id'],
|
||||
'not_applied',
|
||||
'primary_upload_rejected_again'
|
||||
), 409);
|
||||
$pendingArtifact = CloudStorageArtifact::whereKey(
|
||||
$pendingView['artifact_id']
|
||||
)->firstOrFail();
|
||||
$pendingPublication = CloudStoragePublication::where(
|
||||
'artifact_id', $pendingArtifact->id
|
||||
)->firstOrFail();
|
||||
$pendingCopy = CloudStorageOperation::where(
|
||||
'artifact_id', $pendingArtifact->id
|
||||
)->where('kind', 'copy')->firstOrFail();
|
||||
$assert((string) $pendingArtifact->state === 'publishing'
|
||||
&& (int) $pendingArtifact->size_bytes === 0
|
||||
&& (string) $pendingArtifact->sha256 === ''
|
||||
&& (string) $pendingPublication->state === 'failed'
|
||||
&& (string) $pendingCopy->phase === 'terminal'
|
||||
&& (string) $pendingCopy->effect_resolution === 'not_applied',
|
||||
'Failed pending publication violated the blank-identity state contract.');
|
||||
|
||||
// Copy settlement must never overwrite a deletion projection or deletion
|
||||
// worker lease, even if an older accepted copy operation remains claimable.
|
||||
$deletedView = CloudStorageArtifactService::beginPublication(
|
||||
'backup', 'backups/deleted-copy/system.qcow2', 4096,
|
||||
str_repeat('6', 64), 'backup-publication-deleted-copy',
|
||||
hash('sha256', 'deleted-copy'), ['backup_id' => 10]
|
||||
);
|
||||
CloudStorageArtifactService::markPrimaryDispatching(
|
||||
$deletedView['operation_id']
|
||||
);
|
||||
CloudStorageArtifactService::completePrimary($deletedView['operation_id'], [
|
||||
'size_bytes' => 4096, 'sha256' => str_repeat('6', 64),
|
||||
'etag' => '"deleted-copy-primary"', 'version_id' => '',
|
||||
]);
|
||||
$deletedArtifact = CloudStorageArtifact::whereKey(
|
||||
$deletedView['artifact_id']
|
||||
)->firstOrFail();
|
||||
$deletedCopy = CloudStorageOperation::where(
|
||||
'artifact_id', $deletedArtifact->id
|
||||
)->where('kind', 'copy')->firstOrFail();
|
||||
$deletedReplica = CloudStorageReplica::whereKey(
|
||||
(int) $deletedCopy->replica_id
|
||||
)->firstOrFail();
|
||||
$deletedArtifact->state = 'deleted';
|
||||
$deletedArtifact->save();
|
||||
$deletedReplica->state = 'deleted';
|
||||
$deletedReplica->lease_token = str_repeat('d', 32);
|
||||
$deletedReplica->lease_until = time() + 3600;
|
||||
$deletedReplica->error_code = 'delete_projection_sentinel';
|
||||
$deletedReplica->save();
|
||||
$assert(CloudStorageArtifactService::claimReplicaWork(time()) === null,
|
||||
'Deleted artifact unexpectedly returned copy work.');
|
||||
$deletedCopy->refresh();
|
||||
$deletedReplica->refresh();
|
||||
$deletedArtifact->refresh();
|
||||
$assert((string) $deletedCopy->phase === 'terminal'
|
||||
&& (string) $deletedCopy->effect_resolution === 'not_applied'
|
||||
&& (string) $deletedArtifact->state === 'deleted'
|
||||
&& (string) $deletedReplica->state === 'deleted'
|
||||
&& (string) $deletedReplica->lease_token === str_repeat('d', 32)
|
||||
&& (string) $deletedReplica->error_code
|
||||
=== 'delete_projection_sentinel',
|
||||
'Copy fence overwrote an existing deletion projection.');
|
||||
|
||||
CloudStorageBackend::whereKey(2)->update([
|
||||
'admin_state' => 'disabled', 'health_state' => 'unreachable',
|
||||
'tested_revision' => 0,
|
||||
]);
|
||||
$artifactCountBeforeRejectedPublication = CloudStorageArtifact::count();
|
||||
$expect(static fn () => CloudStorageArtifactService::beginPublication(
|
||||
'template', 'cloud-templates/t/g/system.qcow2', 8192,
|
||||
str_repeat('b', 64), 'template-publication-0001', hash('sha256', 't'),
|
||||
['template_import_intent_id' => str_repeat('d', 32)]
|
||||
), 503);
|
||||
$assert(CloudStorageArtifact::count()
|
||||
=== $artifactCountBeforeRejectedPublication,
|
||||
'Required-two preflight left a partial template artifact.');
|
||||
|
||||
echo "Storage artifact service tests passed.\n";
|
||||
@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudStorageReplicaHelper;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$operationId = str_repeat('a', 32);
|
||||
$request = [
|
||||
'protocol' => 'object-replica-v1',
|
||||
'operation_id' => $operationId,
|
||||
'deadline_at' => time() + 60,
|
||||
];
|
||||
$helper = new CloudStorageReplicaHelper(null,
|
||||
static fn (array $input): array => [
|
||||
'protocol' => $input['protocol'],
|
||||
'operation_id' => $input['operation_id'],
|
||||
'outcome' => 'succeeded',
|
||||
'effect_resolution' => 'applied',
|
||||
'size_bytes' => 4096,
|
||||
'sha256' => str_repeat('b', 64),
|
||||
'etag' => '"etag"',
|
||||
// Versionless S3 intentionally omits version_id.
|
||||
]
|
||||
);
|
||||
$receipt = $helper->invoke($request);
|
||||
$assert(($receipt['version_id'] ?? null) === '',
|
||||
'Versionless S3 success was not normalized to an explicit empty version.');
|
||||
|
||||
$mismatch = new CloudStorageReplicaHelper(null,
|
||||
static fn (): array => [
|
||||
'protocol' => 'object-replica-v1',
|
||||
'operation_id' => str_repeat('c', 32),
|
||||
'outcome' => 'succeeded',
|
||||
'effect_resolution' => 'applied',
|
||||
'size_bytes' => 4096,
|
||||
'sha256' => str_repeat('b', 64),
|
||||
'etag' => '"etag"',
|
||||
'version_id' => '',
|
||||
]
|
||||
);
|
||||
$receipt = $mismatch->invoke($request);
|
||||
$assert($receipt['effect_resolution'] === 'unknown'
|
||||
&& $receipt['error_code'] === 'replicator_invalid_receipt',
|
||||
'Mismatched helper receipt was accepted as authoritative.');
|
||||
|
||||
$verify = new CloudStorageReplicaHelper(null,
|
||||
static fn (array $input): array => [
|
||||
'protocol' => $input['protocol'],
|
||||
'operation_id' => $input['operation_id'],
|
||||
'outcome' => 'failed',
|
||||
'effect_resolution' => 'unknown',
|
||||
'error_code' => 'object_download_failed',
|
||||
]
|
||||
);
|
||||
$verifyReceipt = $verify->invoke([
|
||||
'protocol' => 'object-replica-verify-v1',
|
||||
'operation_id' => $operationId,
|
||||
'deadline_at' => time() + 60,
|
||||
]);
|
||||
$assert($verifyReceipt['effect_resolution'] === 'unknown',
|
||||
'Read-only verification uncertainty was not preserved.');
|
||||
|
||||
// Exercise the real proc_open path. proc_get_status() commonly consumes the
|
||||
// child exit status and makes proc_close() return -1; the remembered exit code
|
||||
// must still accept a valid bounded receipt.
|
||||
$script = tempnam(sys_get_temp_dir(), 'virt-storage-helper-');
|
||||
if (!is_string($script)) {
|
||||
throw new RuntimeException('Unable to allocate helper fixture.');
|
||||
}
|
||||
$program = '#!' . PHP_BINARY . "\n<?php\n"
|
||||
. '$request = json_decode(stream_get_contents(STDIN), true);' . "\n"
|
||||
. 'echo json_encode([' . "\n"
|
||||
. "'protocol' => \$request['protocol'],\n"
|
||||
. "'operation_id' => \$request['operation_id'],\n"
|
||||
. "'outcome' => 'succeeded', 'effect_resolution' => 'applied',\n"
|
||||
. "'size_bytes' => 4096, 'sha256' => str_repeat('d', 64),\n"
|
||||
. "'etag' => '\"fixture\"', 'version_id' => ''\n"
|
||||
. ']);' . "\n";
|
||||
file_put_contents($script, $program);
|
||||
chmod($script, 0700);
|
||||
try {
|
||||
$receipt = (new CloudStorageReplicaHelper($script))->invoke($request);
|
||||
$assert($receipt['outcome'] === 'succeeded'
|
||||
&& $receipt['effect_resolution'] === 'applied',
|
||||
'Valid helper receipt was rejected after proc_get_status().');
|
||||
} finally {
|
||||
@unlink($script);
|
||||
}
|
||||
|
||||
// A helper that never reads stdin must be terminated by the same absolute
|
||||
// deadline used for stdout/stderr, even when the request fills the pipe.
|
||||
$blockedScript = tempnam(sys_get_temp_dir(), 'virt-storage-helper-blocked-');
|
||||
if (!is_string($blockedScript)) {
|
||||
throw new RuntimeException('Unable to allocate blocked helper fixture.');
|
||||
}
|
||||
$blockedProgram = '#!' . PHP_BINARY . "\n<?php\nsleep(10);\n";
|
||||
file_put_contents($blockedScript, $blockedProgram);
|
||||
chmod($blockedScript, 0700);
|
||||
try {
|
||||
$blockedRequest = $request;
|
||||
$blockedRequest['deadline_at'] = time() - 5;
|
||||
$blockedRequest['padding'] = str_repeat('x', 1572864);
|
||||
$started = microtime(true);
|
||||
$blockedReceipt = (new CloudStorageReplicaHelper($blockedScript))
|
||||
->invoke($blockedRequest);
|
||||
$elapsed = microtime(true) - $started;
|
||||
$assert($blockedReceipt['effect_resolution'] === 'unknown'
|
||||
&& in_array($blockedReceipt['error_code'], [
|
||||
'replicator_timeout', 'replicator_stdin_failed',
|
||||
], true),
|
||||
'A helper that ignored stdin did not return an unknown receipt.');
|
||||
$assert($elapsed < 4.0,
|
||||
'Blocking stdin escaped the helper deadline: ' . $elapsed);
|
||||
} finally {
|
||||
@unlink($blockedScript);
|
||||
}
|
||||
|
||||
$source = file_get_contents(
|
||||
dirname(__DIR__) . '/app/Services/Cloud/CloudStorageReplicaHelper.php'
|
||||
);
|
||||
$assert(is_string($source)
|
||||
&& str_contains($source, '$stdinFailed = true;')
|
||||
&& str_contains($source, 'stream_select(')
|
||||
&& str_contains($source, 'stream_set_blocking($pipe, false)')
|
||||
&& str_contains($source, '$closedExit >= 0 ? $closedExit : $observedExit')
|
||||
&& str_contains($source, "['bypass_shell' => true]"),
|
||||
'Helper runner lost its stdin, exit-status, or shell-isolation guard.');
|
||||
|
||||
echo "Storage replica helper tests passed.\n";
|
||||
@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__, 2);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$contents = file_get_contents($root . '/' . $path);
|
||||
if (!is_string($contents)) {
|
||||
throw new RuntimeException('Unable to read ' . $path);
|
||||
}
|
||||
return $contents;
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$xcat = $read('web/app/Command/XCat.php');
|
||||
$command = $read('web/app/Command/CloudStorageReplicaWorker.php');
|
||||
$worker = $read('web/app/Services/Cloud/CloudStorageReplicaWorkerService.php');
|
||||
$attention = $read('web/app/Services/Cloud/CloudStorageReplicaAttentionService.php');
|
||||
$controller = $read('web/app/Controllers/Admin/ObjectStorageController.php');
|
||||
$routes = $read('web/config/routes.php');
|
||||
$view = $read('web/resources/views/venix/admin/object_storage.tpl');
|
||||
$javascript = $read('web/public/cloud/admin-object-storage.js');
|
||||
$unit = $read('deploy/virt-cloud-storage-replica-worker.service');
|
||||
|
||||
$assert(str_contains($xcat, "'cloudStorageReplicaWorker'")
|
||||
&& str_contains($xcat, 'CloudStorageReplicaWorker::run'),
|
||||
'Replica worker command is not reachable through xcat.');
|
||||
$assert(str_contains($command, 'CloudStorageReplicaWorkerService')
|
||||
&& str_contains($command, "in_array('--once'")
|
||||
&& str_contains($command, 'CloudRuntimeHeartbeat')
|
||||
&& str_contains($command, "'storage_replica'")
|
||||
&& str_contains($command, 'observationErrors()')
|
||||
&& str_contains($command, '$unresolved = true;')
|
||||
&& str_contains($command, 'elseif (!$unresolved)')
|
||||
&& str_contains($command, "error('storage_replica_failed')"),
|
||||
'Replica worker command lost its loop, persistent warning, heartbeat, error observation, or --once mode.');
|
||||
$assert(str_contains($unit,
|
||||
'ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudStorageReplicaWorker')
|
||||
&& str_contains($unit, 'NoNewPrivileges=true')
|
||||
&& str_contains($unit, 'ProtectSystem=strict')
|
||||
&& str_contains($unit, 'LimitCORE=0'),
|
||||
'Replica worker systemd unit is missing execution or hardening controls.');
|
||||
$assert(str_contains($worker, "'object-replica-verify-v1'")
|
||||
&& str_contains($worker, 'presignedVersionedGet')
|
||||
&& str_contains($worker, 'markReplicaUnknown')
|
||||
&& !str_contains($worker, "result_json ="),
|
||||
'Worker lost exact-read reconciliation or bypasses sanitized persistence.');
|
||||
$assert(str_contains($worker, 'findMultipartUploadsByExactObjectKey')
|
||||
&& str_contains($worker, 'resumeMultipartUpload')
|
||||
&& str_contains($worker, 'operation_available_at')
|
||||
&& str_contains($worker, 'multipart_absence_confirmations')
|
||||
&& str_contains($worker, 'rescheduleReplicaNotApplied')
|
||||
&& !str_contains($worker, '->abortMultipart('),
|
||||
'Worker lost read-only multipart recovery or reintroduced blind Abort.');
|
||||
$assert(str_contains($worker, '$mixedVersionIdentity')
|
||||
&& str_contains($worker, "replica_multipart_identity_ambiguous")
|
||||
&& str_contains($worker, 'multipart_presence_confirmations')
|
||||
&& str_contains($worker, 'replica_completion_inspection_unavailable'),
|
||||
'Worker lost mixed-version rejection or unknown-effect replay fences.');
|
||||
$assert(str_contains($worker, 'markMultipartAttention')
|
||||
&& str_contains($worker, 'markReplicaAttention')
|
||||
&& str_contains($worker, 'multipart_attention_confirmations')
|
||||
&& str_contains($attention, 'CloudStorageArtifactService::reopenReplicaAttention')
|
||||
&& !str_contains($attention, 'abortMultipart')
|
||||
&& !str_contains($attention, 'beginMultipart'),
|
||||
'Multipart ambiguity lacks bounded attention or reintroduced remote mutation.');
|
||||
$assert(str_contains($controller, 'retryReplicaAttention')
|
||||
&& str_contains($routes, '/object-storage/replica-attention/{operation_id:')
|
||||
&& str_contains($routes,
|
||||
'retryReplicaAttention\')->add(new SuperAdmin())')
|
||||
&& str_contains($view, 'os-attention-retry')
|
||||
&& str_contains($javascript, 'initializeReplicaAttention')
|
||||
&& str_contains($javascript, '不会终止会话或直接新建上传')
|
||||
&& str_contains($javascript, '两次确认无远端效果后'),
|
||||
'Administrator replica-attention convergence entry is incomplete.');
|
||||
|
||||
echo "Storage replica worker contract tests passed.\n";
|
||||
Loading…
Reference in New Issue