fix(vpc): exclude occupied instances from member choices

venix
admin 1 month ago
parent 5783ae618f
commit 09801dc6e8

@ -1,5 +1,27 @@
# 本版验证记录
## 2026-10-12:VPC 添加实例候选归属修复
- 根因是用户页面仅排除当前 VPC 的成员,实例列表未携带其他 VPC 的归属。
后端原有全局成员唯一约束与加入校验仍会拒绝重复加入;本次修复可选列表,
没有开放一台实例同时加入多个 VPC。
- bootstrap 批量核对成员、私网租约及用户自己的 VPC:已占用、清理中及
归属无法核实的实例均禁用,并说明原因;查询失败不沿用旧的可加入结果,
不泄露其他用户的 VPC 名称。切换、创建、成员修改和轮询会刷新候选,
10 秒读取超时释放页面等待状态,过期响应不能覆盖新状态或清除未保存草稿。
- 兼容旧版本已完成删除却残留成员/租约的记录:在原 VPC 显示“核对 / 重试”,
仅显式核对且没有待处理操作时,复用原有严格删除凭据校验释放残留。
普通 GET 不清理记录;无凭据、有路由引用或存在未决操作时仍拒绝释放。
- 两套 Node 行为回归 `CloudVpcUserPageBehaviorTest.mjs`、
`CloudVpcMemberChoicesTest.mjs` 通过;PHP 8.5 WASM + SQLite/Eloquent 环境中
`CloudVpcPageMembershipTest.php`、`CloudVpcMemberCandidateRecoveryTest.php`、
`CloudVpcMutationAdmissionTest.php`、`CloudVpcFailedReconcileTest.php` 和
`CloudVpcUserPageContractTest.php` 通过。复用测试夹具执行的成员/私网 IP
回收合同也通过,不将重复执行统计为新增用例。
- 本次未更改数据库结构、Engine、宿主网络或 ACL 策略;前端资源版本提升为
`2026101203`。验证范围为源码回归,未部署线上面板,也未执行真实浏览器或
MariaDB 验收;此前双宿主通信验收记录不等同于本次页面变更的线上验收。
## 2026-10-12:VPC 邻居持久化与双宿主互通
- 真机根因:无 IPv4 地址的私网 bridge 发出的 ARP 使用宿主公网源地址,

@ -59,35 +59,114 @@ final class CloudVpcPageService
return [];
}
try {
return CloudInstance::query()
$instances = CloudInstance::query()
->where('user_id', $userId)
->where('status', 'active')
->orderBy('name')->orderBy('id')->limit(200)->get([
'id', 'name', 'spec_json', 'service_status', 'expires_at',
])->map(static function ($row): array {
$spec = json_decode((string) $row->spec_json, true);
$spec = is_array($spec) && !array_is_list($spec) ? $spec : [];
$regionId = filter_var($spec['region_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$region = trim((string) ($spec['region'] ?? $spec['location'] ?? ''));
// A future expiry does not make a blocked/suspended
// service eligible for a private-network attachment.
// Keep this projection identical to CloudInstance's
// serviceAvailable() lifecycle gate.
$available = (string) $row->service_status === 'exempt'
|| ((string) $row->service_status === 'active'
&& $row->expires_at !== null
&& (int) $row->expires_at > time());
return [
'id' => (int) $row->id,
'name' => (string) $row->name,
'region_id' => $regionId === false ? null : (int) $regionId,
'region' => $region,
'service_available' => $available,
];
})->all();
]);
$attachments = self::attachments(
$instances->pluck('id')->map(static fn ($id): int => (int) $id)->all(),
$userId
);
return $instances->map(static function ($row) use ($attachments): array {
$spec = json_decode((string) $row->spec_json, true);
$spec = is_array($spec) && !array_is_list($spec) ? $spec : [];
$regionId = filter_var($spec['region_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$region = trim((string) ($spec['region'] ?? $spec['location'] ?? ''));
// A future expiry does not make a blocked/suspended
// service eligible for a private-network attachment.
// Keep this projection identical to CloudInstance's
// serviceAvailable() lifecycle gate.
$available = (string) $row->service_status === 'exempt'
|| ((string) $row->service_status === 'active'
&& $row->expires_at !== null
&& (int) $row->expires_at > time());
return [
'id' => (int) $row->id,
'name' => (string) $row->name,
'region_id' => $regionId === false ? null : (int) $regionId,
'region' => $region,
'service_available' => $available,
'vpc_attachment' => $attachments[(int) $row->id],
];
})->all();
} catch (\Throwable) {
return [];
}
}
/**
* Membership and address tombstones reserve the instance until the normal
* reconciliation path physically releases them. This is a display hint;
* attachMember still owns authoritative locking and admission checks.
*/
private static function attachments(array $instanceIds, int $userId): array
{
$unavailable = ['state' => 'unavailable', 'vpc_key' => null, 'vpc_name' => null];
$result = array_fill_keys($instanceIds, $unavailable);
if ($instanceIds === []) {
return $result;
}
try {
$connection = (new CloudInstance())->getConnection();
$schema = $connection->getSchemaBuilder();
foreach (['cloud_vpc_members', 'cloud_vpc_private_ips', 'cloud_vpcs'] as $table) {
if (!$schema->hasTable($table)) {
return $result;
}
}
// Only these owner-scoped instance IDs enter the ledger queries.
// Read every state: a deleted row still owns the global unique key.
$members = $connection->table('cloud_vpc_members')
->whereIn('instance_id', $instanceIds)
->get(['id', 'instance_id', 'vpc_id', 'state']);
$leases = $connection->table('cloud_vpc_private_ips')
->whereIn('instance_id', $instanceIds)
->get(['instance_id', 'member_id', 'vpc_id']);
$vpcs = $connection->table('cloud_vpcs')->where('user_id', $userId)
->whereIn('id', $members->pluck('vpc_id')->unique()->all())
->get(['id', 'vpc_key', 'name', 'state'])->keyBy('id');
$membersByInstance = $members->groupBy('instance_id');
$leasesByInstance = $leases->groupBy('instance_id');
foreach ($instanceIds as $instanceId) {
$instanceMembers = $membersByInstance->get($instanceId);
$instanceLeases = $leasesByInstance->get($instanceId);
if ($instanceMembers === null) {
if ($instanceLeases === null) {
$result[$instanceId]['state'] = 'available';
}
continue;
}
// Corrupt duplicate or foreign-owned membership must not
// become selectable or disclose another account's VPC name.
if ($instanceMembers->count() !== 1) {
continue;
}
$member = $instanceMembers->first();
$vpc = $vpcs->get((int) $member->vpc_id);
if ($vpc === null || !is_string($vpc->vpc_key) || $vpc->vpc_key === '') {
continue;
}
if ($instanceLeases !== null && $instanceLeases->contains(
static fn ($lease): bool => (int) $lease->member_id !== (int) $member->id
|| (int) $lease->vpc_id !== (int) $member->vpc_id
)) {
continue;
}
$cleanup = in_array((string) $member->state, ['deleting', 'deleted'], true)
|| in_array((string) $vpc->state, ['deleting', 'deleted'], true);
$result[$instanceId] = [
'state' => $cleanup ? 'cleanup_pending' : 'attached',
'vpc_key' => (string) $vpc->vpc_key,
'vpc_name' => (string) $vpc->name,
];
}
return $result;
} catch (\Throwable) {
// Unknown ownership is not proof that an instance is unoccupied.
return array_fill_keys($instanceIds, $unavailable);
}
}
}

@ -963,6 +963,14 @@ final class CloudVpcService
})
->orderByDesc('desired_revision')->lockForUpdate()->first();
if ($operation === null) {
// An explicit check can release legacy terminal identities
// using the same complete proof required by member reuse.
// GET and ordinary worker retries remain read-only here, and
// pending operations always retain their normal claim path.
if ($allowFailedRetry
&& self::releasePersistedDeletedMemberTombstonesLocked($locked) > 0) {
return null;
}
throw new CloudError('VPC 没有待核对的目标版本', 409);
}
// A newer mutation owns the VPC's desired state. A worker can

