From f8c35863babc04619d3deee8d4b6ce7a73c02ef6 Mon Sep 17 00:00:00 2001 From: codex Date: Fri, 6 Nov 2026 18:27:08 +0800 Subject: [PATCH] feat(storage): add resilient replica worker --- .../cmd/virt-cloud-storage-replicator/main.go | 2 +- .../main_test.go | 18 + .../virt-cloud-storage-replica-worker.service | 25 + docs/DEPLOYMENT.md | 14 +- web/app/Command/CloudStorageReplicaWorker.php | 72 + web/app/Command/XCat.php | 3 + .../Admin/ObjectStorageController.php | 61 + .../Cloud/CloudRuntimeHealthService.php | 1 + .../Services/Cloud/CloudRuntimeHeartbeat.php | 12 +- .../Cloud/CloudStorageArtifactService.php | 1967 +++++++++++++++++ .../CloudStorageReplicaAttentionService.php | 150 ++ .../Cloud/CloudStorageReplicaHelper.php | 355 +++ .../CloudStorageReplicaWorkerService.php | 660 ++++++ web/config/routes.php | 2 + web/public/cloud/admin-object-storage.js | 40 + .../views/venix/admin/object_storage.tpl | 15 +- web/tests/CloudRuntimeHealthTest.php | 5 +- web/tests/CloudRuntimeHeartbeatTest.php | 17 +- web/tests/CloudStorageArtifactServiceTest.php | 926 ++++++++ web/tests/CloudStorageReplicaHelperTest.php | 135 ++ .../CloudStorageReplicaWorkerContractTest.php | 79 + 21 files changed, 4547 insertions(+), 12 deletions(-) create mode 100644 deploy/virt-cloud-storage-replica-worker.service create mode 100644 web/app/Command/CloudStorageReplicaWorker.php create mode 100644 web/app/Services/Cloud/CloudStorageArtifactService.php create mode 100644 web/app/Services/Cloud/CloudStorageReplicaAttentionService.php create mode 100644 web/app/Services/Cloud/CloudStorageReplicaHelper.php create mode 100644 web/app/Services/Cloud/CloudStorageReplicaWorkerService.php create mode 100644 web/tests/CloudStorageArtifactServiceTest.php create mode 100644 web/tests/CloudStorageReplicaHelperTest.php create mode 100644 web/tests/CloudStorageReplicaWorkerContractTest.php diff --git a/agent/cmd/virt-cloud-storage-replicator/main.go b/agent/cmd/virt-cloud-storage-replicator/main.go index 448f47d7..cc7d2cc6 100644 --- a/agent/cmd/virt-cloud-storage-replicator/main.go +++ b/agent/cmd/virt-cloud-storage-replicator/main.go @@ -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"` } diff --git a/agent/cmd/virt-cloud-storage-replicator/main_test.go b/agent/cmd/virt-cloud-storage-replicator/main_test.go index 2f02668c..cfcebf50 100644 --- a/agent/cmd/virt-cloud-storage-replicator/main_test.go +++ b/agent/cmd/virt-cloud-storage-replicator/main_test.go @@ -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{ diff --git a/deploy/virt-cloud-storage-replica-worker.service b/deploy/virt-cloud-storage-replica-worker.service new file mode 100644 index 00000000..56c4d50e --- /dev/null +++ b/deploy/virt-cloud-storage-replica-worker.service @@ -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 diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 2b32010e..6ddb873c 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -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 diff --git a/web/app/Command/CloudStorageReplicaWorker.php b/web/app/Command/CloudStorageReplicaWorker.php new file mode 100644 index 00000000..6988613a --- /dev/null +++ b/web/app/Command/CloudStorageReplicaWorker.php @@ -0,0 +1,72 @@ +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; + } +} diff --git a/web/app/Command/XCat.php b/web/app/Command/XCat.php index 1919fe17..66f71603 100644 --- a/web/app/Command/XCat.php +++ b/web/app/Command/XCat.php @@ -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 [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" diff --git a/web/app/Controllers/Admin/ObjectStorageController.php b/web/app/Controllers/Admin/ObjectStorageController.php index e4ce3986..6306b8ba 100644 --- a/web/app/Controllers/Admin/ObjectStorageController.php +++ b/web/app/Controllers/Admin/ObjectStorageController.php @@ -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) { diff --git a/web/app/Services/Cloud/CloudRuntimeHealthService.php b/web/app/Services/Cloud/CloudRuntimeHealthService.php index f194fa51..ef21132b 100644 --- a/web/app/Services/Cloud/CloudRuntimeHealthService.php +++ b/web/app/Services/Cloud/CloudRuntimeHealthService.php @@ -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) { diff --git a/web/app/Services/Cloud/CloudRuntimeHeartbeat.php b/web/app/Services/Cloud/CloudRuntimeHeartbeat.php index 7bdf729c..e3bfd220 100644 --- a/web/app/Services/Cloud/CloudRuntimeHeartbeat.php +++ b/web/app/Services/Cloud/CloudRuntimeHeartbeat.php @@ -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; })); diff --git a/web/app/Services/Cloud/CloudStorageArtifactService.php b/web/app/Services/Cloud/CloudStorageArtifactService.php new file mode 100644 index 00000000..d93b829c --- /dev/null +++ b/web/app/Services/Cloud/CloudStorageArtifactService.php @@ -0,0 +1,1967 @@ + */ + private const REPLICA_ATTENTION_ERRORS = [ + 'replica_multipart_identity_ambiguous', + 'replica_multipart_identity_mismatch', + 'replica_multipart_identity_untrusted', + ]; + + /** @return list */ + public static function replicaAttentionErrors(): array + { + return self::REPLICA_ATTENTION_ERRORS; + } + + /** + * Reserve one immutable artifact and every currently eligible replica. + * No provider request is made here. + * + * @return array + */ + public static function beginPublication( + string $kind, + string $objectSuffix, + int $sizeBytes, + string $sha256, + string $requestIdempotencyKey, + string $requestFingerprint, + array $owner + ): array { + self::assertObjectIdentity($sizeBytes, $sha256); + return self::reservePublication( + $kind, + $objectSuffix, + $sizeBytes, + $sha256, + $sizeBytes, + $requestIdempotencyKey, + $requestFingerprint, + $owner + ); + } + + /** Reserve an Agent upload before its exact receipt identity is known. */ + public static function beginAgentPublication( + string $kind, + string $objectSuffix, + int $maximumSizeBytes, + string $requestIdempotencyKey, + string $requestFingerprint, + array $owner + ): array { + if ($maximumSizeBytes < 1) { + throw new CloudError('对象存储制品最大容量无效', 422); + } + return self::reservePublication( + $kind, + $objectSuffix, + 0, + '', + $maximumSizeBytes, + $requestIdempotencyKey, + $requestFingerprint, + $owner + ); + } + + /** @return array */ + private static function reservePublication( + string $kind, + string $objectSuffix, + int $sizeBytes, + string $sha256, + int $maximumSizeBytes, + string $requestIdempotencyKey, + string $requestFingerprint, + array $owner + ): array { + $policy = CloudStorageDurabilityPolicy::forKind($kind); + $objectSuffix = self::objectSuffix($objectSuffix); + $owner = self::owner($kind, $owner); + self::assertRequestIdentity( + $requestIdempotencyKey, + $requestFingerprint + ); + $connection = (new CloudStorageArtifact())->getConnection(); + $operationId = $connection->transaction(static function () use ( + $connection, + $kind, + $objectSuffix, + $sizeBytes, + $sha256, + $maximumSizeBytes, + $requestIdempotencyKey, + $requestFingerprint, + $policy, + $owner + ): string { + $existing = CloudStorageOperation::query() + ->where('request_idempotency_key', $requestIdempotencyKey) + ->lockForUpdate()->first(); + if ($existing instanceof CloudStorageOperation) { + if ((string) $existing->kind !== 'publish' + || !hash_equals( + (string) $existing->request_fingerprint, + $requestFingerprint + )) { + throw new CloudError( + '对象存储发布幂等键已用于其他请求', + 409 + ); + } + self::assertExistingOwner($existing, $owner); + return (string) $existing->operation_id; + } + + $backends = CloudStorageBackend::query() + ->where('admin_state', '<>', 'retired') + ->orderBy('write_priority')->orderBy('id') + ->lockForUpdate()->get()->map( + static fn (CloudStorageBackend $backend): array => [ + 'id' => (int) $backend->id, + 'config_revision' => (int) $backend->config_revision, + 'tested_revision' => (int) $backend->tested_revision, + 'admin_state' => (string) $backend->admin_state, + 'health_state' => (string) $backend->health_state, + 'write_priority' => (int) $backend->write_priority, + 'failure_domain' => (string) $backend->failure_domain, + 'prefix' => (string) $backend->prefix, + ] + )->values()->all(); + $selected = CloudStoragePlacementPolicy::select( + $backends, + $policy['desired_copies'], + $policy['required_copies'] + ); + + $now = time(); + $artifact = new CloudStorageArtifact(); + $artifact->artifact_key = bin2hex(random_bytes(16)); + $artifact->kind = $kind; + $artifact->maximum_size_bytes = $maximumSizeBytes; + $artifact->size_bytes = $sizeBytes; + $artifact->sha256 = $sha256; + $artifact->durability_policy = $policy['policy']; + $artifact->desired_copies = $policy['desired_copies']; + $artifact->required_copies = $policy['required_copies']; + $artifact->state = 'publishing'; + $artifact->last_operation_id = null; + $artifact->verified_at = 0; + $artifact->created_at = $now; + $artifact->updated_at = $now; + $artifact->save(); + + $publication = new CloudStoragePublication(); + $publication->publication_key = bin2hex(random_bytes(16)); + $publication->artifact_id = (int) $artifact->id; + $publication->backup_id = $owner['backup_id']; + $publication->template_import_intent_id = + $owner['template_import_intent_id']; + $publication->rescue_template_id = $owner['rescue_template_id']; + $publication->state = 'waiting_primary'; + $publication->attempts = 0; + $publication->available_at = 0; + $publication->lease_token = null; + $publication->lease_until = 0; + $publication->last_error_code = ''; + $publication->coverage_ready_at = null; + $publication->finalized_at = null; + $publication->created_at = $now; + $publication->updated_at = $now; + $publication->save(); + + $primaryOperationId = bin2hex(random_bytes(16)); + $primaryBackendId = (int) $selected[0]['id']; + foreach ($selected as $index => $backend) { + $replica = new CloudStorageReplica(); + $replica->replica_key = bin2hex(random_bytes(16)); + $replica->artifact_id = (int) $artifact->id; + $replica->backend_id = (int) $backend['id']; + $replica->role = $index === 0 ? 'primary' : 'secondary'; + $replica->object_key = self::objectKey( + (string) $backend['prefix'], + $objectSuffix + ); + $replica->object_version_id = ''; + $replica->object_etag = ''; + $replica->size_bytes = 0; + $replica->sha256 = ''; + $replica->state = 'reserved'; + $replica->publish_operation_id = null; + $replica->delete_operation_id = null; + $replica->delete_generation = 0; + $replica->delete_cycle_attempts = 0; + $replica->delete_presence_confirmations = 0; + $replica->delete_last_checked_at = 0; + $replica->delete_next_check_at = 0; + $replica->delete_attention_at = null; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = ''; + $replica->verified_at = 0; + $replica->created_at = $now; + $replica->updated_at = $now; + $replica->save(); + + $operation = new CloudStorageOperation(); + $operation->operation_id = $index === 0 + ? $primaryOperationId : bin2hex(random_bytes(16)); + $operation->request_idempotency_key = $index === 0 + ? $requestIdempotencyKey + : self::copyIdempotencyKey( + $requestIdempotencyKey, + (int) $backend['id'] + ); + $operation->request_fingerprint = $index === 0 + ? $requestFingerprint : hash('sha256', implode('|', [ + 'copy', (string) $artifact->artifact_key, + (string) $primaryBackendId, + (string) $backend['id'], $objectSuffix, + ])); + $operation->artifact_id = (int) $artifact->id; + $operation->replica_id = (int) $replica->id; + $operation->source_backend_id = $index === 0 + ? null : $primaryBackendId; + $operation->target_backend_id = (int) $backend['id']; + $operation->kind = $index === 0 ? 'publish' : 'copy'; + self::initializeOperation($operation, $now); + if ($index === 0) { + $operation->result_json = json_encode([ + 'maximum_size_bytes' => $maximumSizeBytes, + 'object_suffix' => $objectSuffix, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + } else { + $operation->available_at = + self::COPY_BLOCKED_UNTIL_PRIMARY; + } + $operation->save(); + $replica->publish_operation_id = $operation->operation_id; + $replica->save(); + } + $artifact->last_operation_id = $primaryOperationId; + $artifact->save(); + return $primaryOperationId; + }); + + return self::publicationView($operationId); + } + + /** Internal runtime; credentials must never enter a response or log. */ + public static function primaryRuntime(string $operationId): array + { + $view = self::publicationView($operationId); + return CloudObjectStorageBackendRegistry::runtime( + (int) $view['backend_id'], + true + ); + } + + /** Fence the primary operation immediately before remote publish I/O. */ + public static function markPrimaryDispatching(string $operationId): array + { + self::assertOperationId($operationId); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ($operationId): void { + $operation = self::primaryOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + if ((string) $operation->phase !== 'accepted' + || (string) $replica->state !== 'reserved' + || (string) $artifact->state !== 'publishing') { + throw new CloudError( + '对象存储发布操作已经派发或结束,禁止再次提交', + 409 + ); + } + $now = time(); + $operation->phase = 'dispatching'; + $operation->attempts = (int) $operation->attempts + 1; + $operation->updated_at = $now; + $operation->save(); + $replica->state = 'publishing'; + $replica->updated_at = $now; + $replica->save(); + }); + return self::publicationView($operationId); + } + + /** @param array $identity */ + public static function completePrimary( + string $operationId, + array $identity + ): array { + self::assertOperationId($operationId); + $size = self::positiveInt($identity['size_bytes'] ?? null); + $receiptSha = $identity['sha256'] ?? null; + if (!is_string($receiptSha) + || preg_match('/^[a-f0-9]{64}$/D', $receiptSha) !== 1) { + throw new CloudError('对象存储主副本哈希身份无效', 502); + } + $etag = self::providerIdentity($identity['etag'] ?? null, 256); + $versionId = self::providerVersionIdentity( + $identity['version_id'] ?? null, + 1024 + ); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $size, + $receiptSha, + $etag, + $versionId + ): void { + $operation = self::primaryOperationLocked($operationId); + $copyOperations = self::copyOperationsLocked( + (int) $operation->artifact_id + ); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + if ((string) $operation->phase === 'terminal') { + if ((string) $operation->outcome === 'succeeded') { + self::assertSettledReplicaIdentity( + $artifact, + $replica, + $size, + $receiptSha, + $etag, + $versionId, + '对象存储重复主副本回执身份不一致' + ); + return; + } + throw new CloudError('对象存储发布操作已失败,禁止覆盖结算', 409); + } + if (!in_array((string) $operation->phase, + ['dispatching', 'awaiting_receipt', 'reconciling'], true)) { + throw new CloudError('对象存储发布操作尚未派发', 409); + } + $pendingIdentity = (int) $artifact->size_bytes === 0 + && (string) $artifact->sha256 === ''; + if ($pendingIdentity) { + if ($size > (int) $artifact->maximum_size_bytes) { + throw new CloudError( + '对象存储返回的主副本身份超出预留边界', + 409 + ); + } + $artifact->size_bytes = $size; + $artifact->sha256 = $receiptSha; + } elseif ($size !== (int) $artifact->size_bytes + || !hash_equals( + (string) $artifact->sha256, + $receiptSha + )) { + throw new CloudError('对象存储返回的主副本身份不一致', 409); + } + $now = time(); + $replica->size_bytes = $size; + $replica->sha256 = (string) $artifact->sha256; + $replica->object_etag = $etag; + $replica->object_version_id = $versionId; + $replica->state = 'ready'; + $replica->error_code = ''; + $replica->verified_at = $now; + $replica->updated_at = $now; + $replica->save(); + self::settleSucceeded($operation, [ + 'size_bytes' => $size, + 'sha256' => (string) $artifact->sha256, + 'etag' => $etag, + 'version_id' => $versionId, + ], $now); + foreach ($copyOperations as $copyOperation) { + if ((string) $copyOperation->phase === 'accepted') { + $copyOperation->available_at = $now; + $copyOperation->updated_at = $now; + $copyOperation->save(); + } + } + self::projectArtifactLocked($artifact, $replicas, $now); + }); + return self::publicationView($operationId); + } + + public static function failPrimary( + string $operationId, + string $effectResolution, + string $errorCode + ): array { + self::assertOperationId($operationId); + self::assertEffectResolution($effectResolution); + $errorCode = self::errorCode($errorCode); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $effectResolution, + $errorCode + ): void { + $operation = self::primaryOperationLocked($operationId); + if ((string) $operation->phase === 'terminal') { + if ($effectResolution !== 'not_applied') { + throw new CloudError( + '对象存储发布终态与失败回执冲突', + 409 + ); + } + self::assertTerminalFailure( + $operation, + false, + true, + 'not_applied', + $errorCode, + '对象存储发布终态与失败回执冲突' + ); + return; + } + $copyOperations = self::copyOperationsLocked( + (int) $operation->artifact_id + ); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + $now = time(); + if ($effectResolution === 'not_applied') { + self::settleFailed($operation, false, true, + 'not_applied', $errorCode, $now); + $replica->state = 'degraded'; + foreach ($copyOperations as $copyOperation) { + if ((string) $copyOperation->phase !== 'terminal') { + self::settleFailed( + $copyOperation, + false, + false, + 'not_applied', + 'primary_publish_not_applied', + $now + ); + $secondary = self::operationReplica( + $copyOperation, + $replicas + ); + $secondary->state = 'degraded'; + $secondary->lease_token = null; + $secondary->lease_until = 0; + $secondary->error_code = + 'primary_publish_not_applied'; + $secondary->updated_at = $now; + $secondary->save(); + } + } + } else { + $operation->phase = 'reconciling'; + $operation->outcome = null; + $operation->effect_resolution = $effectResolution; + $operation->effect_may_have_applied = null; + $operation->safe_to_resubmit = null; + $operation->next_check_at = $now + 60; + $operation->error_code = $errorCode; + $operation->updated_at = $now; + $operation->save(); + $replica->state = 'publishing'; + } + $replica->error_code = $errorCode; + $replica->updated_at = $now; + $replica->save(); + $publication = CloudStoragePublication::query() + ->where('artifact_id', $artifact->id) + ->lockForUpdate()->firstOrFail(); + if ($effectResolution === 'not_applied') { + $publication->state = 'failed'; + $publication->last_error_code = $errorCode; + $publication->available_at = 0; + $publication->updated_at = $now; + $publication->save(); + } + if ((int) $artifact->size_bytes > 0 + && (string) $artifact->sha256 !== '') { + self::projectArtifactLocked($artifact, $replicas, $now); + } elseif ($effectResolution === 'not_applied') { + // A pending identity may only exist in publishing state. The + // failed publication row is the durable terminal signal. + $artifact->state = 'publishing'; + $artifact->updated_at = $now; + $artifact->save(); + } + }); + return self::publicationView($operationId); + } + + /** + * Mint a read-only URL for one verified replica selected by health. + * + * @return array{url:string,artifact_id:int,replica_id:int,backend_id:int, + * size_bytes:int,sha256:string,expires_at:int} + */ + public static function presignedRead( + int $artifactId, + int $expiresSeconds = 3600, + ?CloudObjectStorageS3Client $client = null + ): array { + if ($artifactId < 1 || $expiresSeconds < 60 + || $expiresSeconds > 604800) { + throw new CloudError('对象存储读取参数无效', 422); + } + $artifact = CloudStorageArtifact::query()->whereKey($artifactId)->first(); + if (!$artifact instanceof CloudStorageArtifact) { + throw new CloudError('对象存储制品不存在', 404); + } + $replicas = CloudStorageReplica::query() + ->where('artifact_id', $artifactId)->get(); + $backends = CloudStorageBackend::query() + ->whereIn('id', $replicas->pluck('backend_id')->all()) + ->get()->keyBy('id'); + $artifactData = self::artifactData($artifact); + $coverage = CloudStorageDurabilityPolicy::project( + $artifactData, + $replicas->map(static fn (CloudStorageReplica $replica): array => + self::replicaData($replica))->values()->all() + ); + if (!$coverage['can_read']) { + throw new CloudError('对象存储制品尚未达到可读取副本数', 503); + } + $selected = CloudStorageReadRouter::select( + $artifactData, + $replicas->map(static function (CloudStorageReplica $replica) use ( + $backends + ): array { + $backend = $backends->get((int) $replica->backend_id); + return self::replicaData($replica) + ['backend' => [ + 'admin_state' => (string) ($backend?->admin_state ?? ''), + 'health_state' => (string) ($backend?->health_state ?? ''), + 'write_priority' => (int) ($backend?->write_priority ?? -1), + ]]; + })->values()->all() + ); + $replica = $replicas->firstWhere('id', (int) $selected['id']); + if (!$replica instanceof CloudStorageReplica) { + throw new CloudError('对象存储副本不存在', 503); + } + $runtime = CloudObjectStorageBackendRegistry::runtime( + (int) $replica->backend_id, + false + ); + $url = ($client ?? new CloudObjectStorageS3Client()) + ->presignedVersionedGet( + $runtime['config'], + $runtime['credentials'], + (string) $replica->object_key, + (string) $replica->object_version_id, + $expiresSeconds + ); + return [ + 'url' => $url, + 'artifact_id' => (int) $artifact->id, + 'replica_id' => (int) $replica->id, + 'backend_id' => (int) $replica->backend_id, + 'size_bytes' => (int) $artifact->size_bytes, + 'sha256' => (string) $artifact->sha256, + 'expires_at' => time() + $expiresSeconds, + ]; + } + + /** @return array */ + public static function publicationView(string $operationId): array + { + self::assertOperationId($operationId); + $operation = CloudStorageOperation::query() + ->where('operation_id', $operationId)->first(); + if (!$operation instanceof CloudStorageOperation + || (string) $operation->kind !== 'publish') { + throw new CloudError('对象存储发布操作不存在', 404); + } + $artifact = CloudStorageArtifact::query() + ->whereKey((int) $operation->artifact_id)->firstOrFail(); + $replica = CloudStorageReplica::query() + ->whereKey((int) $operation->replica_id)->firstOrFail(); + return [ + 'operation_id' => (string) $operation->operation_id, + 'phase' => (string) $operation->phase, + 'outcome' => $operation->outcome === null + ? null : (string) $operation->outcome, + 'effect_resolution' => (string) $operation->effect_resolution, + 'artifact_id' => (int) $artifact->id, + 'artifact_key' => (string) $artifact->artifact_key, + 'artifact_state' => (string) $artifact->state, + 'replica_id' => (int) $replica->id, + 'backend_id' => (int) $replica->backend_id, + 'object_key' => (string) $replica->object_key, + 'can_publish' => (string) $operation->phase === 'accepted' + && (string) $replica->state === 'reserved', + ]; + } + + /** + * Lease one durable secondary-copy operation. The returned view contains + * immutable object identity only; provider capabilities and credentials + * are minted later by the worker and are never persisted. + * + * @return array|null + */ + public static function claimReplicaWork( + int $now, + int $leaseSeconds = 21720 + ): ?array { + if ($now < 1 || $leaseSeconds < 30 || $leaseSeconds > 25200) { + throw new \InvalidArgumentException('Invalid replica lease'); + } + $connection = (new CloudStorageOperation())->getConnection(); + return $connection->transaction(static function () use ( + $now, + $leaseSeconds + ): ?array { + $operation = CloudStorageOperation::query() + ->where('kind', 'copy') + ->where(static function ($query) use ($now): void { + $query->where(static function ($accepted) use ($now): void { + $accepted->where('phase', 'accepted') + ->where('available_at', '<=', $now); + })->orWhere(static function ($reconcile) use ($now): void { + $reconcile->where('phase', 'reconciling') + ->where('next_check_at', '<=', $now); + })->orWhere(static function ($stale) use ($now): void { + $stale->whereIn('phase', [ + 'dispatching', 'awaiting_receipt', + ])->where('lease_until', '<=', $now); + }); + }) + ->where(static function ($query) use ($now): void { + $query->whereNull('lease_token') + ->orWhere('lease_until', '<=', $now); + }) + ->orderBy('id')->lockForUpdate()->first(); + if (!$operation instanceof CloudStorageOperation) { + return null; + } + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + $source = self::backendReplica( + $replicas, + (int) $operation->source_backend_id + ); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return null; + } + $mode = (string) $operation->phase === 'accepted' + ? 'dispatch' : 'reconcile'; + if (in_array((string) $operation->phase, + ['dispatching', 'awaiting_receipt'], true)) { + $operation->phase = 'reconciling'; + $operation->effect_resolution = 'unknown'; + $operation->error_code = 'replica_worker_lease_expired'; + $operation->next_check_at = $now; + $mode = 'reconcile'; + } elseif ($mode === 'dispatch') { + $operation->phase = 'dispatching'; + $operation->attempts = (int) $operation->attempts + 1; + } + $leaseToken = bin2hex(random_bytes(16)); + $operation->lease_token = $leaseToken; + $operation->lease_until = $now + $leaseSeconds; + $operation->updated_at = $now; + $operation->save(); + + $replica->lease_token = $leaseToken; + $replica->lease_until = $now + $leaseSeconds; + if ($mode === 'dispatch') { + $replica->state = 'copying'; + } + $replica->updated_at = $now; + $replica->save(); + return [ + 'operation_id' => (string) $operation->operation_id, + 'lease_token' => $leaseToken, + 'mode' => $mode, + 'artifact_id' => (int) $artifact->id, + 'size_bytes' => (int) $artifact->size_bytes, + 'sha256' => (string) $artifact->sha256, + 'source_backend_id' => (int) $operation->source_backend_id, + 'source_object_key' => (string) $source->object_key, + 'source_version_id' => (string) $source->object_version_id, + 'source_state' => (string) $source->state, + 'target_backend_id' => (int) $operation->target_backend_id, + 'target_object_key' => (string) $replica->object_key, + 'metadata' => self::copyMetadata($operation->result_json), + 'operation_created_at' => (int) $operation->created_at, + 'operation_available_at' => (int) $operation->available_at, + ]; + }); + } + + /** Persist only provider identifiers and multipart geometry, never URLs. */ + public static function markReplicaAwaitingReceipt( + string $operationId, + string $leaseToken, + array $metadata, + int $now + ): void { + $metadata = self::sanitizeCopyMetadata($metadata); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $metadata, + $now + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + $phase = (string) $operation->phase; + if ($phase === 'reconciling') { + $stored = self::copyMetadata($operation->result_json); + if (!isset($metadata['upload_id'])) { + throw new CloudError( + '对象副本精确分段会话不能被替换', + 409 + ); + } + if (isset($stored['upload_id'])) { + if (!hash_equals( + (string) $stored['upload_id'], + (string) $metadata['upload_id'] + ) + || ($stored['multipart_presence_confirmations'] ?? 0) + < 1 + || ($metadata['multipart_presence_confirmations'] ?? 0) + < 2) { + throw new CloudError( + '对象副本分段会话缺少稳定恢复证据', + 409 + ); + } + } + } elseif ($phase !== 'dispatching') { + throw new CloudError('对象副本复制操作不在派发阶段', 409); + } + $operation->phase = 'awaiting_receipt'; + $operation->effect_resolution = 'unknown'; + $operation->result_json = json_encode( + $metadata, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ); + $operation->next_check_at = (int) $operation->lease_until; + $operation->updated_at = $now; + $operation->save(); + }); + } + + /** @param array $identity */ + public static function completeReplica( + string $operationId, + string $leaseToken, + array $identity, + int $now + ): void { + $size = self::positiveInt($identity['size_bytes'] ?? null); + $sha256 = $identity['sha256'] ?? null; + if (!is_string($sha256) + || preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1) { + throw new CloudError('对象副本哈希身份无效', 502); + } + $etag = self::providerIdentity($identity['etag'] ?? null, 256); + $versionId = self::providerVersionIdentity( + $identity['version_id'] ?? null, + 1024 + ); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $size, + $sha256, + $etag, + $versionId, + $now + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + if ((string) $operation->phase === 'terminal') { + if ((string) $operation->outcome === 'succeeded') { + self::assertSettledReplicaIdentity( + $artifact, + $replica, + $size, + $sha256, + $etag, + $versionId, + '对象副本重复回执身份不一致' + ); + return; + } + throw new CloudError('对象副本复制操作已失败', 409); + } + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + if ($size !== (int) $artifact->size_bytes + || !hash_equals((string) $artifact->sha256, $sha256)) { + throw new CloudError('对象副本身份与制品不一致', 409); + } + if ((string) $replica->object_version_id !== '' + && !hash_equals( + (string) $replica->object_version_id, + $versionId + )) { + throw new CloudError('对象副本版本身份不一致', 409); + } + $replica->size_bytes = $size; + $replica->sha256 = $sha256; + $replica->object_etag = $etag; + $replica->object_version_id = $versionId; + $replica->state = 'ready'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = ''; + $replica->verified_at = $now; + $replica->updated_at = $now; + $replica->save(); + self::settleSucceeded($operation, [ + 'size_bytes' => $size, + 'sha256' => $sha256, + 'etag' => $etag, + 'version_id' => $versionId, + ], $now); + self::projectArtifactLocked($artifact, $replicas, $now); + }); + } + + public static function markReplicaUnknown( + string $operationId, + string $leaseToken, + string $errorCode, + int $now, + int $delaySeconds, + array $metadata = [] + ): void { + $errorCode = self::errorCode($errorCode); + if ($delaySeconds < 5 || $delaySeconds > 3600) { + throw new \InvalidArgumentException('Invalid reconciliation delay'); + } + $metadata = self::sanitizeCopyMetadata($metadata); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $errorCode, + $now, + $delaySeconds, + $metadata + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + $operation->phase = 'reconciling'; + $operation->effect_resolution = 'unknown'; + $operation->lease_token = null; + $operation->lease_until = 0; + $operation->next_check_at = $now + $delaySeconds; + $operation->error_code = $errorCode; + $operation->result_json = json_encode( + $metadata, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ); + $operation->updated_at = $now; + $operation->save(); + $replica->state = 'copying'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = $errorCode; + $replica->updated_at = $now; + $replica->save(); + }); + } + + /** Stop automatic reconciliation after stable multipart identity conflict. */ + public static function markReplicaAttention( + string $operationId, + string $leaseToken, + string $errorCode, + int $now, + array $metadata + ): void { + $errorCode = self::replicaAttentionError($errorCode); + $metadata = self::sanitizeCopyMetadata($metadata); + if (($metadata['multipart_attention_confirmations'] ?? 0) < 2 + || ($metadata['multipart_attention_error_code'] ?? '') + !== $errorCode) { + throw new CloudError('对象副本人工核对证据不足', 409); + } + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $errorCode, + $now, + $metadata + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + if ((string) $operation->phase === 'terminal') { + self::assertTerminalFailure( + $operation, + true, + false, + 'unknown', + $errorCode, + '对象副本人工核对终态冲突' + ); + return; + } + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + $operation->result_json = json_encode( + $metadata, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ); + self::settleFailed( + $operation, + true, + false, + 'unknown', + $errorCode, + $now + ); + $replica->state = 'degraded'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = $errorCode; + $replica->updated_at = $now; + $replica->save(); + self::projectArtifactLocked($artifact, $replicas, $now); + }); + } + + /** Re-open the same copy operation for read-only administrator reconciliation. */ + public static function reopenReplicaAttention( + string $operationId, + int $now + ): void { + self::assertOperationId($operationId); + if ($now < 1) { + throw new \InvalidArgumentException('Invalid attention time'); + } + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $now + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + if ((string) $operation->phase === 'reconciling' + && (string) $operation->error_code + === 'admin_reconcile_requested') { + return; + } + $attentionCode = self::replicaAttentionError( + (string) $operation->error_code + ); + self::assertTerminalFailure( + $operation, + true, + false, + 'unknown', + $attentionCode, + '对象副本不在可重新核对的人工处理终态' + ); + if ((string) $replica->state !== 'degraded' + || !hash_equals( + (string) $replica->error_code, + $attentionCode + )) { + throw new CloudError( + '目标副本已不属于该人工核对操作', + 409 + ); + } + if (in_array((string) $artifact->state, + ['retiring', 'delete_attention', 'deleted'], true)) { + throw new CloudError('对象已进入清理流程,不能重新核对副本', 409); + } + $source = self::backendReplica( + $replicas, + (int) $operation->source_backend_id + ); + if ((string) $source->state !== 'ready' + || (int) $source->size_bytes !== (int) $artifact->size_bytes + || !hash_equals( + (string) $artifact->sha256, + (string) $source->sha256 + )) { + throw new CloudError('对象副本的可验证源已不可用', 409); + } + $metadata = self::copyMetadata($operation->result_json); + $metadata['absence_confirmations'] = 0; + $metadata['multipart_absence_confirmations'] = 0; + $metadata['multipart_presence_confirmations'] = 0; + $metadata['multipart_attention_confirmations'] = 0; + unset($metadata['multipart_attention_error_code']); + $operation->phase = 'reconciling'; + $operation->outcome = null; + $operation->effect_resolution = 'unknown'; + $operation->effect_may_have_applied = null; + $operation->safe_to_resubmit = null; + $operation->lease_token = null; + $operation->lease_until = 0; + $operation->next_check_at = $now; + $operation->error_code = 'admin_reconcile_requested'; + $operation->result_json = json_encode( + self::sanitizeCopyMetadata($metadata), + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ); + $operation->terminal_at = null; + $operation->updated_at = $now; + $operation->save(); + $replica->state = 'copying'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = 'admin_reconcile_requested'; + $replica->updated_at = $now; + $replica->save(); + self::projectArtifactLocked($artifact, $replicas, $now); + }); + } + + public static function failReplicaNotApplied( + string $operationId, + string $leaseToken, + string $errorCode, + int $now, + bool $safeToResubmit = false + ): void { + if ($safeToResubmit) { + self::rescheduleReplicaNotApplied( + $operationId, + $leaseToken, + $errorCode, + $now, + 60 + ); + return; + } + $errorCode = self::errorCode($errorCode); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $errorCode, + $now, + $safeToResubmit + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + if ((string) $operation->phase === 'terminal') { + self::assertTerminalFailure( + $operation, + false, + false, + 'not_applied', + $errorCode, + '对象副本终态与失败回执冲突' + ); + return; + } + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + self::settleFailed( + $operation, + false, + $safeToResubmit, + 'not_applied', + $errorCode, + $now + ); + $replica->state = 'degraded'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = $errorCode; + $replica->updated_at = $now; + $replica->save(); + self::projectArtifactLocked($artifact, $replicas, $now); + }); + } + + /** Re-open the same copy intent after a definite no-effect receipt. */ + public static function rescheduleReplicaNotApplied( + string $operationId, + string $leaseToken, + string $errorCode, + int $now, + int $delaySeconds = 60 + ): void { + $errorCode = self::errorCode($errorCode); + if ($delaySeconds < 5 || $delaySeconds > 3600) { + throw new \InvalidArgumentException('Invalid replica retry delay'); + } + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $errorCode, + $now, + $delaySeconds + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + if (!in_array((string) $operation->phase, + ['dispatching', 'awaiting_receipt', 'reconciling'], true)) { + throw new CloudError( + '对象副本不在可安全重排的阶段', + 409 + ); + } + $operation->phase = 'accepted'; + $operation->outcome = null; + $operation->effect_resolution = 'not_applicable'; + $operation->effect_may_have_applied = null; + $operation->safe_to_resubmit = null; + $operation->lease_token = null; + $operation->lease_until = 0; + $operation->available_at = $now + $delaySeconds; + $operation->next_check_at = 0; + $operation->error_code = $errorCode; + $operation->result_json = null; + $operation->terminal_at = null; + $operation->updated_at = $now; + $operation->save(); + $replica->state = 'reserved'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = $errorCode; + $replica->updated_at = $now; + $replica->save(); + self::projectArtifactLocked($artifact, $replicas, $now); + }); + } + + /** Terminal mismatch after a target object is proven to exist. */ + public static function failReplicaAppliedMismatch( + string $operationId, + string $leaseToken, + string $errorCode, + int $now + ): void { + $errorCode = self::errorCode($errorCode); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $errorCode, + $now + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + if ((string) $operation->phase === 'terminal') { + self::assertTerminalFailure( + $operation, + true, + false, + 'applied', + $errorCode, + '对象副本终态与远端效果回执冲突' + ); + return; + } + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + self::settleFailed( + $operation, + true, + false, + 'applied', + $errorCode, + $now + ); + $replica->state = 'degraded'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = $errorCode; + $replica->updated_at = $now; + $replica->save(); + self::projectArtifactLocked($artifact, $replicas, $now); + }); + } + + /** Re-open only after read-only proof of no object and no upload session. */ + public static function rescheduleReplicaAfterProof( + string $operationId, + string $leaseToken, + array $evidence, + int $now, + int $delaySeconds = 60 + ): void { + if ($delaySeconds < 5 || $delaySeconds > 3600) { + throw new \InvalidArgumentException('Invalid replica retry delay'); + } + $evidence = self::sanitizeCopyMetadata($evidence); + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $evidence, + $now, + $delaySeconds + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + if ((string) $operation->phase !== 'reconciling') { + throw new CloudError('对象副本尚未完成效果核对', 409); + } + $stored = self::copyMetadata($operation->result_json); + $sameSession = isset($evidence['upload_id'], $stored['upload_id']) + && hash_equals( + (string) $stored['upload_id'], + (string) $evidence['upload_id'] + ); + $noSession = !isset($evidence['upload_id']) + && !isset($stored['upload_id']); + if (($evidence['multipart_absence_confirmations'] ?? 0) < 2 + || ($stored['multipart_absence_confirmations'] ?? 0) < 1 + || (!$sameSession && !$noSession)) { + throw new CloudError('对象副本缺少可安全重排的核对证据', 409); + } + $operation->phase = 'accepted'; + $operation->effect_resolution = 'not_applicable'; + $operation->lease_token = null; + $operation->lease_until = 0; + $operation->available_at = $now + $delaySeconds; + $operation->next_check_at = 0; + $operation->error_code = ''; + $operation->result_json = null; + $operation->updated_at = $now; + $operation->save(); + $replica->state = 'reserved'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = ''; + $replica->updated_at = $now; + $replica->save(); + }); + } + + /** Return pre-side-effect work to the same pinned operation. */ + public static function deferReplica( + string $operationId, + string $leaseToken, + string $errorCode, + int $now, + int $delaySeconds + ): void { + $errorCode = self::errorCode($errorCode); + if ($delaySeconds < 5 || $delaySeconds > 3600) { + throw new \InvalidArgumentException('Invalid replica delay'); + } + $connection = (new CloudStorageOperation())->getConnection(); + $connection->transaction(static function () use ( + $operationId, + $leaseToken, + $errorCode, + $now, + $delaySeconds + ): void { + $operation = self::copyOperationLocked($operationId); + [$artifact, $replicas] = self::artifactContextLocked($operation); + $replica = self::operationReplica($operation, $replicas); + self::assertLeaseToken($operation, $leaseToken, $now); + if (self::stopCopyIfArtifactNotCopyable( + $operation, + $artifact, + $replica, + $now + )) { + return; + } + if ((string) $operation->phase !== 'dispatching') { + throw new CloudError('对象副本复制已发生远端效果,不能延后重放', 409); + } + $operation->phase = 'accepted'; + $operation->effect_resolution = 'not_applicable'; + $operation->lease_token = null; + $operation->lease_until = 0; + $operation->available_at = $now + $delaySeconds; + $operation->next_check_at = 0; + $operation->error_code = $errorCode; + $operation->updated_at = $now; + $operation->save(); + $replica->state = 'reserved'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = $errorCode; + $replica->updated_at = $now; + $replica->save(); + }); + } + + private static function primaryOperationLocked( + string $operationId + ): CloudStorageOperation { + $operation = CloudStorageOperation::query() + ->where('operation_id', $operationId) + ->lockForUpdate()->first(); + if (!$operation instanceof CloudStorageOperation + || (string) $operation->kind !== 'publish') { + throw new CloudError('对象存储发布操作不存在', 404); + } + return $operation; + } + + private static function copyOperationLocked( + string $operationId + ): CloudStorageOperation { + self::assertOperationId($operationId); + $operation = CloudStorageOperation::query() + ->where('operation_id', $operationId) + ->lockForUpdate()->first(); + if (!$operation instanceof CloudStorageOperation + || (string) $operation->kind !== 'copy') { + throw new CloudError('对象副本复制操作不存在', 404); + } + return $operation; + } + + /** @return array */ + private static function copyOperationsLocked(int $artifactId): array + { + return CloudStorageOperation::query() + ->where('artifact_id', $artifactId) + ->where('kind', 'copy') + ->orderBy('id') + ->lockForUpdate() + ->get() + ->all(); + } + + /** + * Every mutation uses the same lock order: operation, artifact, replicas + * by id, then publication. Callers that also need sibling operations lock + * those immediately after their primary operation and before this method. + * + * @return array{0:CloudStorageArtifact,1:array} + */ + private static function artifactContextLocked( + CloudStorageOperation $operation + ): array { + $artifact = CloudStorageArtifact::query() + ->whereKey((int) $operation->artifact_id) + ->lockForUpdate() + ->firstOrFail(); + $replicas = CloudStorageReplica::query() + ->where('artifact_id', $artifact->id) + ->orderBy('id') + ->lockForUpdate() + ->get() + ->all(); + return [$artifact, $replicas]; + } + + /** @param array $replicas */ + private static function operationReplica( + CloudStorageOperation $operation, + array $replicas + ): CloudStorageReplica { + foreach ($replicas as $replica) { + if ((int) $replica->id === (int) $operation->replica_id) { + return $replica; + } + } + throw new CloudError('对象副本记录不存在', 409); + } + + /** @param array $replicas */ + private static function backendReplica( + array $replicas, + int $backendId + ): CloudStorageReplica { + foreach ($replicas as $replica) { + if ((int) $replica->backend_id === $backendId) { + return $replica; + } + } + throw new CloudError('对象源副本记录不存在', 409); + } + + private static function assertSettledReplicaIdentity( + CloudStorageArtifact $artifact, + CloudStorageReplica $replica, + int $size, + string $sha256, + string $etag, + string $versionId, + string $message + ): void { + if ($size !== (int) $artifact->size_bytes + || $size !== (int) $replica->size_bytes + || !hash_equals((string) $artifact->sha256, $sha256) + || !hash_equals((string) $replica->sha256, $sha256) + || !hash_equals((string) $replica->object_etag, $etag) + || !hash_equals( + (string) $replica->object_version_id, + $versionId + )) { + throw new CloudError($message, 409); + } + } + + private static function stopCopyIfArtifactNotCopyable( + CloudStorageOperation $operation, + CloudStorageArtifact $artifact, + CloudStorageReplica $replica, + int $now + ): bool { + if (!in_array((string) $artifact->state, + ['retiring', 'delete_attention', 'deleted'], true)) { + return false; + } + self::settleFailed( + $operation, + false, + false, + 'not_applied', + 'artifact_not_copyable', + $now + ); + if ((string) $artifact->state === 'retiring' + && in_array((string) $replica->state, + ['reserved', 'copying'], true)) { + $replica->state = 'degraded'; + $replica->lease_token = null; + $replica->lease_until = 0; + $replica->error_code = 'artifact_not_copyable'; + $replica->updated_at = $now; + $replica->save(); + } + return true; + } + + private static function assertTerminalFailure( + CloudStorageOperation $operation, + bool $effectMayHaveApplied, + bool $safeToResubmit, + string $resolution, + string $errorCode, + string $message + ): void { + if ((string) $operation->phase !== 'terminal' + || (string) $operation->outcome !== 'failed' + || (string) $operation->effect_resolution !== $resolution + || (bool) $operation->effect_may_have_applied + !== $effectMayHaveApplied + || (bool) $operation->safe_to_resubmit !== $safeToResubmit + || !hash_equals((string) $operation->error_code, $errorCode)) { + throw new CloudError($message, 409); + } + } + + private static function assertLeaseToken( + CloudStorageOperation $operation, + string $leaseToken, + int $now + ): void { + if (preg_match('/^[a-f0-9]{32}$/D', $leaseToken) !== 1 + || !is_string($operation->lease_token) + || !hash_equals((string) $operation->lease_token, $leaseToken) + || (int) $operation->lease_until <= $now) { + throw new CloudError('对象副本复制租约已经失效', 409); + } + } + + /** @return array */ + private static function copyMetadata($json): array + { + if (!is_string($json) || $json === '') { + return []; + } + try { + $value = json_decode($json, true, 16, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + return []; + } + return is_array($value) ? self::sanitizeCopyMetadata($value) : []; + } + + /** @return array */ + private static function sanitizeCopyMetadata(array $metadata): array + { + CloudInput::only($metadata, [ + 'upload_id', 'part_size_bytes', 'part_count', + 'maximum_size_bytes', 'absence_confirmations', + 'multipart_absence_confirmations', + 'multipart_presence_confirmations', + 'multipart_attention_confirmations', + 'multipart_attention_error_code', 'initiated_at', + ]); + if ($metadata === []) { + return []; + } + $uploadId = $metadata['upload_id'] ?? null; + $result = []; + if ($uploadId !== null) { + if (!is_string($uploadId) || $uploadId === '' + || strlen($uploadId) > 1024 + || preg_match('/[\x00-\x1f\x7f]/', $uploadId) === 1) { + throw new CloudError('对象副本分段上传身份无效', 502); + } + $result['upload_id'] = $uploadId; + foreach (['part_size_bytes', 'part_count', + 'maximum_size_bytes'] as $key) { + $value = $metadata[$key] ?? null; + if (!is_int($value) || $value < 1) { + throw new CloudError('对象副本分段上传几何无效', 502); + } + $result[$key] = $value; + } + if (array_key_exists('initiated_at', $metadata)) { + $initiatedAt = $metadata['initiated_at']; + if (!is_int($initiatedAt) || $initiatedAt < 1) { + throw new CloudError('对象副本分段上传时间无效', 502); + } + $result['initiated_at'] = $initiatedAt; + } + } elseif (array_intersect_key($metadata, array_flip([ + 'part_size_bytes', 'part_count', 'maximum_size_bytes', + 'initiated_at', + ])) !== []) { + throw new CloudError('对象副本分段上传身份无效', 502); + } + $absence = $metadata['absence_confirmations'] ?? 0; + if (!is_int($absence) || $absence < 0 || $absence > 2) { + throw new CloudError('对象副本核对次数无效', 502); + } + $result['absence_confirmations'] = $absence; + $multipartAbsence = + $metadata['multipart_absence_confirmations'] ?? 0; + if (!is_int($multipartAbsence) + || $multipartAbsence < 0 + || $multipartAbsence > 2) { + throw new CloudError('对象副本分段会话核对次数无效', 502); + } + $result['multipart_absence_confirmations'] = $multipartAbsence; + $multipartPresence = + $metadata['multipart_presence_confirmations'] ?? 0; + if (!is_int($multipartPresence) + || $multipartPresence < 0 + || $multipartPresence > 2) { + throw new CloudError('对象副本分段会话稳定次数无效', 502); + } + $result['multipart_presence_confirmations'] = $multipartPresence; + $multipartAttention = + $metadata['multipart_attention_confirmations'] ?? 0; + if (!is_int($multipartAttention) + || $multipartAttention < 0 + || $multipartAttention > 2) { + throw new CloudError('对象副本人工核对次数无效', 502); + } + $result['multipart_attention_confirmations'] = $multipartAttention; + if (array_key_exists('multipart_attention_error_code', $metadata)) { + $result['multipart_attention_error_code'] = + self::replicaAttentionError( + $metadata['multipart_attention_error_code'] + ); + } + return $result; + } + + private static function replicaAttentionError($errorCode): string + { + if (!is_string($errorCode) + || !in_array($errorCode, self::REPLICA_ATTENTION_ERRORS, true)) { + throw new CloudError('对象副本人工核对原因无效', 409); + } + return $errorCode; + } + + private static function projectArtifactLocked( + CloudStorageArtifact $artifact, + array $replicas, + int $now + ): void { + $projection = CloudStorageDurabilityPolicy::project( + self::artifactData($artifact), + array_map( + static fn (CloudStorageReplica $replica): array => + self::replicaData($replica), + $replicas + ) + ); + $artifact->state = $projection['state']; + if ($projection['can_read']) { + $artifact->verified_at = $now; + } + $artifact->updated_at = $now; + $artifact->save(); + + $publication = CloudStoragePublication::query() + ->where('artifact_id', $artifact->id) + ->lockForUpdate()->first(); + if ($publication instanceof CloudStoragePublication + && !in_array((string) $publication->state, + ['finalizing', 'completed', 'failed', 'retired'], true)) { + if ($projection['can_read']) { + $publication->state = 'ready_to_finalize'; + $publication->available_at = $now; + if ($publication->coverage_ready_at === null) { + $publication->coverage_ready_at = $now; + } + } else { + $publication->state = 'waiting_protection'; + $publication->available_at = 0; + } + $publication->updated_at = $now; + $publication->save(); + } + } + + /** @return array */ + private static function artifactData(CloudStorageArtifact $artifact): array + { + return [ + 'id' => (int) $artifact->id, + 'state' => (string) $artifact->state, + 'size_bytes' => (int) $artifact->size_bytes, + 'sha256' => (string) $artifact->sha256, + 'desired_copies' => (int) $artifact->desired_copies, + 'required_copies' => (int) $artifact->required_copies, + ]; + } + + /** @return array */ + private static function replicaData(CloudStorageReplica $replica): array + { + return [ + 'id' => (int) $replica->id, + 'backend_id' => (int) $replica->backend_id, + 'role' => (string) $replica->role, + 'state' => (string) $replica->state, + 'size_bytes' => (int) $replica->size_bytes, + 'sha256' => (string) $replica->sha256, + 'verified_at' => (int) $replica->verified_at, + ]; + } + + private static function settleSucceeded( + CloudStorageOperation $operation, + array $result, + int $now + ): void { + $operation->phase = 'terminal'; + $operation->outcome = 'succeeded'; + $operation->effect_resolution = 'applied'; + $operation->effect_may_have_applied = 0; + $operation->safe_to_resubmit = 0; + $operation->lease_token = null; + $operation->lease_until = 0; + $operation->error_code = ''; + $operation->result_json = json_encode( + $result, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ); + $operation->terminal_at = $now; + $operation->updated_at = $now; + $operation->save(); + } + + private static function settleFailed( + CloudStorageOperation $operation, + bool $effectMayHaveApplied, + bool $safeToResubmit, + string $resolution, + string $errorCode, + int $now + ): void { + $operation->phase = 'terminal'; + $operation->outcome = 'failed'; + $operation->effect_resolution = $resolution; + $operation->effect_may_have_applied = $effectMayHaveApplied ? 1 : 0; + $operation->safe_to_resubmit = $safeToResubmit ? 1 : 0; + $operation->lease_token = null; + $operation->lease_until = 0; + $operation->error_code = $errorCode; + $operation->terminal_at = $now; + $operation->updated_at = $now; + $operation->save(); + } + + private static function initializeOperation( + CloudStorageOperation $operation, + int $now + ): void { + $operation->phase = 'accepted'; + $operation->outcome = null; + $operation->effect_resolution = 'not_applicable'; + $operation->effect_may_have_applied = null; + $operation->safe_to_resubmit = null; + $operation->attempts = 0; + $operation->lease_token = null; + $operation->lease_until = 0; + $operation->available_at = $now; + $operation->next_check_at = 0; + $operation->error_code = ''; + $operation->result_json = null; + $operation->terminal_at = null; + $operation->created_at = $now; + $operation->updated_at = $now; + } + + private static function objectKey(string $prefix, string $suffix): string + { + $prefix = trim($prefix, '/'); + $key = ($prefix === '' ? '' : $prefix . '/') . $suffix; + if (strlen($key) > 512) { + throw new CloudError('对象存储制品路径过长', 422); + } + return $key; + } + + private static function objectSuffix(string $value): string + { + $value = trim($value, '/'); + if ($value === '' || strlen($value) > 512 + || preg_match('/^[A-Za-z0-9][A-Za-z0-9._\/-]*$/D', $value) !== 1 + || str_contains($value, '//')) { + throw new CloudError('对象存储制品路径无效', 422); + } + foreach (explode('/', $value) as $segment) { + if ($segment === '.' || $segment === '..') { + throw new CloudError('对象存储制品路径无效', 422); + } + } + return $value; + } + + private static function copyIdempotencyKey( + string $requestKey, + int $backendId + ): string { + return 'storage-copy-' . substr(hash( + 'sha256', + $requestKey . '|' . $backendId + ), 0, 48); + } + + /** @return array{backup_id:?int,template_import_intent_id:?string,rescue_template_id:?string} */ + private static function owner(string $kind, array $owner): array + { + CloudInput::only($owner, [ + 'backup_id', 'template_import_intent_id', 'rescue_template_id', + ]); + $normalized = [ + 'backup_id' => null, + 'template_import_intent_id' => null, + 'rescue_template_id' => null, + ]; + if ($kind === 'backup') { + $value = filter_var($owner['backup_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + if ($value === false) { + throw new CloudError('备份对象存储发布归属无效', 422); + } + $normalized['backup_id'] = (int) $value; + } elseif ($kind === 'template') { + $value = $owner['template_import_intent_id'] ?? null; + if (!is_string($value) + || preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) { + throw new CloudError('云模板对象存储发布归属无效', 422); + } + $normalized['template_import_intent_id'] = $value; + } elseif ($kind === 'rescue') { + $value = $owner['rescue_template_id'] ?? null; + if (!is_string($value) + || preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) { + throw new CloudError('救援镜像对象存储发布归属无效', 422); + } + $normalized['rescue_template_id'] = $value; + } else { + throw new CloudError('对象存储制品类型无效', 422); + } + $provided = array_filter($owner, + static fn ($value): bool => $value !== null && $value !== ''); + if (count($provided) !== 1) { + throw new CloudError('对象存储发布必须且只能绑定一个归属', 422); + } + return $normalized; + } + + private static function assertExistingOwner( + CloudStorageOperation $operation, + array $owner + ): void { + $publication = CloudStoragePublication::query() + ->where('artifact_id', $operation->artifact_id) + ->lockForUpdate()->first(); + if (!$publication instanceof CloudStoragePublication + || (int) ($publication->backup_id ?? 0) + !== (int) ($owner['backup_id'] ?? 0) + || (string) ($publication->template_import_intent_id ?? '') + !== (string) ($owner['template_import_intent_id'] ?? '') + || (string) ($publication->rescue_template_id ?? '') + !== (string) ($owner['rescue_template_id'] ?? '')) { + throw new CloudError('对象存储发布幂等键归属不一致', 409); + } + } + + private static function assertObjectIdentity( + int $sizeBytes, + string $sha256 + ): void { + if ($sizeBytes < 1 + || preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1) { + throw new CloudError('对象存储制品身份无效', 422); + } + } + + private static function assertRequestIdentity( + string $requestKey, + string $fingerprint + ): void { + if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $requestKey) !== 1 + || preg_match('/^[a-f0-9]{64}$/D', $fingerprint) !== 1) { + throw new CloudError('对象存储发布请求身份无效', 422); + } + } + + private static function assertOperationId(string $operationId): void + { + if (preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) { + throw new CloudError('对象存储操作身份无效', 422); + } + } + + private static function assertEffectResolution(string $value): void + { + if (!in_array($value, ['unknown', 'not_applied'], true)) { + throw new CloudError('对象存储操作效果状态无效', 422); + } + } + + private static function errorCode(string $value): string + { + if (preg_match('/^[a-z][a-z0-9_]{0,95}$/D', $value) !== 1) { + return 'storage_operation_failed'; + } + return $value; + } + + private static function positiveInt($value): int + { + if (!is_int($value) || $value < 1) { + throw new CloudError('对象存储返回的对象大小无效', 502); + } + return $value; + } + + private static function providerIdentity($value, int $maximum): string + { + if (!is_string($value) || $value === '' || strlen($value) > $maximum + || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) { + throw new CloudError('对象存储返回的对象身份无效', 502); + } + return $value; + } + + private static function providerVersionIdentity( + $value, + int $maximum + ): string { + if ($value === null) { + $value = ''; + } + if (!is_string($value) || strlen($value) > $maximum + || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) { + throw new CloudError('对象存储返回的版本身份无效', 502); + } + return $value; + } +} diff --git a/web/app/Services/Cloud/CloudStorageReplicaAttentionService.php b/web/app/Services/Cloud/CloudStorageReplicaAttentionService.php new file mode 100644 index 00000000..4b37cab3 --- /dev/null +++ b/web/app/Services/Cloud/CloudStorageReplicaAttentionService.php @@ -0,0 +1,150 @@ + */ + 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 => '分段上传身份需要人工核对', + }; + } +} diff --git a/web/app/Services/Cloud/CloudStorageReplicaHelper.php b/web/app/Services/Cloud/CloudStorageReplicaHelper.php new file mode 100644 index 00000000..1b046ce7 --- /dev/null +++ b/web/app/Services/Cloud/CloudStorageReplicaHelper.php @@ -0,0 +1,355 @@ +):array */ + private readonly ?\Closure $testInvoker; + + /** @param null|callable(array):array $testInvoker */ + public function __construct( + private readonly ?string $binaryPath = null, + ?callable $testInvoker = null + ) { + $this->testInvoker = $testInvoker === null + ? null : \Closure::fromCallable($testInvoker); + } + + /** @param array $request @return array */ + 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 $receipt @return array */ + 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 */ + 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, + ]; + } +} diff --git a/web/app/Services/Cloud/CloudStorageReplicaWorkerService.php b/web/app/Services/Cloud/CloudStorageReplicaWorkerService.php new file mode 100644 index 00000000..ac5c1084 --- /dev/null +++ b/web/app/Services/Cloud/CloudStorageReplicaWorkerService.php @@ -0,0 +1,660 @@ + */ + private readonly \Closure $runtimeResolver; + + /** @var \Closure():int */ + private readonly \Closure $clock; + + /** @var list */ + private array $errors = []; + + /** + * @param null|callable(int,bool):array $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 */ + public function observationErrors(): array + { + return $this->errors; + } + + /** @param array $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 $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 $work + * @param array $runtime + * @param array $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 $work + * @param array $receipt + * @param array $metadata + * @param array|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 $work @param array $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 $work + * @param array $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 $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 $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 $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 $work + * @param array $sourceRuntime + * @param array $targetRuntime + * @param array $plan + * @param array $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 $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 $plan @return array */ + 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'], + ]; + } +} diff --git a/web/config/routes.php b/web/config/routes.php index f93ec542..9781ac61 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -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'); diff --git a/web/public/cloud/admin-object-storage.js b/web/public/cloud/admin-object-storage.js index 7b1e9ef8..5eff4758 100644 --- a/web/public/cloud/admin-object-storage.js +++ b/web/public/cloud/admin-object-storage.js @@ -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(); diff --git a/web/resources/views/venix/admin/object_storage.tpl b/web/resources/views/venix/admin/object_storage.tpl index be79a53f..ff66f1f8 100644 --- a/web/resources/views/venix/admin/object_storage.tpl +++ b/web/resources/views/venix/admin/object_storage.tpl @@ -19,7 +19,7 @@ @@ -58,6 +58,19 @@