You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
405 lines
14 KiB
JavaScript
405 lines
14 KiB
JavaScript
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',
|
|
);
|
|
|
|
// The page module has one local UI import and one exported bootstrap function.
|
|
// Remove only that module syntax, then expose the shipped helpers from the same
|
|
// lexical scope. This keeps the assertions coupled to production behavior
|
|
// without copying status projection logic into the test.
|
|
const source = moduleSource
|
|
.replace(/^import[^\n]+\n/u, '')
|
|
.replace('export async function initialize()', 'async function initialize()')
|
|
+ `\n;globalThis.__vpcBehavior = {
|
|
state,
|
|
normalizeRoot,
|
|
awaitingMembers,
|
|
rootStatus,
|
|
needsPolling,
|
|
handleDetailInput,
|
|
createRegionOptions,
|
|
hasPendingCreateIntent,
|
|
openCreateModal,
|
|
closeCreateModal,
|
|
createVpc,
|
|
saveEditor,
|
|
cancelReadbacks,
|
|
applyBootstrapPayload,
|
|
lockDeletingDetail,
|
|
restoreDeleteIntent,
|
|
acknowledgeDeleteRestore,
|
|
restoreVpcDelete,
|
|
};\n`;
|
|
|
|
class Node {
|
|
constructor() {
|
|
this.children = [];
|
|
this.attributes = new Map();
|
|
this.dataset = {};
|
|
this.className = '';
|
|
this.disabled = false;
|
|
this.hidden = true;
|
|
this.textContent = '';
|
|
this.title = '';
|
|
this.value = '';
|
|
this.isConnected = true;
|
|
this.resetCount = 0;
|
|
this.classList = { add() {}, remove() {} };
|
|
}
|
|
|
|
append(...children) { this.children.push(...children); }
|
|
replaceChildren(...children) { this.children = [...children]; }
|
|
removeAttribute(name) { this.attributes.delete(name); if (name === 'title') this.title = ''; }
|
|
reset() { this.resetCount += 1; }
|
|
focus() { document.activeElement = this; }
|
|
}
|
|
|
|
class OptionNode extends Node {
|
|
constructor(label, value, defaultSelected = false, selected = false) {
|
|
super();
|
|
this.textContent = String(label);
|
|
this.value = String(value);
|
|
this.defaultSelected = defaultSelected;
|
|
this.selected = selected;
|
|
}
|
|
}
|
|
|
|
const ids = [
|
|
'vpc-page-notice',
|
|
'vpc-page-error',
|
|
'vpc-create-region',
|
|
'vpc-create-open',
|
|
'vpc-create-submit',
|
|
'vpc-create-availability',
|
|
'vpc-create-region-hint',
|
|
'vpc-create-modal',
|
|
'vpc-create-form',
|
|
'vpc-create-name',
|
|
'vpc-create-close',
|
|
'vpc-create-cancel',
|
|
'vpc-create-error',
|
|
];
|
|
const nodes = Object.fromEntries(ids.map(id => [id, new Node()]));
|
|
const document = {
|
|
activeElement: null,
|
|
body: new Node(),
|
|
getElementById: id => nodes[id] || null,
|
|
};
|
|
let clearedTimers = 0;
|
|
let uuidCounter = 0;
|
|
const context = {
|
|
document,
|
|
HTMLElement: Node,
|
|
Option: OptionNode,
|
|
crypto: { randomUUID: () => `00000000-0000-4000-8000-${String(++uuidCounter).padStart(12, '0')}` },
|
|
clearTimeout() { clearedTimers += 1; },
|
|
console,
|
|
globalThis: null,
|
|
};
|
|
context.globalThis = context;
|
|
vm.runInNewContext(source, context, { filename: 'vpc.js' });
|
|
|
|
const {
|
|
state,
|
|
normalizeRoot,
|
|
awaitingMembers,
|
|
rootStatus,
|
|
needsPolling,
|
|
handleDetailInput,
|
|
createRegionOptions,
|
|
hasPendingCreateIntent,
|
|
openCreateModal,
|
|
closeCreateModal,
|
|
createVpc,
|
|
saveEditor,
|
|
cancelReadbacks,
|
|
applyBootstrapPayload,
|
|
lockDeletingDetail,
|
|
restoreDeleteIntent,
|
|
acknowledgeDeleteRestore,
|
|
restoreVpcDelete,
|
|
} = context.__vpcBehavior;
|
|
|
|
const emptyReservation = {
|
|
state: 'applying',
|
|
sync_state: 'applied',
|
|
usable: false,
|
|
setup_state: 'awaiting_members',
|
|
member_count: 0,
|
|
last_error_code: '',
|
|
};
|
|
|
|
assert.equal(awaitingMembers(emptyReservation), true);
|
|
assert.equal(rootStatus(emptyReservation), 'awaiting_members',
|
|
'A newly reserved VPC with no members is an actionable setup step, not a failure.');
|
|
|
|
for (const lastErrorCode of ['vpc_no_members', 'vpc_no_participating_hosts']) {
|
|
const legacyReservation = {
|
|
state: 'degraded',
|
|
sync_state: 'failed',
|
|
usable: false,
|
|
last_error_code: lastErrorCode,
|
|
};
|
|
assert.equal(rootStatus(legacyReservation), 'awaiting_members',
|
|
`${lastErrorCode} must keep pre-projection rows usable as a neutral empty state.`);
|
|
}
|
|
|
|
const explicitUnsafeProjection = normalizeRoot({
|
|
state: 'degraded',
|
|
sync_state: 'failed',
|
|
usable: false,
|
|
setup_state: null,
|
|
member_count: 0,
|
|
last_error_code: 'vpc_no_participating_hosts',
|
|
});
|
|
assert.equal(rootStatus(explicitUnsafeProjection), 'degraded',
|
|
'Explicit null setup_state/member_count fields must let the server reject an unsafe empty ledger.');
|
|
assert.equal(rootStatus(normalizeRoot({
|
|
state: 'degraded',
|
|
sync_state: 'failed',
|
|
usable: false,
|
|
last_error_code: 'vpc_no_participating_hosts',
|
|
})), 'awaiting_members', 'Only a truly legacy projection may use the closed-set gate fallback.');
|
|
|
|
assert.equal(rootStatus({
|
|
state: 'degraded',
|
|
sync_state: 'failed',
|
|
usable: false,
|
|
member_count: 0,
|
|
last_error_code: 'vpc_host_apply_failed',
|
|
}), 'degraded', 'A real host failure must not be hidden by an empty member count.');
|
|
|
|
assert.equal(rootStatus({
|
|
...emptyReservation,
|
|
state: 'deleting',
|
|
sync_state: 'failed',
|
|
last_error_code: 'vpc_no_participating_hosts',
|
|
}), 'deleting', 'Deletion owns the root even when stale empty-state evidence remains.');
|
|
|
|
assert.equal(rootStatus({
|
|
...emptyReservation,
|
|
state: 'degraded',
|
|
sync_state: 'failed',
|
|
member_count: 1,
|
|
}), 'degraded', 'A non-empty VPC must not consume stale awaiting-members projection.');
|
|
|
|
const restorableDelete = normalizeRoot({
|
|
vpc_key: '1'.repeat(32),
|
|
name: 'restore-me',
|
|
state: 'deleting',
|
|
sync_state: 'uncertain',
|
|
desired_revision: 6,
|
|
last_operation_id: '2'.repeat(32),
|
|
can_restore_delete: true,
|
|
});
|
|
assert.equal(restorableDelete.can_restore_delete, true,
|
|
'Only the explicit server capability may enable deletion restoration.');
|
|
assert.equal(normalizeRoot({ can_restore_delete: 'true' }).can_restore_delete, false,
|
|
'A truthy non-boolean capability must fail closed.');
|
|
|
|
state.selectedKey = restorableDelete.vpc_key;
|
|
state.selected = { vpc: restorableDelete, members: [] };
|
|
state.busy = false;
|
|
const ordinaryDeleteControl = new Node();
|
|
const reconcileDeleteControl = new Node();
|
|
const restoreDeleteControl = new Node();
|
|
const deletingContainer = {
|
|
dataset: {},
|
|
querySelectorAll() {
|
|
return [ordinaryDeleteControl, reconcileDeleteControl, restoreDeleteControl];
|
|
},
|
|
};
|
|
lockDeletingDetail(deletingContainer, reconcileDeleteControl, restoreDeleteControl);
|
|
assert.equal(deletingContainer.dataset.rootDeleting, 'true');
|
|
assert.equal(ordinaryDeleteControl.disabled, true,
|
|
'Ordinary controls must remain locked throughout root deletion.');
|
|
assert.equal(reconcileDeleteControl.disabled, false);
|
|
assert.equal(restoreDeleteControl.disabled, false,
|
|
'The server-authorized restore action must remain available beside reconcile.');
|
|
|
|
state.busy = true;
|
|
ordinaryDeleteControl.disabled = false;
|
|
reconcileDeleteControl.disabled = false;
|
|
restoreDeleteControl.disabled = false;
|
|
lockDeletingDetail(deletingContainer, reconcileDeleteControl, restoreDeleteControl);
|
|
assert.equal(ordinaryDeleteControl.disabled, true);
|
|
assert.equal(reconcileDeleteControl.disabled, true);
|
|
assert.equal(restoreDeleteControl.disabled, true,
|
|
'Busy state must lock both exceptional deletion actions.');
|
|
state.busy = false;
|
|
|
|
const firstRestoreIntent = restoreDeleteIntent(restorableDelete);
|
|
const secondRestoreIntent = restoreDeleteIntent(restorableDelete);
|
|
assert.equal(firstRestoreIntent.path,
|
|
`/api/v1/vpcs/${restorableDelete.vpc_key}/delete/restore`);
|
|
assert.equal(firstRestoreIntent.body.confirmation_name, 'restore-me');
|
|
assert.equal(firstRestoreIntent.body.expected_revision, 6);
|
|
assert.equal(firstRestoreIntent.body.expected_operation_id, '2'.repeat(32));
|
|
assert.match(firstRestoreIntent.body.request_key, /^vpc-delete-restore-/);
|
|
assert.equal(secondRestoreIntent.body.request_key, firstRestoreIntent.body.request_key,
|
|
'An unacknowledged restore retry must reuse its idempotency key.');
|
|
const nextDeleteRestoreIntent = restoreDeleteIntent({
|
|
...restorableDelete,
|
|
desired_revision: 8,
|
|
last_operation_id: '3'.repeat(32),
|
|
});
|
|
assert.notEqual(nextDeleteRestoreIntent.body.request_key,
|
|
firstRestoreIntent.body.request_key,
|
|
'A later delete identity must receive a new restore idempotency key.');
|
|
|
|
state.deleteRequestKeys.set(restorableDelete.vpc_key, 'stale-delete-request');
|
|
acknowledgeDeleteRestore(restorableDelete.vpc_key);
|
|
assert.equal(state.deleteRequestKeys.has(restorableDelete.vpc_key), false,
|
|
'A successful restore must retire the old delete idempotency key.');
|
|
assert.equal(state.restoreDeleteRequestKeys.has(restorableDelete.vpc_key), false,
|
|
'A successful restore must retire its restore idempotency intent.');
|
|
|
|
let restorePrompts = 0;
|
|
context.prompt = () => { restorePrompts += 1; return 'restore-me'; };
|
|
state.busy = true;
|
|
await restoreVpcDelete();
|
|
assert.equal(restorePrompts, 0, 'Busy state must reject restore before prompting.');
|
|
state.busy = false;
|
|
state.selected.vpc.can_restore_delete = false;
|
|
await restoreVpcDelete();
|
|
assert.equal(restorePrompts, 0,
|
|
'A deleting root without the explicit server capability must reject restore.');
|
|
state.selected.vpc.can_restore_delete = true;
|
|
|
|
state.selected = null;
|
|
state.vpcs = [{ vpc_key: 'empty', ...emptyReservation }];
|
|
assert.equal(Boolean(needsPolling()), false,
|
|
'An empty reservation is stable and must not enter the eight-second convergence loop.');
|
|
state.vpcs = [{
|
|
vpc_key: 'failed',
|
|
state: 'degraded',
|
|
sync_state: 'failed',
|
|
usable: false,
|
|
member_count: 1,
|
|
last_error_code: 'vpc_host_apply_failed',
|
|
}];
|
|
assert.equal(needsPolling(), true, 'A real degraded VPC remains in fast polling.');
|
|
state.vpcs = [];
|
|
state.selected = null;
|
|
assert.equal(needsPolling(), false);
|
|
assert.equal(typeof needsPolling(), 'boolean', 'Polling projection must always return a boolean.');
|
|
|
|
function detailTarget(editor) {
|
|
return {
|
|
closest(selector) {
|
|
assert.equal(selector, '#vpc-route-editor, #vpc-acl-editor');
|
|
return editor === 'route' || editor === 'acl' ? {} : null;
|
|
},
|
|
matches() { return false; },
|
|
};
|
|
}
|
|
|
|
state.detailDirty = false;
|
|
handleDetailInput({ target: detailTarget('member') });
|
|
assert.equal(state.detailDirty, false,
|
|
'Member and other detail inputs must not pause polling as unsaved route/ACL edits.');
|
|
|
|
for (const editor of ['route', 'acl']) {
|
|
state.detailDirty = false;
|
|
nodes['vpc-page-notice'].hidden = true;
|
|
handleDetailInput({ target: detailTarget(editor) });
|
|
assert.equal(state.detailDirty, true, `${editor} edits must mark the detail dirty.`);
|
|
assert.equal(nodes['vpc-page-notice'].hidden, false);
|
|
assert.match(nodes['vpc-page-notice'].textContent, /未保存修改/);
|
|
}
|
|
|
|
state.busy = false;
|
|
state.regions = [];
|
|
createRegionOptions();
|
|
assert.equal(nodes['vpc-create-region'].disabled, true);
|
|
assert.equal(nodes['vpc-create-open'].disabled, true,
|
|
'Create must stay unavailable when the server exposes no Fabric-backed region.');
|
|
assert.equal(nodes['vpc-create-submit'].disabled, true);
|
|
assert.equal(nodes['vpc-create-availability'].hidden, false);
|
|
assert.match(nodes['vpc-create-region-hint'].textContent, /暂不能创建 VPC/);
|
|
|
|
state.regions = [{ id: 7, name: 'Hong Kong' }];
|
|
createRegionOptions();
|
|
assert.equal(nodes['vpc-create-region'].disabled, false);
|
|
assert.equal(nodes['vpc-create-open'].disabled, false);
|
|
assert.equal(nodes['vpc-create-submit'].disabled, false);
|
|
assert.equal(nodes['vpc-create-availability'].hidden, true);
|
|
assert.deepEqual(nodes['vpc-create-region'].children.map(option => option.value), ['', '7']);
|
|
|
|
const retryForm = nodes['vpc-create-form'];
|
|
retryForm.dataset.requestKey = 'vpc-create-12345678';
|
|
retryForm.dataset.requestFingerprint = '{"name":"retry","region_id":7}';
|
|
assert.equal(hasPendingCreateIntent(retryForm), true);
|
|
nodes['vpc-create-modal'].hidden = false;
|
|
state.createFocusReturn = nodes['vpc-create-open'];
|
|
closeCreateModal();
|
|
assert.equal(retryForm.dataset.requestKey, 'vpc-create-12345678',
|
|
'Closing the modal after an attempted create must preserve its idempotency key.');
|
|
const resetsBeforeRetry = retryForm.resetCount;
|
|
openCreateModal();
|
|
assert.equal(retryForm.resetCount, resetsBeforeRetry,
|
|
'Reopening an ambiguous create must preserve its form intent for a safe retry.');
|
|
closeCreateModal(true, true);
|
|
assert.equal(hasPendingCreateIntent(retryForm), false,
|
|
'Only an acknowledged success or explicit reset may clear the create intent.');
|
|
|
|
state.busy = false;
|
|
state.regions = [{ id: 7, name: 'Hong Kong' }];
|
|
const invalidForm = {
|
|
checkValidity: () => false,
|
|
reportValidityCalled: false,
|
|
reportValidity() { this.reportValidityCalled = true; },
|
|
};
|
|
const clearedBeforeInvalidSubmit = clearedTimers;
|
|
await createVpc({ preventDefault() {}, currentTarget: invalidForm });
|
|
assert.equal(invalidForm.reportValidityCalled, true);
|
|
assert.equal(clearedTimers, clearedBeforeInvalidSubmit,
|
|
'An invalid create form must not stop status polling.');
|
|
|
|
state.selectedKey = 'unsafe-empty';
|
|
state.selected = { vpc: normalizeRoot({
|
|
vpc_key: 'unsafe-empty',
|
|
state: 'degraded',
|
|
sync_state: 'failed',
|
|
usable: false,
|
|
setup_state: null,
|
|
member_count: 0,
|
|
last_error_code: 'vpc_no_participating_hosts',
|
|
}), members: [] };
|
|
await saveEditor('routes');
|
|
assert.match(nodes['vpc-page-error'].textContent, /有可用成员后/,
|
|
'Every zero-member detail must reject policy saves, including explicit unsafe projections.');
|
|
|
|
let abortedReadbacks = 0;
|
|
state.refreshEpoch = 2;
|
|
state.bootstrapEpoch = 3;
|
|
state.listEpoch = 4;
|
|
state.detailEpoch = 5;
|
|
state.bootstrapController = { abort() { abortedReadbacks += 1; } };
|
|
state.listController = { abort() { abortedReadbacks += 1; } };
|
|
state.detailController = { abort() { abortedReadbacks += 1; } };
|
|
cancelReadbacks();
|
|
assert.equal(abortedReadbacks, 3);
|
|
assert.deepEqual([
|
|
state.refreshEpoch, state.bootstrapEpoch, state.listEpoch, state.detailEpoch,
|
|
], [3, 4, 5, 6], 'A mutation must invalidate every in-flight read generation.');
|
|
assert.equal(state.bootstrapController, null);
|
|
assert.equal(state.listController, null);
|
|
assert.equal(state.detailController, null);
|
|
|
|
const token = 'a'.repeat(64);
|
|
state.userId = '';
|
|
applyBootstrapPayload({
|
|
user: { user_id: '9', csrf_token: token },
|
|
regions: [{ id: 8, name: 'Singapore' }],
|
|
instances: [{ id: 12, name: 'vm-12' }],
|
|
}, false);
|
|
assert.deepEqual(state.regions, [{ id: 8, name: 'Singapore' }]);
|
|
assert.deepEqual(state.instances, [{ id: 12, name: 'vm-12' }]);
|
|
|
|
console.log('Cloud VPC user-page projection, retry, policy-gate, polling and candidate-refresh behavior passed.');
|