feat(storage): add resilient replica worker

go
codex 2 weeks ago
parent 982cbf0b68
commit f8c35863ba

@ -51,7 +51,7 @@ type replicaReceipt struct {
SizeBytes int64 `json:"size_bytes,omitempty"`
SHA256 string `json:"sha256,omitempty"`
ETag string `json:"etag,omitempty"`
VersionID string `json:"version_id,omitempty"`
VersionID string `json:"version_id"`
ErrorCode string `json:"error_code,omitempty"`
}

@ -97,6 +97,24 @@ func TestRunReturnsBoundedSuccessReceipt(t *testing.T) {
}
}
func TestRunKeepsVersionlessSuccessExplicit(t *testing.T) {
now := time.Unix(1_800_000_000, 0).UTC()
copier := &fakeCopier{result: objecttransfer.UploadResult{
SizeBytes: objecttransfer.MinPartSizeBytes,
SHA256: strings.Repeat("a", 64), ETag: `"final"`,
}}
receipt := run(encodeRequest(t, validRequest(now)),
func() time.Time { return now }, copier)
encoded, err := json.Marshal(receipt)
if err != nil {
t.Fatal(err)
}
if receipt.Outcome != "succeeded" || receipt.VersionID != "" ||
!bytes.Contains(encoded, []byte(`"version_id":""`)) {
t.Fatalf("versionless identity was omitted: %s", encoded)
}
}
func TestRunPreservesUnknownEffectWithoutCapabilityLeak(t *testing.T) {
now := time.Unix(1_800_000_000, 0).UTC()
copier := &fakeCopier{err: &objecttransfer.Error{

@ -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

@ -101,9 +101,9 @@ php xcat cloudRepairInstanceMetadata --apply
### 对象存储应用
后台 `/admin/object-storage` 可配置一个全局 S3 兼容对象存储应用,适用于 AWS S3、MinIO 及实现 AWS Signature Version 4 的兼容服务。该功能复用业务库已有的 `configurations` 表,不需要导入新表。Endpoint 必须是带有效证书的 HTTPS origin;MinIO 通常选择路径寻址,AWS S3 通常选择虚拟主机寻址。页面默认展示运行概览、就绪条件和脱敏连接详情;只有超级管理员可从编辑抽屉修改连接。对象清理异常位于独立工作区,`delete_uncertain` 只显示系统核对进度,只有 `delete_attention` 提供人工“重新核对”入口。
后台 `/admin/object-storage` 可配置两套相互独立的 S3 兼容对象存储后端,适用于 AWS S3、MinIO 及实现 AWS Signature Version 4 的兼容服务。后端、制品、副本、操作和发布账本保存在业务库的 `cloud_storage_*` 表;不能再用旧 `configurations` 单应用记录替代当前结构。Endpoint 必须是带有效证书的 HTTPS origin;MinIO 通常选择路径寻址,AWS S3 通常选择虚拟主机寻址。每套后端必须分别验证当前配置版本后才能参与写入;模板和救援镜像要求两个不同故障域的副本,普通云备份先完成主副本后异步复制。页面默认展示运行概览、就绪条件和脱敏连接详情;只有超级管理员可修改连接。对象清理异常位于独立工作区,未知删除只显示系统核对进度,只有进入人工核对状态才提供受控恢复入口。
Access Key ID 与 Secret Access Key 只在超级管理员提交时进入 PHP,使用 `cloud_data_key` 的独立用途密钥密封后保存,读取页面不会回显。修改任一配置或停用应用都会清除原就绪标记;必须重新执行“验证连接并启用”。连接验证只发送签名的 `HeadBucket` 请求,需要目标 Bucket 的 `s3:ListBucket` 权限,不上传、覆盖或删除对象。管理员虚拟机管理已接入完整系统盘备份和新实例恢复,目标可以是原宿主机或其他合格宿主机;用户自动备份使用同一对象存储,在实例设置中按每天或每周于 UTC 00:00 调度并保留最多两份。云镜像导入还会先把经过校验的内容发布到 `cloud-templates/` 不可变主副本,再向宿主机签发该精确版本的只读地址;没有旧本地模板路径或直接暂存分发回退。运行账户需要在配置前缀下同时授予 `vm-backups/` 与 `cloud-templates/` 的上传、`GetObject`、`HeadObject` 和 `DeleteObject` 权限;开启 Bucket 版本控制时还必须授予 `s3:GetObjectVersion` 与 `s3:DeleteObjectVersion`,让 HEAD 与删除准确绑定 `versionId`。维护迁移使用宿主机间 PeerMigration V3 直传,不创建 S3 迁移对象,也不需要 `vm-migrations/` 权限。当前不包含增量链和管理员手工备份的自动保留策略,具体安全边界见 `docs/PORTABLE_VM_BACKUPS.md`。
Access Key ID 与 Secret Access Key 只在超级管理员提交时进入 PHP,使用 `cloud_data_key` 的独立用途密钥密封后保存,读取页面不会回显。修改任一后端配置或停用后端都会清除该后端的就绪标记;必须重新执行连接验证。连接验证只发送签名的 `HeadBucket` 请求,需要目标 Bucket 的 `s3:ListBucket` 权限,不上传、覆盖或删除对象。副本 Worker 为崩溃恢复执行精确对象键的 multipart 列表查询,因此每套后端还必须授予 Bucket 级 `s3:ListBucketMultipartUploads`。运行账户需要在各自配置前缀下授予 multipart 创建、分片上传、完成与中止,以及 `GetObject`、`HeadObject` 和 `DeleteObject`;开启 Bucket 版本控制时还必须授予 `s3:GetObjectVersion` 与 `s3:DeleteObjectVersion`,让读取与删除准确绑定 `versionId`。管理员虚拟机管理的完整系统盘备份和用户自动备份使用同一制品账本;云镜像与救援镜像在达到冻结的副本覆盖数前不得下发到宿主机。维护迁移使用宿主机间 PeerMigration V3 直传,不创建对象存储迁移对象。当前不包含增量链和管理员手工备份的自动保留策略,具体安全边界见 `docs/PORTABLE_VM_BACKUPS.md`。
生产 Bucket 必须把生命周期规则作为控制面之外的最后兜底:建议在 1 天后终止未完成 multipart upload;开启版本控制时,按业务保留要求清理 `vm-backups/` 与 `cloud-templates/` 的非当前版本和过期删除标记。生命周期不得提前删除仍由面板备份、云镜像目录或未完成导入意图引用的当前版本。管理员本地上传云镜像时,浏览器直接向对象存储执行分片 `PUT`,Bucket CORS 必须只允许面板 HTTPS origin,允许 `PUT`,并在 `ExposeHeaders` 中公开 `ETag`;不要使用 `*` origin 搭配管理站点。面板保存每个已确认分片,刷新后重新选择同一文件会跳过这些分片;取消或 24 小时过期后,普通 worker 会中止仍可确认的 multipart。若创建 multipart 的响应在 upload ID 返回前丢失,面板只能放弃该上传记录,因此上述生命周期规则是清除提供商残留分片的必需兜底。官方地址导入先持久化同一导入意图和唯一对象键,再由 PHP 有界下载、校验并发布;正常结束立即删除本地临时文件,进程硬中止遗留的同前缀普通文件由 worker 在 24 小时后逐个回收。PUT 结果不明时只允许用同一对象键执行 HEAD 核对,不能新建导入或盲目重写。
@ -229,9 +229,16 @@ cp /home/virt-cloud/deploy/virt-cloud-policy-worker@.service /etc/systemd/system
cp /home/virt-cloud/deploy/virt-cloud-vpc-worker@.service /etc/systemd/system/
cp /home/virt-cloud/deploy/virt-cloud-recovery-worker.service /etc/systemd/system/
cp /home/virt-cloud/deploy/virt-cloud-notification-worker.service /etc/systemd/system/
cp /home/virt-cloud/deploy/virt-cloud-storage-replica-worker.service /etc/systemd/system/
cd /home/virt-cloud/agent
go build -trimpath -o /home/virt-cloud/bin/virt-cloud-storage-replicator \
./cmd/virt-cloud-storage-replicator
chown root:root /home/virt-cloud/bin/virt-cloud-storage-replicator
chmod 0755 /home/virt-cloud/bin/virt-cloud-storage-replicator
systemctl daemon-reload
systemctl enable --now virt-cloud-worker.service \
virt-cloud-recovery-worker.service virt-cloud-notification-worker.service \
virt-cloud-storage-replica-worker.service \
virt-cloud-lifecycle.service \
virt-cloud-policy-worker@1.service virt-cloud-policy-worker@2.service \
virt-cloud-vpc-worker@{1..8}.service
@ -241,6 +248,8 @@ systemctl enable --now virt-cloud-worker.service \
`virt-cloud-notification-worker.service` 消费管理员维护通知和实例补偿结果通知;两个通道每轮各最多领取一封,任一通道异常不阻塞另一通道,也不占用虚拟机任务 worker。投递使用 300 秒租约;邮件传输一旦开始后返回失败、异常或租约过期都记为“效果未知”,不会自动重发。该服务是两类通知的必需组件;只更新 PHP 而不安装并启动该 unit 时,通知会安全保留在待发送状态。
`virt-cloud-storage-replica-worker.service` 独立流式复制已冻结的对象存储制品,不占用虚拟机任务 worker。PHP 只通过标准输入把短期、限方法的 capability 交给 helper;命令行、环境、数据库和日志都不保存 capability 或对象存储凭据。复制租约覆盖 helper 的完整六小时硬截止;进程中断、回执损坏或完成结果不确定时只对固定目标对象执行 HEAD 与精确对象键的 Multipart 列表查询,不自动重放复制或 Abort。只有连续两次确认目标对象和对应 Multipart 会话都不存在后,才会重排同一复制意图;唯一且时间窗口匹配的未持久化会话可被原操作接管。同一对象键出现多个会话、记录会话与远端不匹配或会话无法归属原操作时,连续两次稳定证据会使原操作进入“副本人工核对”;管理员在提供商侧清理多余会话后只能重开该原操作的只读核对,本次点击不会由面板 Abort 或直接新建上传;只有两次确认无远端效果后才会沿用原操作安全重试。该 worker 独立写入 `storage_replica` 运行心跳;后台运行状态出现警告时应同时核对制品发布状态和该 unit 的 journal,不能仅凭 systemd 的 `active` 判断复制正常。
实例补偿要求 v35 的批次、明细和收件人账本。`php xcat cloudInit` 只能为全新空数据库创建和验证它们,不能冒充既有数据库的增量升级。既有安装发布前必须备份数据库,使用经过审核的一次性迁移落地完整 v35 结构并核对 schema 指纹;升级成功后删除迁移脚本。然后重启普通 worker 和 notification worker。补偿不调用 Agent/Gateway,因此这一功能本身不要求更新或重新编译宿主机 Agent 和面板 Gateway。完整语义见 [`SERVICE_COMPENSATION.md`](SERVICE_COMPENSATION.md)。
共享流量池必须严格按 `disabled -> shadow -> enforced` 上线,并在强制执行前通过全部账本、采样和网络策略门禁。现有数据库不能使用 `php xcat cloudInit` 冒充增量升级,旧服务周期也不能通过 SQL 回填到流量池;完整步骤、验收项和故障处置见 [`TRAFFIC_POOL_ROLLOUT.md`](TRAFFIC_POOL_ROLLOUT.md)。
@ -430,6 +439,7 @@ location = /agent/console {
```bash
journalctl -u virt-cloud-agent.service -n 200 --no-pager
journalctl -u virt-cloud-worker.service -u virt-cloud-recovery-worker.service \
-u virt-cloud-storage-replica-worker.service \
-u virt-cloud-lifecycle.service \
-u 'virt-cloud-policy-worker@*' -u 'virt-cloud-vpc-worker@*' \
-n 200 --no-pager

@ -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;
}
}

@ -22,6 +22,8 @@ class XCat
'createAdmin' => $this->createAdmin(),
'cloudInit' => CloudSetup::initialize(),
'cloudWorker' => CloudWorker::run($this->argv) === 0,
'cloudStorageReplicaWorker' =>
CloudStorageReplicaWorker::run($this->argv) === 0,
'cloudLifecycle' => CloudLifecycle::run($this->argv) === 0,
'cloudTrafficPoolAttention' =>
CloudTrafficPoolAttention::run($this->argv) === 0,
@ -101,6 +103,7 @@ class XCat
. " php xcat createAdmin <email> [name]\n"
. " php xcat cloudInit\n"
. " php xcat cloudWorker [--once] [--policy-only|--vpc-batch-only|--recovery-only|--notification-only]\n"
. " php xcat cloudStorageReplicaWorker [--once]\n"
. " php xcat cloudLifecycle [--once]\n"
. " php xcat cloudTrafficPoolAttention inspect --pool-id=N\n"
. " php xcat cloudTrafficPoolAttention inspect-resolution --resolution-key=UUID\n"

@ -9,6 +9,7 @@ use App\Services\Cloud\CloudBackupService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudObjectStorageBackendRegistry;
use App\Services\Cloud\CloudStorageReplicaAttentionService;
final class ObjectStorageController extends AdminController
{
@ -27,6 +28,8 @@ final class ObjectStorageController extends AdminController
$error = '';
$cleanupDebt = null;
$cleanupDebtError = '';
$replicaAttention = null;
$replicaAttentionError = '';
$status = 200;
try {
$backends = CloudObjectStorageBackendRegistry::listView();
@ -58,6 +61,19 @@ final class ObjectStorageController extends AdminController
error_log('Object cleanup debt read failed: ' . get_class($exception));
$cleanupDebtError = '对象清理债务暂时无法读取,请检查数据库结构。';
}
try {
$query = $request->getQueryParams();
$replicaAttention = CloudStorageReplicaAttentionService::listView([
'page' => $query['attention_page'] ?? 1,
'per_page' => 20,
]);
} catch (CloudError $exception) {
$replicaAttentionError = $exception->getMessage();
} catch (\Throwable $exception) {
error_log('Object replica attention read failed: '
. get_class($exception));
$replicaAttentionError = '副本人工核对列表暂时无法读取。';
}
$smarty = $this->view()->assign([
'object_storage_backends' => $backends,
@ -65,6 +81,8 @@ final class ObjectStorageController extends AdminController
'object_storage_error' => $error,
'cleanup_debt' => $cleanupDebt,
'cleanup_debt_error' => $cleanupDebtError,
'replica_attention' => $replicaAttention,
'replica_attention_error' => $replicaAttentionError,
]);
$response->getBody()->write($smarty->fetch('admin/object_storage.tpl'));
return $response->withStatus($status)
@ -211,6 +229,49 @@ final class ObjectStorageController extends AdminController
}
}
public function replicaAttention($request, $response, $args)
{
try {
return $response->withJson([
'ret' => 1,
'msg' => '副本人工核对列表已刷新。',
'replica_attention' =>
CloudStorageReplicaAttentionService::listView(
$request->getQueryParams()
),
])->withHeader('Cache-Control', 'private, no-store');
} catch (CloudError $exception) {
return $this->json($response, 0, $exception->getMessage(),
$exception->httpStatus);
} catch (\Throwable $exception) {
error_log('Object replica attention refresh failed: '
. get_class($exception));
return $this->json($response, 0,
'副本人工核对列表刷新失败。', 500);
}
}
public function retryReplicaAttention($request, $response, $args)
{
try {
$operationId = (string) ($args['operation_id'] ?? '');
$result = CloudStorageReplicaAttentionService::retry($operationId);
return $response->withJson([
'ret' => 1,
'msg' => '已使用原操作恢复只读核对;不会新建上传或终止远端会话。',
'replica_attention' => $result,
])->withHeader('Cache-Control', 'private, no-store');
} catch (CloudError $exception) {
return $this->json($response, 0, $exception->getMessage(),
$exception->httpStatus);
} catch (\Throwable $exception) {
error_log('Object replica attention retry failed: '
. get_class($exception));
return $this->json($response, 0,
'副本核对恢复失败,请检查原操作状态。', 500);
}
}
private function transition($request, $response, array $args,
string $method, string $success)
{

@ -92,6 +92,7 @@ final class CloudRuntimeHealthService
'vpc' => 'VPC 批量任务处理',
'recovery' => '任务安全收敛',
'notification' => '维护邮件投递',
'storage_replica' => '对象存储副本复制',
'lifecycle' => '到期与流量调度'] as $key => $label) {
$found = null;
foreach (is_array($heartbeats) ? $heartbeats : [] as $row) {

@ -9,6 +9,7 @@ final class CloudRuntimeHeartbeat
'vpc' => ['vpc', 'VPC 批量任务 worker'],
'recovery' => ['recovery', '任务安全收敛 worker'],
'notification' => ['notification', '客户通知 worker'],
'storage_replica' => ['storage_replica', '对象存储副本 worker'],
'lifecycle' => ['lifecycle', '生命周期调度']];
private const PHASES = ['startup' => '启动', 'worker_tick' => '任务消费或核对',
'recovery_tick' => '任务安全收敛',
@ -21,6 +22,7 @@ final class CloudRuntimeHeartbeat
'template_reconcile' => '云镜像副本核对',
'rescue_template_reconcile' => '救援 ISO 副本核对',
'rescue_template_cleanup' => '救援 ISO 退役清理',
'storage_replica_tick' => '对象存储副本复制或核对',
'traffic_sync' => '流量同步',
'runtime_status_sync' => '实例状态同步',
'instance_reconcile' => '实例策略核对',
@ -34,6 +36,7 @@ final class CloudRuntimeHeartbeat
'template_reconcile_failed',
'rescue_template_reconcile_failed',
'rescue_template_cleanup_failed',
'storage_replica_failed',
'traffic_sync_failed', 'runtime_status_sync_failed',
'runtime_status_sync_unconfigured', 'traffic_collection_unconfigured',
'traffic_log_schema_missing', 'traffic_agent_unavailable',
@ -223,7 +226,7 @@ final class CloudRuntimeHeartbeat
if (++$scanned > self::SCAN_LIMIT || $removed >= 32) {
break;
}
if (preg_match('/^(normal|policy|vpc|recovery|notification|lifecycle)-[1-9][0-9]*-[a-f0-9]{24}\.json(?:\.tmp)?$/D',
if (preg_match('/^(normal|policy|vpc|recovery|notification|storage_replica|lifecycle)-[1-9][0-9]*-[a-f0-9]{24}\.json(?:\.tmp)?$/D',
$entry->getFilename()) !== 1) {
continue;
}
@ -313,7 +316,7 @@ final class CloudRuntimeHeartbeat
$incomplete = true;
break;
}
if (preg_match('/^(normal|policy|vpc|recovery|notification|lifecycle)-[1-9][0-9]*-[a-f0-9]{24}\.json$/D',
if (preg_match('/^(normal|policy|vpc|recovery|notification|storage_replica|lifecycle)-[1-9][0-9]*-[a-f0-9]{24}\.json$/D',
$entry->getFilename(), $match) !== 1) {
continue;
}
@ -339,7 +342,10 @@ final class CloudRuntimeHeartbeat
// The outer PHP HTTP deadline is 900 seconds (the Agent and
// Gateway finish earlier); policy calls have a 120s timeout.
// SMTP/lifecycle also need a generous observation window.
$grace = $row['state'] === 'busy' ? ($kind === 'policy' ? 180 : 1200) : 90;
$grace = $row['state'] === 'busy'
? ($kind === 'policy' ? 180
: ($kind === 'storage_replica' ? 21840 : 1200))
: 90;
return $row['mode'] === 'daemon' && $row['state'] !== 'stopped'
&& $now - $row['last_seen'] <= $grace;
}));

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'],
];
}
}

@ -190,6 +190,8 @@ $app->group('/admin', function () {
$this->post('/object-storage/backends/{backend_id:[0-9]+}/disable', 'App\Controllers\Admin\ObjectStorageController:disableBackend')->add(new SuperAdmin());
$this->get('/object-storage/cleanup-debts', 'App\Controllers\Admin\ObjectStorageController:cleanupDebt');
$this->post('/object-storage/cleanup-debts/{backup_id:[0-9]+}/retry', 'App\Controllers\Admin\ObjectStorageController:retryCleanup')->add(new SuperAdmin());
$this->get('/object-storage/replica-attention', 'App\Controllers\Admin\ObjectStorageController:replicaAttention');
$this->post('/object-storage/replica-attention/{operation_id:[a-f0-9]{32}}/retry', 'App\Controllers\Admin\ObjectStorageController:retryReplicaAttention')->add(new SuperAdmin());
$this->get('/cloud/templates', 'App\Controllers\Admin\CloudPageController:templates');
$this->get('/cloud/rescue', 'App\Controllers\Admin\CloudPageController:rescue');
$this->get('/cloud/instances', 'App\Controllers\Admin\CloudPageController:instances');

@ -271,6 +271,45 @@
});
}
function initializeReplicaAttention() {
var refresh = document.getElementById('osAttentionRefresh');
if (refresh) refresh.addEventListener('click', function () {
window.location.hash = 'protection';
window.location.reload();
});
var notice = document.getElementById('osAttentionNotice');
document.querySelectorAll('.os-attention-retry').forEach(function (button) {
button.addEventListener('click', function () {
var operationId = String(button.getAttribute('data-operation-id') || '');
if (!/^[a-f0-9]{32}$/.test(operationId) || button.disabled) return;
confirmAction({
title: '重新核对原副本操作',
message: '请先在对象存储提供商确认已清理多余的 multipart 会话。本次点击只重开原操作的只读核对,不会终止会话或直接新建上传;只有两次确认无远端效果后才会沿用原操作安全重试。',
confirmLabel: '开始核对',
tone: 'primary',
}).then(function (confirmed) {
if (!confirmed) return;
button.disabled = true;
showNotice(notice, '正在重开原操作的只读核对…', true, false);
request('/admin/object-storage/replica-attention/'
+ encodeURIComponent(operationId) + '/retry', {}).then(function (result) {
showNotice(notice, result.msg, true, false);
window.setTimeout(function () {
window.location.hash = 'protection';
window.location.reload();
}, 700);
}).catch(function (error) {
var unknown = error && error.mutationMayHaveApplied === true;
showNotice(notice, unknown
? '重开结果无法确认,请刷新后查看原操作,不要重复提交。'
: error && error.message || '重新核对失败。', false, unknown);
if (!unknown) button.disabled = false;
});
});
});
});
}
function initializeTabs() {
var tabs = Array.prototype.slice.call(document.querySelectorAll('[data-os-tab]'));
var panels = Array.prototype.slice.call(document.querySelectorAll('[data-os-panel]'));
@ -301,6 +340,7 @@
initializeConfigurationDrawer();
initializeBackendActions();
initializeCleanupDebt();
initializeReplicaAttention();
}
initialize();

@ -19,7 +19,7 @@
<nav class="os-tabs" role="tablist" aria-label="对象存储工作区">
<button class="os-tab is-active" id="osTabBackends" type="button" role="tab" aria-selected="true" aria-controls="osPanelBackends" data-os-tab="backends"><i class="mdi mdi-server-network"></i><span>存储后端</span></button>
<button class="os-tab" id="osTabProtection" type="button" role="tab" aria-selected="false" aria-controls="osPanelProtection" data-os-tab="protection"><i class="mdi mdi-shield-sync-outline"></i><span>副本保护</span>{if $object_storage_summary.replication_backlog_count|default:0 > 0}<b>{$object_storage_summary.replication_backlog_count}</b>{/if}</button>
<button class="os-tab" id="osTabProtection" type="button" role="tab" aria-selected="false" aria-controls="osPanelProtection" data-os-tab="protection"><i class="mdi mdi-shield-sync-outline"></i><span>副本保护</span>{if ($replica_attention|default:false) && $replica_attention.summary.count > 0}<b>{$replica_attention.summary.count}</b>{elseif $object_storage_summary.replication_backlog_count|default:0 > 0}<b>{$object_storage_summary.replication_backlog_count}</b>{/if}</button>
<button class="os-tab" id="osTabCleanup" type="button" role="tab" aria-selected="false" aria-controls="osPanelCleanup" data-os-tab="cleanup"><i class="mdi mdi-alert-circle-outline"></i><span>清理异常</span>{if ($cleanup_debt|default:false) && $cleanup_debt.summary.count > 0}<b>{$cleanup_debt.summary.count}</b>{/if}</button>
</nav>
@ -58,6 +58,19 @@
<div class="os-panel" id="osPanelProtection" role="tabpanel" aria-labelledby="osTabProtection" data-os-panel="protection" hidden>
<section class="os-card"><div class="os-card-head"><div><p class="os-section-kicker">Replica coverage</p><h2>副本保护</h2><p>只有经大小与 SHA-256 核对为就绪的副本才计入覆盖率;连接已验证不等于对象已有双副本。</p></div></div><div class="os-status"><div class="os-status-item"><span>已保护制品</span><strong>{$object_storage_summary.protected_artifact_count|default:0}</strong></div><div class="os-status-item"><span>待复制 / 修复</span><strong>{$object_storage_summary.replication_backlog_count|default:0}</strong></div><div class="os-status-item"><span>降级制品</span><strong>{$object_storage_summary.degraded_artifact_count|default:0}</strong></div></div><div class="os-alert is-info">后台只为新操作选择健康后端;已经开始的 multipart 上传不会因健康状态变化而切换目标。读取仅从经过验证的就绪副本中选择。</div></section>
<section class="os-card" id="objectReplicaAttention">
<div class="os-card-head"><div><p class="os-section-kicker">Multipart reconciliation</p><h2>副本人工核对</h2><p>连续两次发现分段上传身份冲突后会停止自动轮询。请先在存储提供商清理多余会话,再使用原操作重新核对;本次点击不直接新建上传,只有两次确认无远端效果后才会沿用原操作安全重试。</p></div><button class="btn btn-outline-secondary btn-sm" id="osAttentionRefresh" type="button"><i class="mdi mdi-refresh me-1"></i>刷新</button></div>
{if ($replica_attention_error|default:'') != ''}<div class="os-alert is-error">{$replica_attention_error|escape}</div>
{elseif $replica_attention|default:false}
<div class="os-status os-debt-summary"><div class="os-status-item"><span>需人工核对</span><strong>{$replica_attention.summary.count} 个操作</strong></div><div class="os-status-item"><span>恢复边界</span><strong>先只读核对</strong><small>不会 Abort;无效果证据稳定后才安全重试</small></div></div>
{if $replica_attention.items|@count > 0}
<div class="os-debt-list" role="list"><div class="os-debt-list-head" aria-hidden="true"><span>制品</span><span>目标后端</span><span>冲突原因</span><span>停止时间</span><span>操作</span></div>
{foreach $replica_attention.items as $item}<article class="os-debt-row" role="listitem"><div class="os-debt-cell"><span class="os-cell-label">制品</span><strong>#{$item.artifact_id} {$item.artifact_kind|escape}</strong><small>{$item.artifact_state|escape}</small></div><div class="os-debt-cell"><span class="os-cell-label">目标后端</span><strong>#{$item.backend_id} {$item.backend_name|escape}</strong><small class="os-mono">{$item.operation_id|escape}</small></div><div class="os-debt-cell"><span class="os-cell-label">冲突原因</span><strong>{$item.error_text|escape}</strong><small class="os-mono">{$item.error_code|escape}</small></div><div class="os-debt-cell"><span class="os-cell-label">停止时间</span><strong>{if $item.attention_at > 0}{$item.attention_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}{else}未记录{/if}</strong></div><div class="os-debt-cell os-debt-action"><span class="os-cell-label">操作</span>{if $item.can_retry && $admin_can_manage|default:false}<button class="btn btn-sm btn-outline-warning os-attention-retry" type="button" data-operation-id="{$item.operation_id|escape}">重新核对</button>{else}<span class="os-waiting-action"><i class="mdi mdi-lock-clock"></i>源副本不可用</span>{/if}</div></article>{/foreach}
</div>
{if $replica_attention.pagination.total_pages > 1}<div class="os-actions os-pagination"><a class="btn btn-sm btn-outline-secondary {if $replica_attention.pagination.page <= 1}disabled{/if}" href="/admin/object-storage?attention_page={$replica_attention.pagination.page-1}#protection">上一页</a><span class="os-help">第 {$replica_attention.pagination.page} / {$replica_attention.pagination.total_pages} 页</span><a class="btn btn-sm btn-outline-secondary {if $replica_attention.pagination.page >= $replica_attention.pagination.total_pages}disabled{/if}" href="/admin/object-storage?attention_page={$replica_attention.pagination.page+1}#protection">下一页</a></div>{/if}
{else}<div class="os-empty"><i class="mdi mdi-check-circle-outline"></i><strong>当前没有副本身份冲突</strong><span>自动核对没有被不确定的分段会话阻断。</span></div>{/if}{/if}
<div class="os-notice" id="osAttentionNotice" role="status" aria-live="polite"></div>
</section>
</div>
<div class="os-panel" id="osPanelCleanup" role="tabpanel" aria-labelledby="osTabCleanup" data-os-panel="cleanup" hidden>

@ -52,11 +52,12 @@ foreach ([['user_id' => 42, 'is_admin' => false], ['user_id' => 0, 'is_admin' =>
$assert($calls === [], 'Unauthorized requests performed probes.');
$payload = $service->snapshot($actor);
$checks = array_column($payload['checks'], null, 'key');
$assert(count($checks) === 10 && $calls === ['default', 'log', 'agents', 'redis'], 'Missing or duplicate probes.');
$assert(count($checks) === 11 && $calls === ['default', 'log', 'agents', 'redis'], 'Missing or duplicate probes.');
$assert($checks['agents']['status'] === 'ok' && $checks['worker']['status'] === 'busy'
&& $checks['policy']['status'] === 'unknown'
&& $checks['vpc']['status'] === 'unknown'
&& $checks['notification']['status'] === 'unknown'
&& $checks['storage_replica']['status'] === 'unknown'
&& $checks['lifecycle']['status'] === 'warning',
'Health or heartbeat semantics changed.');
$assert(!str_contains(json_encode($payload), 'MUST_NOT_EXPOSE'), 'Heartbeat internal fields leaked.');
@ -181,7 +182,7 @@ $response = (new CloudAdminRuntimeController())->index($request, new Response())
$assert($response->getStatusCode() === 200
&& $response->getHeaderLine('Cache-Control') === 'private, no-store', 'Runtime response cached or unavailable.');
$decoded = json_decode((string) $response->getBody(), true);
$assert(count($decoded['checks']) === 10
$assert(count($decoded['checks']) === 11
&& array_column($decoded['checks'], 'status', 'key')['agents'] === 'error',
'Partial failure lost other checks or fabricated Agent configuration health.');
$routes = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php');

@ -47,7 +47,8 @@ try {
$missing = $testRoot . '/not-created';
$empty = $checks($missing);
$assert(array_keys($empty) === [
'worker', 'policy', 'vpc', 'recovery', 'notification', 'lifecycle',
'worker', 'policy', 'vpc', 'recovery', 'notification',
'storage_replica', 'lifecycle',
]
&& array_unique(array_column($empty, 'status')) === ['unknown'] && !file_exists($missing),
'Missing snapshot must be unknown, cover all kinds, and never create runtime files.');
@ -60,7 +61,10 @@ try {
$notification = CloudRuntimeHeartbeat::start(
'notification', false, $directory, $clock
);
$assert(count($files($directory)) === 5, 'Concurrent worker identities overwrite one another.');
$storageReplica = CloudRuntimeHeartbeat::start(
'storage_replica', false, $directory, $clock
);
$assert(count($files($directory)) === 6, 'Concurrent worker identities overwrite one another.');
$assert(is_readable($directory) && is_writable($directory),
'Runtime directory is not readable and writable.');
foreach ($files($directory) as $path) {
@ -71,13 +75,20 @@ try {
&& $checks($directory)['policy']['active_count'] === 2
&& $checks($directory)['recovery']['active_count'] === 1
&& $checks($directory)['notification']['active_count'] === 1
&& $checks($directory)['notification']['label'] === '客户通知 worker',
&& $checks($directory)['notification']['label'] === '客户通知 worker'
&& $checks($directory)['storage_replica']['active_count'] === 1
&& $checks($directory)['storage_replica']['label'] === '对象存储副本 worker',
'Starting workers or multiple policy reporters were not represented.');
$notification->busy('notification');
$assert(str_contains(
$checks($directory)['notification']['message'],
'邮件通知'
), 'Customer notification delivery did not receive an isolated runtime phase.');
$storageReplica->busy('storage_replica_tick');
$assert(str_contains(
$checks($directory)['storage_replica']['message'],
'对象存储副本复制或核对'
), 'Object replica work did not receive an isolated runtime phase.');
$normal->busy('worker_tick');
$assert(str_contains($checks($directory)['worker']['message'], '任务消费或核对'),

@ -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…
Cancel
Save