@ -375,7 +375,7 @@ function schedulePoll(delay = needsPolling() ? 8000 : 30000) {
state.pollTimer = window.setTimeout(async () => {
if (state.stopped || document.visibilityState === 'hidden') return;
if (state.busy) { schedulePoll(1500); return; }
await loadList(true);
await Promise.all([loadList(true), refreshBootstrap(true)]);
if (state.stopped || state.busy || document.visibilityState === 'hidden') {
if (!state.stopped) schedulePoll(1500);
return;
@ -433,7 +433,7 @@ function renderList() {
const reconcile = byId('vpc-list-reconcile');
const selectedStatus = rootStatus(selectedDocumentCurrent() ? state.selected.vpc : null);
const canReconcile = selectedDocumentCurrent()
&& !['active', 'awaiting_members'].includes(selectedStatus);
&& (!['active', 'awaiting_members'].includes(selectedStatus) || hasMemberCleanup());
reconcile.hidden = !canReconcile;
reconcile.disabled = !canReconcile || state.busy;
renderSummary();
@ -541,7 +541,8 @@ function renderDetail() {
addMember.dataset.vpcAction = 'add-member';
addMember.disabled = state.busy;
actions.append(addMember);
} else if (status !== 'active') {
}
if (!['active', 'awaiting_members'].includes(status) || hasMemberCleanup(doc)) {
reconcile = button('核对 / 重试', 'button button-primary small');
reconcile.dataset.vpcAction = 'reconcile';
reconcile.disabled = state.busy;
@ -595,41 +596,89 @@ function renderDetail() {
lockDeletingDetail(container, reconcile);
}
function renderMembers(doc) {
const card = section('成员与私网 IP', '平台自动分配私网 IP。首次加入请先完全关机,提交后点“核对 / 重试”写入配置,再启动实例等待来宾网络核验。', 'vpc-members');
const form = element('form', 'vpc-inline-form vpc-member-form'); form.dataset.vpcForm = 'member';
const instance = input('选择实例', '', 'select'); instance.control.name = 'instance_id'; instance.control.required = true;
instance.control.id = 'vpc-member-instance';
instance.wrapper.querySelector('label').htmlFor = instance.control.id;
function hasMemberCleanup(doc = state.selected) {
return Boolean(doc?.members?.some(item => childStatus(item.state) === 'deleted'));
}
function memberChoice(row, doc) {
const current = doc?.members?.find(item => Number(item.instance_id) === Number(row?.id));
const attachment = row?.vpc_attachment;
if (current && ['deleting', 'deleted'].includes(childStatus(current.state))) {
return { disabled: true, reason: '旧 VPC 私网仍在清理' };
}
if (attachment?.state === 'cleanup_pending') {
const name = String(attachment.vpc_name || '').trim();
return { disabled: true, reason: name
? `旧 VPC:${name} 仍在清理,请先核对` : '旧 VPC 私网仍在清理' };
}
if (current) return { disabled: true, reason: '已在当前 VPC' };
if (attachment?.state === 'attached') {
const name = String(attachment.vpc_name || '').trim();
return { disabled: true, reason: attachment.vpc_key === doc?.vpc?.vpc_key
? '已在当前 VPC' : (name ? `已加入 VPC:${name}` : '已加入其他 VPC') };
}
// Only an explicit, current server projection proves that both the member
// and its independent private-IP reservation have been released.
if (attachment?.state !== 'available') {
return { disabled: true, reason: '私网归属待核验,请刷新' };
}
if (row.service_available === false) return { disabled: true, reason: '服务当前不可用' };
const regionId = Number(row.region_id);
if (!Number.isInteger(regionId) || regionId <= 0) {
return { disabled: true, reason: '地区待核验,暂不可加入' };
}
return regionId === Number(doc?.vpc?.region_id)
? { disabled: false, reason: '' } : { disabled: true, reason: '地区不匹配' };
}
function populateMemberChoices(select, doc) {
const previous = select.value;
const placeholder = new Option('请选择同地区实例', '', true, true);
placeholder.disabled = true;
instance.control.append(placeholder);
const vpcRegionId = Number(doc.vpc.region_id || 0);
const attached = new Set(doc.members
.filter(item => childStatus(item.state) !== 'deleted')
.map(item => Number(item.instance_id)));
const eligible = [];
const unavailable = [];
for (const row of state.instances.filter(item => item.service_available !== false)) {
const rowRegionId = Number(row.region_id);
const regionVerified = Number.isInteger(rowRegionId) && rowRegionId > 0;
const sameRegion = regionVerified && rowRegionId === vpcRegionId;
const alreadyAttached = attached.has(Number(row.id));
const suffix = alreadyAttached ? ' · 已在当前 VPC'
: (!regionVerified ? ' · 地区待核验,暂不可加入'
: (!sameRegion ? ' · 地区不匹配' : ''));
const choice = memberChoice(row, doc);
const suffix = choice.reason ? ` · ${choice.reason}` : '';
const option = new Option(`${row.name} · ${safeText(row.region, '地区待核验')}${suffix}`, String(row.id));
option.dataset.regionId = row.region_id || '';
option.disabled = alreadyAttached || !sameRegion;
option.disabled = choice.disabled;
(option.disabled ? unavailable : eligible).push(option);
}
instance.control.append(...eligible, ...unavailable);
select.replaceChildren(placeholder, ...eligible, ...unavailable);
select.value = eligible.some(option => option.value === previous) ? previous : '';
return eligible.length;
}
function refreshMemberChoices() {
const select = byId('vpc-member-instance');
if (!select || !selectedDocumentCurrent()) return;
const count = populateMemberChoices(select, state.selected);
const save = document.querySelector('[data-vpc-member-submit]');
if (save) save.disabled = state.busy || selectedRootDeleting() || count === 0;
const hint = document.querySelector('[data-vpc-member-empty]');
if (hint) hint.hidden = count > 0;
}
function renderMembers(doc) {
const card = section('成员与私网 IP', '平台自动分配私网 IP。首次加入请先完全关机,提交后点“核对 / 重试”写入配置,再启动实例等待来宾网络核验。', 'vpc-members');
const form = element('form', 'vpc-inline-form vpc-member-form'); form.dataset.vpcForm = 'member';
const instance = input('选择实例', '', 'select'); instance.control.name = 'instance_id'; instance.control.required = true;
instance.control.id = 'vpc-member-instance';
instance.wrapper.querySelector('label').htmlFor = instance.control.id;
const eligibleCount = populateMemberChoices(instance.control, doc);
const save = button('加入 VPC', 'button button-primary small'); save.type = 'submit';
save.disabled = state.busy || eligible.length === 0;
save.dataset.vpcMemberSubmit = 'true';
save.disabled = state.busy || eligibleCount === 0;
form.append(instance.wrapper, save); card.append(form);
if (!eligible.length) {
const hint = element('p', 'vpc-member-empty-hint',
'当前没有可加入的同地区实例。已加入其他 VPC、私网仍在清理或归属待核验的实例暂不可加入。');
hint.dataset.vpcMemberEmpty = 'true';
hint.hidden = eligibleCount > 0;
card.append(hint);
if (hasMemberCleanup(doc)) {
card.append(element('p', 'vpc-member-empty-hint',
'当前没有可加入的同地区实例。实例地区缺失或不一致时会保持禁用,请先创建或核验同地区实例。'));
'存在尚未释放的旧成员记录。请点击“核对 / 重试”,完成清理核验后实例才可加入其他 VPC。'));
}
const list = element('div', 'vpc-row-list');
for (const row of doc.members.filter(item => childStatus(item.state) !== 'deleted')) {
@ -898,7 +947,8 @@ async function loadDetail(key, silent = false, allowDirty = false) {
state.detailController?.abort(); state.detailController = new AbortController();
try {
const payload = await api(`/api/v1/vpcs/${encodeURIComponent(key)}`, { signal: state.detailController.signal });
if (epoch !== state.detailEpoch || state.stopped || key !== state.selectedKey) return null;
if (epoch !== state.detailEpoch || state.stopped || key !== state.selectedKey
|| (state.detailDirty && !allowDirty)) return null;
state.selected = normalizeDocument(payload);
if (rootStatus(state.selected?.vpc) === 'deleted') {
finishVpcDeletion();
@ -930,7 +980,10 @@ async function selectVpc(key) {
detail.replaceChildren();
delete detail.dataset.vpcKey;
renderList();
await loadDetail(state.selectedKey);
const selectedKey = state.selectedKey;
await refreshBootstrap(true);
if (selectedKey !== state.selectedKey || state.stopped || state.busy) return;
await loadDetail(selectedKey);
schedulePoll(needsPolling() ? 5000 : 30000);
}
@ -970,6 +1023,7 @@ async function mutate(path, method, body, message) {
} catch (error) {
setError(error.message); setNotice(''); return null;
} finally {
await refreshBootstrap(true);
state.busy = false;
previousDisabled.forEach((disabled, node) => {
if (node.isConnected) node.disabled = disabled;
@ -977,6 +1031,7 @@ async function mutate(path, method, body, message) {
createRegionOptions(); renderList();
if (succeeded && state.selected) renderDetail();
else refreshRouteEditorState();
refreshMemberChoices();
schedulePoll(succeeded && needsPolling() ? 1500 : undefined);
}
}
@ -1027,6 +1082,7 @@ async function createVpc(event) {
await applyDocument(payload, 'VPC 已创建。请添加同地区实例以启用私网。');
} catch (error) { setFormError('vpc-create-error', error.message); }
finally {
await refreshBootstrap(true);
state.busy = false;
previousDisabled.forEach((disabled, node) => {
if (node.isConnected) node.disabled = disabled;
@ -1036,6 +1092,7 @@ async function createVpc(event) {
if (acknowledged) closeCreateModal(true, true);
createRegionOptions(); renderList();
if (acknowledged && state.selected) renderDetail();
refreshMemberChoices();
schedulePoll(needsPolling() ? 1500 : 30000);
}
}
@ -1047,6 +1104,13 @@ async function submitMember(form) {
setError('请选择一个已核验为同地区的实例。');
return;
}
const row = state.instances.find(item => Number(item.id) === instanceId);
const choice = memberChoice(row, state.selected);
if (choice.disabled) {
setError(choice.reason);
refreshMemberChoices();
return;
}
const body = { instance_id: instanceId, request_key: requestKey('member-add') };
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members`, 'POST', body,
'实例已加入 VPC 目标。请完全关机后点“核对 / 重试”写入配置,再启动实例等待来宾网络核验。');
@ -1108,7 +1172,7 @@ async function reconcile() {
if (!state.busy) setError('VPC 详情尚未读取完成,请等待刷新后再核对。');
return;
}
if (rootStatus(state.selected?.vpc) === 'awaiting_members') {
if (rootStatus(state.selected?.vpc) === 'awaiting_members' && !hasMemberCleanup()) {
setNotice('VPC 正在等待实例;添加同地区实例后会自动生成新的配置版本。', 'warning');
return;
}
@ -1224,14 +1288,20 @@ function readBootstrap() {
async function refreshBootstrap(silent = false) {
const epoch = ++state.bootstrapEpoch;
state.bootstrapController?.abort();
state.bootstrapController = new AbortController();
const controller = new AbortController();
state.bootstrapController = controller;
let timedOut = false;
const timeout = window.setTimeout(() => {
timedOut = true;
controller.abort();
}, 10000);
try {
const response = await fetch(`${location.pathname}${location.search}`, {
method: 'GET',
headers: new Headers({ Accept: 'text/html' }),
credentials: 'same-origin',
cache: 'no-store',
signal: state.bootstrapController.signal,
signal: controller.signal,
});
if (!response.ok) throw new Error(`页面候选数据刷新失败 (${response.status})`);
const html = await response.text();
@ -1245,12 +1315,21 @@ async function refreshBootstrap(silent = false) {
applyBootstrapPayload(payload, false);
createRegionOptions();
renderList();
if (state.selected) renderDetail();
// A candidate refresh must not rebuild an in-progress ACL/route editor.
refreshMemberChoices();
return null;
} catch (error) {
if (error?.name === 'AbortError') return null;
if (error?.name === 'AbortError' && !timedOut) return null;
if (epoch !== state.bootstrapEpoch || state.stopped) return null;
if (timedOut) error = new Error('实例归属读取超时,请稍后刷新。');
state.instances = state.instances.map(row => ({ ...row,
vpc_attachment: { state: 'unavailable', vpc_key: null, vpc_name: null },
}));
refreshMemberChoices();
if (!silent) setError(error.message);
return error;
} finally {
clearTimeout(timeout);
}
}

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026101202' scope='global'}
{assign var=venix_asset_version value='2026101203' scope='global'}

@ -0,0 +1,162 @@
<?php
namespace App\Services\Cloud {
// Reconciliation in this suite must settle from durable local evidence;
// fail immediately if it unexpectedly reaches the private HTTP boundary.
final class CloudEngineClient
{
public static int $requests = 0;
public function __construct(...$arguments)
{
}
public function vpc(...$arguments): array
{
self::$requests++;
throw new \RuntimeException('Candidate recovery must not contact the engine');
}
}
}
namespace {
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudVpcPageService;
use App\Services\Cloud\CloudVpcService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
require __DIR__ . '/CloudVpcMemberReuseTest.php';
if (!isset($capsule)) {
return;
}
$schema->table('cloud_instances', static function (Blueprint $table): void {
$table->text('spec_json')->default('{}');
});
$seedRecovery = static function (int $id, string $memberState = 'deleted') use (
$seedVpc, $seedInstance, $seedPair
): array {
$octet = $id - 900;
$vpc = $seedVpc($id, '10.98.' . $octet . '.0/24',
'10.98.' . $octet . '.0/24', 10, 'deleted', 'active');
$instanceId = $id * 100;
$memberId = $id * 1000;
$privateId = $memberId + 1;
$seedInstance($instanceId, 10);
Capsule::table('cloud_instances')->where('id', $instanceId)->update([
'spec_json' => json_encode(['region_id' => 1, 'region' => 'Test Region']),
]);
$seedPair($memberId, $privateId, $vpc, $instanceId, 10,
'10.98.' . $octet . '.1', $memberState);
return $vpc + [
'instance_id' => $instanceId, 'member_id' => $memberId,
'private_id' => $privateId, 'private_ip' => '10.98.' . $octet . '.1',
];
};
$attachment = static function (array $vpc) use ($actor, $assert): array {
$rows = array_column(CloudVpcPageService::bootstrap($actor)['instances'], null, 'id');
$assert(isset($rows[$vpc['instance_id']]), 'Recovery instance is missing from the page bootstrap.');
return $rows[$vpc['instance_id']]['vpc_attachment'];
};
$assertRetained = static function (array $vpc) use ($assert, $attachment): void {
$assert(Capsule::table('cloud_vpc_members')->where('id', $vpc['member_id'])->count() === 1
&& Capsule::table('cloud_vpc_private_ips')->where('id', $vpc['private_id'])->count() === 1
&& $attachment($vpc)['state'] === 'cleanup_pending',
'An unproven or in-flight identity was released or became selectable.');
};
$recoverable = $seedRecovery(980);
$beforeRoot = (array) Capsule::table('cloud_vpcs')->where('id', 980)->first();
$beforeOperation = (array) Capsule::table('cloud_vpc_operations')
->where('operation_id', $recoverable['operation_id'])->first();
CloudVpcService::show($recoverable['vpc_key'], $actor);
$assertRetained($recoverable);
foreach ([false, true] as $allowDeferredRetry) {
$expectCloudError(static fn () => CloudVpcService::reconcile(
$recoverable['vpc_key'], $actor, $allowDeferredRetry
), 409);
$assertRetained($recoverable);
}
CloudVpcService::reconcile($recoverable['vpc_key'], $actor, true, true);
$assert(Capsule::table('cloud_vpc_members')->where('id', $recoverable['member_id'])->count() === 0
&& Capsule::table('cloud_vpc_private_ips')->where('id', $recoverable['private_id'])->count() === 0
&& $attachment($recoverable) === ['state' => 'available', 'vpc_key' => null, 'vpc_name' => null]
&& (array) Capsule::table('cloud_vpcs')->where('id', 980)->first() === $beforeRoot
&& (array) Capsule::table('cloud_vpc_operations')
->where('operation_id', $recoverable['operation_id'])->first() === $beforeOperation
&& Capsule::table('cloud_vpc_operations')->where('vpc_id', 980)->count() === 1,
'Explicit proof-based recovery must release only the old pair and leave root/revision/operation audit unchanged.');
$expectCloudError(static fn () => CloudVpcService::reconcile(
$recoverable['vpc_key'], $actor, true, true
), 409);
// A later root marker does not erase exact historical absence evidence when
// there is no operation to claim; the existing proof verifier remains owner.
$advanced = $seedRecovery(981);
Capsule::table('cloud_vpcs')->where('id', 981)->update([
'desired_revision' => 2, 'desired_digest' => hash('sha256', 'recovery-newer-root'),
'state' => 'degraded', 'sync_state' => 'uncertain',
'last_operation_id' => $keyFor('recovery-newer-root', 981),
]);
CloudVpcService::reconcile($advanced['vpc_key'], $actor, true, true);
$assert($attachment($advanced)['state'] === 'available'
&& (int) Capsule::table('cloud_vpcs')->where('id', 981)->value('desired_revision') === 2
&& Capsule::table('cloud_vpc_operations')->where('vpc_id', 981)->count() === 1,
'Recovery either lost valid historical proof or created a replacement operation.');
$missingProof = $seedRecovery(982);
Capsule::table('cloud_vpc_operations')->where('operation_id', $missingProof['operation_id'])
->update(['observed_json' => null]);
$deleting = $seedRecovery(983, 'deleting');
$referenced = $seedRecovery(984);
$seedRoute(984000, $referenced, $referenced['member_id'], '10.99.0.1/32', $referenced['private_ip']);
$rootDeleting = $seedRecovery(985);
Capsule::table('cloud_vpcs')->where('id', 985)->update(['state' => 'deleting']);
foreach ([$missingProof, $deleting, $referenced, $rootDeleting] as $blocked) {
$expectCloudError(static fn () => CloudVpcService::reconcile(
$blocked['vpc_key'], $actor, true, true
), 409);
$assertRetained($blocked);
$assert(Capsule::table('cloud_vpc_operations')->where('vpc_id', $blocked['id'])->count() === 1,
'A refused cleanup must not create an operation.');
}
// A real pending target takes precedence even with a valid older removal
// proof. Its live lease returns the ordinary document without GC or replay.
$inFlight = $seedRecovery(986);
$historical = (array) Capsule::table('cloud_vpc_operations')
->where('operation_id', $inFlight['operation_id'])->first();
$pendingDocument = json_decode($historical['payload_json'], true);
unset($pendingDocument['operation_id'], $pendingDocument['desired_digest']);
$pendingDocument['desired_revision'] = 2;
$pendingDigest = hash('sha256', $canonicalJson($pendingDocument));
$pendingId = $keyFor('candidate-recovery-pending', 986);
$pendingDocument['operation_id'] = $pendingId;
$pendingDocument['desired_digest'] = $pendingDigest;
$pending = $historical;
unset($pending['id']);
$pending = array_replace($pending, [
'operation_id' => $pendingId, 'desired_revision' => 2,
'idempotency_key' => 'candidate-recovery-pending-986',
'request_hash' => hash('sha256', 'candidate-recovery-pending-986'),
'status' => 'running', 'payload_json' => json_encode($pendingDocument),
'observed_json' => null, 'finished_at' => null,
'lease_token' => str_repeat('a', 32), 'lease_until' => time() + 300,
]);
Capsule::table('cloud_vpc_operations')->insert($pending);
Capsule::table('cloud_vpcs')->where('id', 986)->update([
'desired_revision' => 2, 'desired_digest' => $pendingDigest,
'state' => 'degraded', 'sync_state' => 'uncertain', 'last_operation_id' => $pendingId,
]);
foreach (['queued', 'running', 'uncertain', 'waiting_observed'] as $status) {
Capsule::table('cloud_vpc_operations')->where('operation_id', $pendingId)->update(['status' => $status]);
CloudVpcService::reconcile($inFlight['vpc_key'], $actor, true, true);
$assertRetained($inFlight);
$assert(Capsule::table('cloud_vpc_operations')->where('operation_id', $pendingId)->value('status') === $status
&& Capsule::table('cloud_vpc_operations')->where('vpc_id', 986)->count() === 2,
'A live operation was bypassed, replayed or replaced by candidate cleanup.');
}
$assert(CloudEngineClient::$requests === 0, 'Candidate cleanup unexpectedly contacted the engine.');
echo "VPC member candidate recovery runtime passed.\n";
}

@ -0,0 +1,476 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const moduleSource = await readFile(new URL('../public/cloud/vpc.js', import.meta.url), 'utf8');
// Execute the shipped candidate and request code, without duplicating its rules.
// Only the unrelated full detail layout is replaced with an observation hook;
// list rendering, candidate rendering, requests and state transitions stay real.
const source = moduleSource
.replace(/^import[^\n]+\n/u, '')
.replace('export async function initialize()', 'async function initialize()')
+ `\n;globalThis.__memberChoices = {
state, memberChoice, populateMemberChoices, refreshMemberChoices,
submitMember, refreshBootstrap, mutate, selectVpc, createVpc,
hasMemberCleanup, reconcile, renderList,
observeDetailRender(callback) { renderDetail = callback; },
};\n`;
class Node {
constructor() {
this.children = [];
this.dataset = {};
this.attributes = new Map();
this.value = '';
this.textContent = '';
this.disabled = false;
this.hidden = false;
this.isConnected = true;
this.classList = { add() {}, remove() {} };
}
get options() { return this.children; }
append(...nodes) { this.children.push(...nodes); }
replaceChildren(...nodes) { this.children = nodes; }
setAttribute(name, value) { this.attributes.set(name, value); }
removeAttribute(name) { this.attributes.delete(name); }
querySelector() { return null; }
querySelectorAll() { return []; }
reset() {}
focus() {}
}
class OptionNode extends Node {
constructor(label, value, defaultSelected = false, selected = false) {
super();
Object.assign(this, { textContent: String(label), value: String(value), defaultSelected, selected });
}
}
const token = 'a'.repeat(64);
const region = { id: 7, name: 'Test region' };
const available = { state: 'available', vpc_key: null, vpc_name: null };
const attached = { state: 'attached', vpc_key: 'old-vpc', vpc_name: '原 VPC' };
const instance = (id = 11, attachment = available, overrides = {}) => ({
id, name: `vm-${id}`, region_id: 7, region: region.name,
service_available: true, vpc_attachment: attachment, ...overrides,
});
const doc = (key = 'new-vpc', members = []) => ({
vpc: { vpc_key: key, name: key, region_id: 7, cidr: '10.20.0.0/24',
state: 'active', usable: true, member_count: members.length },
members, routes: [], acl_rules: [], operations: [],
});
const bootstrap = instances => ({
user: { user_id: '9', csrf_token: token }, regions: [region], instances,
});
const response = payload => ({ status: 200, ok: true, async json() { return payload; } });
const pageResponse = instances => ({
ok: true, status: 200,
async text() { return `<script id="vpc-bootstrap">${JSON.stringify(bootstrap(instances))}</script>`; },
});
const deferred = () => {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
};
function harness() {
const ids = [
'vpc-member-instance', 'vpc-page-error', 'vpc-page-notice', 'vpc-detail-panel', 'vpc-detail',
'vpc-create-region', 'vpc-create-open', 'vpc-create-submit', 'vpc-create-availability',
'vpc-create-region-hint', 'vpc-create-close', 'vpc-create-cancel', 'vpc-create-error',
'vpc-create-form', 'vpc-create-modal', 'vpc-list', 'vpc-list-empty', 'vpc-list-reconcile',
'vpc-stat-total', 'vpc-stat-active', 'vpc-stat-attention', 'vpc-list-caption',
];
const nodes = Object.fromEntries(ids.map(id => [id, new Node()]));
const memberSubmit = new Node();
const emptyHint = new Node();
const aclDraft = new Node();
aclDraft.value = 'unsaved ACL draft';
const controls = [nodes['vpc-member-instance'], memberSubmit];
const requests = [];
const timers = new Map();
let timerSequence = 0;
let handler = () => { throw new Error('Unexpected request'); };
const context = {
document: {
visibilityState: 'visible', body: new Node(),
getElementById(id) { return nodes[id] || null; },
createElement() { return new Node(); },
querySelector(selector) {
return ({ '[data-vpc-member-submit]': memberSubmit,
'[data-vpc-member-empty]': emptyHint, '#vpc-acl-editor': aclDraft })[selector] || null;
},
querySelectorAll() { return controls; },
},
Option: OptionNode, HTMLElement: Node, Headers, AbortController,
DOMParser: class {
parseFromString(html, contentType) {
assert.equal(contentType, 'text/html');
const match = html.match(/<script id="vpc-bootstrap">([\s\S]*)<\/script>/u);
return { getElementById(id) {
assert.equal(id, 'vpc-bootstrap');
return match ? { textContent: match[1] } : null;
} };
}
},
location: { protocol: 'https:', hostname: 'panel.test', pathname: '/user/vpcs', search: '' },
crypto: { randomUUID() { return '12345678-1234-1234-1234-123456789abc'; } },
window: { setTimeout(callback, delay) {
const id = ++timerSequence;
timers.set(id, { callback, delay });
return id;
} },
clearTimeout(id) { timers.delete(id); }, confirm() { return true; }, toast() {},
async fetch(path, options = {}) {
const request = { path, ...options };
requests.push(request);
return handler(request);
},
};
vm.runInNewContext(source, context, { filename: 'vpc.js' });
const api = context.__memberChoices;
Object.assign(api.state, { csrfToken: token, userId: '9', regions: [region],
instances: [instance()], selectedKey: 'new-vpc', selected: doc(), vpcs: [doc().vpc] });
const renders = [];
api.observeDetailRender(() => {
renders.push({ busy: api.state.busy, attachment: api.state.instances[0]?.vpc_attachment?.state });
});
return { ...api, nodes, memberSubmit, emptyHint, aclDraft, requests, renders, timers,
fireTimeout(delay) {
const entry = [...timers].find(([, timer]) => timer.delay === delay);
assert.ok(entry, `Expected a pending ${delay} ms timeout`);
timers.delete(entry[0]);
entry[1].callback();
},
setFetch(nextHandler) { handler = nextHandler; } };
}
// A same-region VM owned by another VPC stays visible with an explanatory label.
{
const h = harness();
const choice = h.memberChoice(instance(11, attached), doc());
assert.equal(choice.disabled, true);
assert.equal(choice.reason, '已加入 VPC:原 VPC');
h.state.instances = [instance(11, attached), instance(12)];
assert.equal(h.populateMemberChoices(h.nodes['vpc-member-instance'], doc()), 1);
const options = h.nodes['vpc-member-instance'].options;
assert.deepEqual(options.map(option => option.value), ['', '12', '11']);
assert.equal(options[1].disabled, false);
assert.equal(options[2].disabled, true);
assert.match(options[2].textContent, /已加入 VPC:原 VPC/u);
}
// Server projection merges all live ownership states into attached; the local
// current-detail guard must also win over an older available bootstrap payload.
for (const memberState of ['active', 'applying', 'waiting', 'uncertain', 'degraded', 'suspended', 'unknown']) {
const h = harness();
const currentDoc = doc('new-vpc', [{ instance_id: 11, state: memberState }]);
const choice = h.memberChoice(instance(), currentDoc);
assert.equal(choice.disabled, true, `${memberState} current member must stay unavailable`);
assert.equal(choice.reason, '已在当前 VPC');
}
for (const memberState of ['deleting', 'deleted']) {
const h = harness();
assert.match(h.memberChoice(instance(), doc('new-vpc', [
{ instance_id: 11, state: memberState },
])).reason, /仍在清理/u);
}
// A legacy deleted tombstone still owns cleanup. Keep it unselectable while
// providing an explicit reconciliation path even for an otherwise stable root.
{
const h = harness();
assert.equal(h.hasMemberCleanup(null), false);
assert.equal(h.hasMemberCleanup({}), false);
assert.equal(h.hasMemberCleanup(doc()), false);
for (const state of ['active', 'deleting', 'unknown']) {
assert.equal(h.hasMemberCleanup(doc('new-vpc', [{ instance_id: 11, state }])), false);
}
assert.equal(h.hasMemberCleanup(doc('new-vpc', [{ instance_id: 11, state: 'deleted' }])), true);
assert.equal(h.hasMemberCleanup(doc('new-vpc', [
{ instance_id: 12, state: 'active' }, { instance_id: 11, state: 'DELETED' },
])), true);
assert.match(h.memberChoice(instance(11, { state: 'cleanup_pending', vpc_name: '旧私网' }), doc()).reason,
/旧私网.*仍在清理.*核对/u);
}
for (const status of ['active', 'awaiting_members']) {
const h = harness();
const cleanupDoc = doc('new-vpc', [{ instance_id: 11, state: 'deleted' }]);
if (status === 'awaiting_members') Object.assign(cleanupDoc.vpc, {
state: 'applying', usable: false, setup_state: 'awaiting_members', member_count: 0,
});
h.state.selected = cleanupDoc;
h.renderList();
assert.equal(h.nodes['vpc-list-reconcile'].hidden, false,
`${status} with a deleted member must retain its cleanup action.`);
assert.equal(h.nodes['vpc-list-reconcile'].disabled, false);
assert.equal(h.memberChoice(instance(), cleanupDoc).disabled, true);
h.setFetch(request => request.method === 'POST'
? response(cleanupDoc) : pageResponse([instance(11, { state: 'cleanup_pending' })]));
await h.reconcile();
assert.deepEqual(h.requests.filter(request => request.method === 'POST').map(request => request.path),
['/api/v1/vpcs/new-vpc/reconcile']);
assert.equal(h.state.instances[0].vpc_attachment.state, 'cleanup_pending',
'Requesting reconciliation alone must not manufacture a cleanup receipt.');
assert.equal(h.memberSubmit.disabled, true);
}
{
const h = harness();
Object.assign(h.state.selected.vpc, { state: 'applying', usable: false,
setup_state: 'awaiting_members', member_count: 0 });
h.renderList();
assert.equal(h.nodes['vpc-list-reconcile'].hidden, true);
assert.equal(h.nodes['vpc-list-reconcile'].disabled, true);
await h.reconcile();
assert.equal(h.requests.length, 0, 'A genuinely empty VPC does not need a cleanup reconciliation.');
assert.match(h.nodes['vpc-page-notice'].textContent, /等待实例/u);
}
{
const h = harness();
const cases = [
[instance(), false, ''],
[instance(11, { ...attached, vpc_key: 'new-vpc' }), true, '已在当前 VPC'],
[instance(11, { ...attached, vpc_name: '' }), true, '已加入其他 VPC'],
[instance(11, { state: 'cleanup_pending' }), true, '仍在清理'],
[instance(11, { state: 'unavailable' }), true, '待核验'],
[instance(11, { state: 'future-unknown' }), true, '待核验'],
[instance(11, null), true, '待核验'],
[{ id: 11 }, true, '待核验'],
[undefined, true, '待核验'],
[instance(11, available, { region_id: 8 }), true, '地区不匹配'],
[instance(11, available, { region_id: null }), true, '地区待核验'],
[instance(11, available, { region_id: 'invalid' }), true, '地区待核验'],
[instance(11, available, { service_available: false }), true, '服务当前不可用'],
];
for (const [row, disabled, reason] of cases) {
const result = h.memberChoice(row, doc());
assert.equal(result.disabled, disabled);
assert.ok(result.reason.includes(reason), result.reason);
}
h.state.instances = [instance(11, available, { service_available: false })];
h.refreshMemberChoices();
assert.deepEqual(h.nodes['vpc-member-instance'].options.map(option => option.value), ['']);
assert.equal(h.memberSubmit.disabled, true);
assert.equal(h.emptyHint.hidden, false);
}
// A fresh projection revokes an existing selection; successful cleanup makes it
// selectable again but must not silently reselect the previously blocked VM.
{
const h = harness();
const select = h.nodes['vpc-member-instance'];
h.refreshMemberChoices();
select.value = '11';
h.state.instances = [instance(11, { state: 'cleanup_pending' })];
h.refreshMemberChoices();
assert.equal(select.value, '');
assert.equal(h.memberSubmit.disabled, true);
h.setFetch(() => pageResponse([instance()]));
await h.refreshBootstrap();
assert.equal(select.value, '');
assert.equal(select.options.find(option => option.value === '11').disabled, false);
assert.equal(h.memberSubmit.disabled, false);
assert.equal(h.emptyHint.hidden, true);
select.value = '11';
await h.refreshBootstrap();
assert.equal(select.value, '11', 'A still eligible selection survives refresh.');
assert.equal(h.timers.size, 0, 'Completed candidate refresh must clear its timeout.');
}
for (const row of [instance(11, attached), instance(11, { state: 'cleanup_pending' }),
instance(11, null), instance(11, available, { region_id: 8 }),
instance(11, available, { service_available: false })]) {
const h = harness();
h.state.instances = [row];
await h.submitMember({ instance_id: { value: '11' } });
assert.equal(h.requests.length, 0, 'A manually forced blocked value must not POST.');
assert.notEqual(h.nodes['vpc-page-error'].textContent, '');
}
{
const h = harness();
await h.submitMember({ instance_id: { value: '9999' } });
assert.equal(h.requests.length, 0, 'A fabricated instance id must not POST.');
}
// Read-only candidate refreshes must keep dirty ACL input nodes and values intact.
{
const h = harness();
h.state.detailDirty = true;
const draft = h.aclDraft;
h.setFetch(() => pageResponse([instance(11, attached)]));
await h.refreshBootstrap();
assert.equal(h.state.detailDirty, true);
assert.equal(h.renders.length, 0, 'Candidate refresh must not rebuild the detail editor.');
assert.equal(h.aclDraft, draft);
assert.equal(h.aclDraft.value, 'unsaved ACL draft');
assert.equal(h.memberSubmit.disabled, true);
}
for (const failure of [
() => { throw new Error('network unavailable'); },
() => ({ ok: false, status: 503 }),
() => ({ ok: true, async text() { return '<html>login</html>'; } }),
() => ({ ok: true, async text() { return '<script id="vpc-bootstrap">broken</script>'; } }),
() => ({ ok: true, async text() {
return '<script id="vpc-bootstrap">{"user":{"user_id":"10","csrf_token":"'
+ token + '"},"instances":[]}</script>';
} }),
]) {
const h = harness();
h.refreshMemberChoices();
h.nodes['vpc-member-instance'].value = '11';
h.setFetch(failure);
assert.ok(await h.refreshBootstrap(true));
assert.equal(h.state.instances[0].vpc_attachment.state, 'unavailable');
assert.equal(h.nodes['vpc-member-instance'].value, '');
assert.equal(h.memberSubmit.disabled, true, 'A failed projection refresh must fail closed.');
}
// Ignore a pre-mutation response even if transport ignores AbortController.
// Refresh ownership after the write before controls become actionable again.
{
const h = harness();
const oldRead = deferred();
let pageRequests = 0;
h.setFetch(request => {
if (request.path === '/user/vpcs') {
pageRequests += 1;
if (pageRequests === 1) return oldRead.promise;
assert.equal(h.state.busy, true, 'Fresh ownership must be read while mutation stays locked.');
return pageResponse([instance(11, attached)]);
}
assert.equal(request.method, 'POST');
return response(doc('new-vpc', [{ instance_id: 11, state: 'applying' }]));
});
const pending = h.refreshBootstrap(true);
const oldSignal = h.requests[0].signal;
await h.submitMember({ instance_id: { value: '11' } });
assert.equal(oldSignal.aborted, true);
oldRead.resolve(pageResponse([instance()]));
await pending;
assert.equal(h.state.instances[0].vpc_attachment.state, 'attached');
assert.equal(h.memberSubmit.disabled, true);
assert.equal(h.state.busy, false);
assert.deepEqual(h.requests.map(request => `${request.method} ${request.path}`), [
'GET /user/vpcs', 'POST /api/v1/vpcs/new-vpc/members', 'GET /user/vpcs',
]);
assert.equal(h.renders.at(-1).attachment, 'attached');
}
// An ambiguous failed POST still refreshes ownership; a stale error from an
// earlier refresh must not erase a newer successful projection either.
{
const h = harness();
const oldRead = deferred();
let pageRequests = 0;
h.setFetch(request => {
if (request.method === 'POST') throw new Error('response lost');
pageRequests += 1;
return pageRequests === 1 ? oldRead.promise : pageResponse([instance(11, attached)]);
});
const pending = h.refreshBootstrap(true);
await h.mutate('/api/v1/vpcs/new-vpc/members', 'POST', { instance_id: 11 });
oldRead.resolve({ ok: false, status: 503 });
await pending;
assert.equal(h.state.instances[0].vpc_attachment.state, 'attached');
assert.equal(h.memberSubmit.disabled, true);
assert.match(h.nodes['vpc-page-error'].textContent, /response lost/u);
assert.equal(h.renders.length, 0, 'A failed mutation must not overwrite an editor draft.');
}
// A successful write must not leave all controls locked when refreshing either
// response headers or the HTML body stalls. Drive the actual deadline callback
// deterministically; no real timer or remote request is used by these tests.
for (const stalledStage of ['fetch', 'body']) {
const h = harness();
const reachedStall = deferred();
h.setFetch(request => {
if (request.method === 'POST') return response(doc());
const awaitAbort = () => new Promise((resolve, reject) => {
request.signal.addEventListener('abort', () => {
const error = new Error('aborted');
error.name = 'AbortError';
reject(error);
}, { once: true });
reachedStall.resolve();
});
return stalledStage === 'fetch' ? awaitAbort() : { ok: true, text: awaitAbort };
});
const operation = h.mutate('/api/v1/vpcs/new-vpc/members', 'POST', { instance_id: 11 });
await reachedStall.promise;
assert.equal(h.state.busy, true);
h.fireTimeout(10000);
await operation;
assert.equal(h.requests.at(-1).signal.aborted, true);
assert.equal(h.state.busy, false, `A ${stalledStage} timeout must release the mutation lock.`);
assert.equal(h.state.instances[0].vpc_attachment.state, 'unavailable');
assert.equal(h.memberSubmit.disabled, true);
assert.equal([...h.timers.values()].some(timer => timer.delay === 10000), false);
}
{
const h = harness();
const oldRead = deferred();
let pageRequests = 0;
h.setFetch(() => ++pageRequests === 1 ? oldRead.promise : pageResponse([instance(11, attached)]));
const pending = h.refreshBootstrap(true);
await h.refreshBootstrap(true);
const latestSignal = h.requests.at(-1).signal;
h.fireTimeout(10000);
assert.equal(latestSignal.aborted, false, 'An old deadline must only abort its own controller.');
oldRead.resolve({ ok: false, status: 503 });
await pending;
assert.equal(h.state.instances[0].vpc_attachment.state, 'attached',
'An expired read cannot replace the newer ownership projection with unavailable.');
assert.equal(h.timers.size, 0);
}
{
const h = harness();
h.setFetch(request => request.path === '/user/vpcs'
? pageResponse([instance(11, attached)]) : response(doc('another-vpc')));
await h.selectVpc('another-vpc');
assert.deepEqual(h.requests.map(request => request.path), ['/user/vpcs', '/api/v1/vpcs/another-vpc']);
assert.equal(h.state.selectedKey, 'another-vpc');
assert.equal(h.renders.at(-1).attachment, 'attached', 'Switching must refresh ownership before rendering choices.');
}
// A detail read started before the user edits a policy must not later erase it.
{
const h = harness();
const detailRead = deferred();
const detailStarted = deferred();
h.setFetch(request => {
if (request.path === '/user/vpcs') return pageResponse([instance()]);
detailStarted.resolve();
return detailRead.promise;
});
const selection = h.selectVpc('another-vpc');
await detailStarted.promise;
h.state.detailDirty = true;
detailRead.resolve(response(doc('another-vpc')));
await selection;
assert.equal(h.state.detailDirty, true);
assert.equal(h.renders.length, 0, 'A delayed detail read must preserve newly edited policy input.');
}
{
const h = harness();
h.setFetch(request => {
if (request.method === 'POST') return response(doc('created-vpc'));
assert.equal(h.state.busy, true);
return pageResponse([instance(11, attached)]);
});
const form = h.nodes['vpc-create-form'];
Object.assign(form, { name: { value: 'created-vpc' }, region_id: { value: '7' },
checkValidity() { return true; } });
await h.createVpc({ preventDefault() {}, currentTarget: form });
assert.deepEqual(h.requests.map(request => `${request.method} ${request.path}`), [
'POST /api/v1/vpcs', 'GET /user/vpcs',
]);
assert.equal(h.state.selectedKey, 'created-vpc');
assert.equal(h.state.busy, false);
assert.equal(h.renders.at(-1).attachment, 'attached', 'Creating a VPC must not reuse the old candidate snapshot.');
}
console.log('Cloud VPC member choices, cleanup, stale-read fencing and mutation refresh behavior passed.');

@ -0,0 +1,208 @@
<?php
use App\Services\Cloud\CloudVpcPageService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$root = dirname(__DIR__);
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
if (!is_file($root . '/vendor/autoload.php')) {
echo "VPC page membership runtime skipped (vendor missing).\n";
return;
}
require $root . '/vendor/autoload.php';
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_regions', static function (Blueprint $table): void {
$table->integer('id')->primary();
$table->string('name');
$table->string('country_code');
$table->string('status');
$table->integer('sort');
});
$schema->create('cloud_region_fabrics', static function (Blueprint $table): void {
$table->integer('region_id')->primary();
$table->integer('fabric_revision');
$table->string('state');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->integer('id')->primary();
$table->integer('user_id');
$table->string('name');
$table->string('status');
$table->text('spec_json');
$table->string('service_status');
$table->integer('expires_at')->nullable();
});
$schema->create('cloud_vpcs', static function (Blueprint $table): void {
$table->integer('id')->primary();
$table->integer('user_id');
$table->integer('region_id');
$table->string('vpc_key');
$table->string('name');
$table->string('state');
});
$schema->create('cloud_vpc_members', static function (Blueprint $table): void {
$table->integer('id')->primary();
$table->integer('instance_id');
$table->integer('vpc_id');
$table->string('state');
});
$schema->create('cloud_vpc_private_ips', static function (Blueprint $table): void {
$table->integer('instance_id');
$table->integer('member_id')->nullable();
$table->integer('vpc_id');
});
Capsule::table('cloud_regions')->insert([
['id' => 1, 'name' => 'Region A', 'country_code' => 'hk', 'status' => 'active', 'sort' => 1],
['id' => 2, 'name' => 'Region B', 'country_code' => 'jp', 'status' => 'active', 'sort' => 0],
]);
Capsule::table('cloud_region_fabrics')->insert([
['region_id' => 1, 'fabric_revision' => 1, 'state' => 'active'],
['region_id' => 2, 'fabric_revision' => 0, 'state' => 'active'],
]);
$key = static fn (int $id): string => str_pad(dechex($id), 32, '0', STR_PAD_LEFT);
foreach ([1 => 'active', 2 => 'active', 3 => 'deleting', 4 => 'deleted', 5 => 'active'] as $id => $state) {
Capsule::table('cloud_vpcs')->insert([
'id' => $id, 'user_id' => $id === 5 ? 8 : 7, 'region_id' => 1,
'vpc_key' => $key($id), 'name' => $id === 5 ? 'foreign-secret-name' : 'VPC ' . $id,
'state' => $state,
]);
}
$seedInstance = static function (int $id, array $overrides = []): void {
Capsule::table('cloud_instances')->insert(array_replace([
'id' => $id, 'user_id' => 7, 'name' => sprintf('VM %04d', $id), 'status' => 'active',
'spec_json' => json_encode(['region_id' => 1, 'region' => 'Region A']),
'service_status' => 'active', 'expires_at' => time() + 3600,
], $overrides));
};
$seedMember = static function (int $instanceId, int $vpcId, string $state): void {
Capsule::table('cloud_vpc_members')->insert([
'id' => $instanceId, 'instance_id' => $instanceId, 'vpc_id' => $vpcId, 'state' => $state,
]);
Capsule::table('cloud_vpc_private_ips')->insert([
'instance_id' => $instanceId, 'member_id' => $instanceId, 'vpc_id' => $vpcId,
]);
};
for ($id = 1; $id <= 25; $id++) {
$seedInstance($id);
}
$seedInstance(90, ['user_id' => 8, 'name' => 'foreign-instance-name']);
$seedMember(2, 1, 'active');
$seedMember(3, 2, 'active');
foreach ([4 => 'applying', 5 => 'uncertain', 6 => 'degraded', 7 => 'failed', 8 => 'pending'] as $id => $state) {
$seedMember($id, 1, $state);
}
$seedMember(11, 1, 'deleting');
$seedMember(12, 1, 'deleted');
$seedMember(13, 3, 'active');
$seedMember(14, 4, 'active');
Capsule::table('cloud_vpc_private_ips')->insert(['instance_id' => 15, 'member_id' => null, 'vpc_id' => 1]);
$seedMember(16, 5, 'active');
$seedMember(17, 999, 'active');
$seedMember(18, 1, 'active');
Capsule::table('cloud_vpc_private_ips')->where('instance_id', 18)->update(['vpc_id' => 5]);
$seedMember(19, 1, 'active');
// Model a pre-existing corrupt database without relaxing the production unique key.
Capsule::table('cloud_vpc_members')->insert(['id' => 190, 'instance_id' => 19, 'vpc_id' => 2, 'state' => 'active']);
Capsule::table('cloud_instances')->where('id', 20)->update(['expires_at' => time() - 1]);
Capsule::table('cloud_instances')->where('id', 21)->update(['service_status' => 'suspended']);
Capsule::table('cloud_instances')->where('id', 22)->update(['service_status' => 'exempt', 'expires_at' => null]);
Capsule::table('cloud_instances')->where('id', 23)->update(['status' => 'deleted']);
Capsule::table('cloud_instances')->where('id', 24)->update([
'spec_json' => json_encode(['region_id' => 2, 'region' => 'Region B']),
]);
Capsule::table('cloud_instances')->where('id', 25)->update(['spec_json' => 'invalid json']);
$actor = ['user_id' => 7, 'is_global' => true];
$read = static function () use ($actor): array {
$data = CloudVpcPageService::bootstrap($actor);
return array_column($data['instances'], null, 'id');
};
$connection = $capsule->getConnection('default');
$connection->enableQueryLog();
$rows = $read();
$queryCount = count($connection->getQueryLog());
$assert($rows[1]['vpc_attachment'] === ['state' => 'available', 'vpc_key' => null, 'vpc_name' => null],
'An unoccupied instance must remain selectable.');
foreach ([2 => 1, 3 => 2, 4 => 1, 5 => 1, 6 => 1, 7 => 1, 8 => 1] as $id => $vpcId) {
$assert($rows[$id]['vpc_attachment'] === [
'state' => 'attached', 'vpc_key' => $key($vpcId), 'vpc_name' => 'VPC ' . $vpcId,
], 'Every occupied member state must expose its owner-scoped VPC attachment.');
}
$assert($rows[2]['region_id'] === $rows[3]['region_id'],
'The cross-VPC fixture must exercise two VPCs in the same region.');
foreach ([11, 12, 13, 14] as $id) {
$assert($rows[$id]['vpc_attachment']['state'] === 'cleanup_pending',
'Member or root deletion must retain the instance reservation.');
}
foreach ([15, 16, 17, 18, 19] as $id) {
$assert($rows[$id]['vpc_attachment'] === ['state' => 'unavailable', 'vpc_key' => null, 'vpc_name' => null],
'Orphan, conflicting, duplicate or foreign ledgers must be unavailable without disclosing a VPC.');
}
$assert(!isset($rows[90]) && !isset($rows[23]) && !str_contains(json_encode($rows), 'foreign-'),
'The tenant projection must not reveal other accounts or deleted instances.');
$assert(!$rows[20]['service_available'] && !$rows[21]['service_available'] && $rows[22]['service_available']
&& $rows[24]['region_id'] === 2 && $rows[25]['region_id'] === null,
'Membership projection must preserve service lifecycle and region eligibility fields.');
$bootstrap = CloudVpcPageService::bootstrap($actor);
$assert(count($bootstrap['regions']) === 1 && $bootstrap['regions'][0]['country_code'] === 'HK',
'The existing active Fabric region projection must remain unchanged.');
$assert(CloudVpcPageService::bootstrap(['user_id' => 0])['instances'] === [],
'An actor without an account must not receive instance candidates.');
// A reload must observe joins immediately; only normal physical cleanup frees
// occupancy, never a terminal-looking member state or deletion of half a pair.
$seedMember(1, 2, 'applying');
$assert($read()[1]['vpc_attachment']['state'] === 'attached', 'A refresh missed a newly attached instance.');
Capsule::table('cloud_vpc_members')->where('instance_id', 1)->update(['state' => 'deleted']);
$assert($read()[1]['vpc_attachment']['state'] === 'cleanup_pending', 'Deleted membership was prematurely released.');
Capsule::table('cloud_vpc_members')->where('instance_id', 1)->delete();
$assert($read()[1]['vpc_attachment']['state'] === 'unavailable', 'An orphan lease was prematurely released.');
Capsule::table('cloud_vpc_private_ips')->where('instance_id', 1)->delete();
$assert($read()[1]['vpc_attachment']['state'] === 'available', 'Completed cleanup did not restore candidacy on refresh.');
$assertAllUnavailable = static function (string $reason) use ($read, $assert): void {
$observed = $read();
$assert(count($observed) === 24, 'Read failure must keep the bounded instance display available.');
foreach ($observed as $row) {
$assert($row['vpc_attachment'] === ['state' => 'unavailable', 'vpc_key' => null, 'vpc_name' => null], $reason);
}
};
foreach (['cloud_vpc_members', 'cloud_vpc_private_ips', 'cloud_vpcs'] as $table) {
$schema->rename($table, $table . '_hidden');
$assertAllUnavailable('A missing ledger table was mistaken for no membership.');
$schema->rename($table . '_hidden', $table);
}
// Inject a read failure at the actual database execution boundary while all
// table checks pass. An unavailable ledger must not reopen free candidates.
$failMembershipRead = true;
$connection->beforeExecuting(static function (string $query) use (&$failMembershipRead): void {
if ($failMembershipRead && str_contains($query, 'from "cloud_vpc_members"')) {
throw new RuntimeException('Simulated ledger read outage');
}
});
$assertAllUnavailable('A failed ledger query was mistaken for no membership.');
$failMembershipRead = false;
$assert($read()[1]['vpc_attachment']['state'] === 'available', 'Recovered reads must refresh candidacy.');
for ($id = 100; $id < 305; $id++) {
$seedInstance($id);
}
$connection->flushQueryLog();
$bounded = $read();
$assert(count($bounded) === 200, 'The page lost its 200-instance bound.');
$assert(count($connection->getQueryLog()) === $queryCount,
'Membership projection introduced per-instance database queries.');
$assert(array_slice(array_keys($bounded), 0, 24) === array_keys($rows),
'Membership projection changed stable instance ordering.');
echo "VPC page membership runtime passed.\n";

@ -150,11 +150,17 @@ $assert($memberRender !== '' && $memberSubmit !== ''
&& !str_contains($memberSubmit, 'subnet_key')
&& !str_contains($memberSubmit, 'private_ip'),
'Tenant member attach must submit only the instance and idempotency key.');
$assert(str_contains($memberRender, "new Option('请选择同地区实例', '', true, true)")
&& str_contains($memberRender, 'Number.isInteger(rowRegionId) && rowRegionId > 0')
&& str_contains($memberRender, 'regionVerified && rowRegionId === vpcRegionId')
&& str_contains($memberRender, '地区待核验,暂不可加入')
&& !str_contains($memberRender, '!row.region_id'),
$memberChoiceStart = strpos($script, 'function memberChoice(');
$memberChoiceEnd = strpos($script, 'function renderMembers(', $memberChoiceStart ?: 0);
$memberChoices = $memberChoiceStart !== false && $memberChoiceEnd !== false
? substr($script, $memberChoiceStart, $memberChoiceEnd - $memberChoiceStart) : '';
$assert(str_contains($memberChoices, "new Option('请选择同地区实例', '', true, true)")
&& str_contains($memberChoices, '!Number.isInteger(regionId) || regionId <= 0')
&& str_contains($memberChoices, 'regionId === Number(doc?.vpc?.region_id)')
&& str_contains($memberChoices, '地区待核验,暂不可加入')
&& str_contains($memberChoices, "attachment?.state !== 'available'")
&& str_contains($memberChoices, '已加入 VPC:')
&& str_contains($memberSubmit, 'memberChoice(row, state.selected)'),
'Tenant member choices must fail closed when the instance region is missing or mismatched.');
$assert(str_contains($template, '创建 VPC'),
'VPC view is missing the create form.');
@ -236,9 +242,9 @@ $assert(str_contains($script, "vpc_no_participating_hosts:")
&& str_contains($script, 'member_count_known: memberCountKnown')
&& str_contains($script, "!['active', 'awaiting_members'].includes(projectedStatus(item))")
&& str_contains($script, "status === 'awaiting_members'")
&& str_contains($script, "if (rootStatus(state.selected?.vpc) === 'awaiting_members')")
&& str_contains($script, "if (rootStatus(state.selected?.vpc) === 'awaiting_members' && !hasMemberCleanup())")
&& str_contains($script, "needsPolling() ? 8000 : 30000"),
'Empty VPCs must project a neutral awaiting-members state, avoid reconcile and use the stable poll interval.');
'Empty VPCs must avoid reconcile unless legacy member cleanup needs proof-based release.');
$assert(str_contains($script, "element('details', `vpc-disclosure")
&& str_contains($script, "disclosure('高级网络策略'")
&& str_contains($script, "disclosure('同步与诊断'")
@ -271,8 +277,9 @@ $assert($saveEditor !== ''
'Policy writes must fail closed whenever the current detail has no usable member.');
$assert(str_contains($script, 'data-vpc-tombstone-state="deleting"')
&& str_contains($script, 'pendingTombstones')
&& str_contains($script, 'sameRegion')
&& str_contains($script, 'alreadyAttached')
&& str_contains($script, 'function memberChoice(')
&& str_contains($script, "attachment?.state !== 'available'")
&& str_contains($script, 'populateMemberChoices(instance.control, doc)')
&& str_contains($script, 'option.disabled')
&& str_contains($script, 'requestFingerprint')
&& str_contains($script, 'confirmDetailMutation'),
@ -333,7 +340,7 @@ $pollEnd = strpos($script, 'function renderSummary(', $pollStart ?: 0);
$pollBlock = ($pollStart !== false && $pollEnd !== false)
? substr($script, $pollStart, $pollEnd - $pollStart) : '';
$assert($pollBlock !== ''
&& str_contains($pollBlock, 'await loadList(true)')
&& str_contains($pollBlock, 'await Promise.all([loadList(true), refreshBootstrap(true)])')
&& str_contains($pollBlock,
"if (state.stopped || state.busy || document.visibilityState === 'hidden')")
&& str_contains($pollBlock, 'await loadDetail(state.selectedKey, true)')

Loading…
Cancel
Save