|
|
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
|
|
|
|
function versionedModuleUrl(path) {
|
|
|
const url = new URL(path, import.meta.url);
|
|
|
url.search = '';
|
|
|
if (assetVersion) url.searchParams.set('v', assetVersion);
|
|
|
return url.href;
|
|
|
}
|
|
|
|
|
|
const [taskObserver, runtime] = await Promise.all([
|
|
|
import(versionedModuleUrl('./task-observer.js')),
|
|
|
import(versionedModuleUrl('./runtime.js')),
|
|
|
]);
|
|
|
const {
|
|
|
announceTaskAccepted, observeTask, recoveryTaskFailureNotice,
|
|
|
resolvedTaskFailureNotice, taskSucceededWithoutRecovery, taskUrl,
|
|
|
} = taskObserver;
|
|
|
const {
|
|
|
api, byId, initializeSession, readBootstrap, showError, toast,
|
|
|
} = runtime;
|
|
|
const i18n = globalThis.VenixUserCopy;
|
|
|
const t = (key, parameters = {}) => i18n.text(key, parameters);
|
|
|
|
|
|
const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options)
|
|
|
?? Promise.resolve(false);
|
|
|
|
|
|
const PORT_STATE_LABELS = Object.freeze({
|
|
|
preparing: ['vpc.status.port.preparing', 'other'],
|
|
|
attached: ['vpc.status.port.attached', 'running'],
|
|
|
detaching: ['vpc.status.port.detaching', 'other'],
|
|
|
release_pending: ['vpc.status.port.release_pending', 'other'],
|
|
|
released: ['vpc.status.port.released', 'other'],
|
|
|
migrating: ['vpc.status.port.migrating', 'other'],
|
|
|
});
|
|
|
|
|
|
const BATCH_ITEM_STATE_LABELS = Object.freeze({
|
|
|
waiting_route: ['vpc.status.batch_item.waiting', 'other'],
|
|
|
queued: ['vpc.status.batch_item.running', 'other'],
|
|
|
succeeded: ['vpc.status.batch_item.succeeded', 'running'],
|
|
|
failed: ['vpc.status.batch_item.failed', 'failed'],
|
|
|
unknown: ['vpc.status.batch_item.failed', 'failed'],
|
|
|
});
|
|
|
|
|
|
const state = {
|
|
|
items: [], instances: [], regions: [], maximum: 16, used: 0,
|
|
|
loading: false, controller: null, creating: false, initialized: false,
|
|
|
createKey: '', createFingerprint: '', userKey: 'unknown',
|
|
|
mutatingVpcs: new Set(), deleteUncertainVpcs: new Set(),
|
|
|
mutatingInstances: new Set(),
|
|
|
mutatingBatches: new Set(), membershipBatches: [],
|
|
|
batchRefreshAt: 0,
|
|
|
observers: new Map(), terminalTasks: new Set(),
|
|
|
selections: new Map(), memberQueries: new Map(),
|
|
|
regionOptions: '',
|
|
|
};
|
|
|
|
|
|
function element(tag, className = '', content) {
|
|
|
const node = document.createElement(tag);
|
|
|
if (className) node.className = className;
|
|
|
if (content !== undefined) node.textContent = String(content);
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function idempotencyKey() {
|
|
|
if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().replaceAll('-', '');
|
|
|
if (globalThis.crypto?.getRandomValues) {
|
|
|
const bytes = new Uint8Array(16);
|
|
|
globalThis.crypto.getRandomValues(bytes);
|
|
|
return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
|
|
|
}
|
|
|
return `${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`
|
|
|
.padEnd(32, '0').slice(0, 32);
|
|
|
}
|
|
|
|
|
|
function transportUncertain(error) {
|
|
|
const status = Number(error?.status);
|
|
|
const name = String(error?.name || '');
|
|
|
return error?.mutationMayHaveApplied === true
|
|
|
|| (Number.isFinite(status) && status >= 500)
|
|
|
|| ['TypeError', 'AbortError', 'TimeoutError'].includes(name);
|
|
|
}
|
|
|
|
|
|
function setPageStatus(message = '', type = '') {
|
|
|
const target = byId('cloud-vpcs-status');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `vm-settings-status${type ? ` ${type}` : ''}`;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function apply(payload) {
|
|
|
state.items = Array.isArray(payload?.items) ? payload.items : [];
|
|
|
state.instances = Array.isArray(payload?.instances) ? payload.instances : [];
|
|
|
state.membershipBatches = Array.isArray(payload?.membership_batches)
|
|
|
? payload.membership_batches : [];
|
|
|
state.regions = Array.isArray(payload?.regions) ? payload.regions : [];
|
|
|
state.maximum = Math.max(1, Number(payload?.maximum) || 16);
|
|
|
state.used = Math.max(0, Number(payload?.used) || state.items.length);
|
|
|
render();
|
|
|
observeActiveTasks();
|
|
|
observeActiveBatches();
|
|
|
}
|
|
|
|
|
|
function renderRegions() {
|
|
|
const select = byId('cloud-vpc-region');
|
|
|
const options = JSON.stringify(state.regions.map(region => [region.id, region.name, region.code]));
|
|
|
if (options !== state.regionOptions) {
|
|
|
state.regionOptions = options;
|
|
|
const selected = select.value;
|
|
|
select.replaceChildren();
|
|
|
const empty = element('option', '', t(state.regions.length
|
|
|
? 'vpc.create.region_select' : 'vpc.create.region_empty'));
|
|
|
empty.value = '';
|
|
|
select.append(empty);
|
|
|
for (const region of state.regions) {
|
|
|
const option = element('option', '', region.name || region.code
|
|
|
|| t('vpc.create.region_unnamed'));
|
|
|
option.value = String(region.id);
|
|
|
option.selected = String(region.id) === selected;
|
|
|
select.append(option);
|
|
|
}
|
|
|
}
|
|
|
select.disabled = state.creating;
|
|
|
byId('cloud-vpc-name').disabled = state.creating;
|
|
|
byId('cloud-vpc-create-submit').disabled = state.creating
|
|
|
|| state.used >= state.maximum || !state.regions.length;
|
|
|
byId('cloud-vpc-create-submit').textContent = t(state.creating
|
|
|
? 'vpc.create.submitting' : 'vpc.create.submit');
|
|
|
const availability = byId('cloud-vpc-create-availability');
|
|
|
availability.textContent = state.used >= state.maximum
|
|
|
? t('vpc.create.quota_full', { maximum: state.maximum })
|
|
|
: !state.regions.length ? t('vpc.create.region_unavailable') : '';
|
|
|
availability.hidden = !availability.textContent;
|
|
|
}
|
|
|
|
|
|
function vpcState(value) {
|
|
|
return String(value || '').toLowerCase() === 'active'
|
|
|
? [t('vpc.status.active'), 'running'] : [t('vpc.status.unknown'), 'other'];
|
|
|
}
|
|
|
|
|
|
function instanceId(instance) {
|
|
|
return String(instance?.id || '');
|
|
|
}
|
|
|
|
|
|
function portAction(instance) {
|
|
|
if (instance?.can_attach === true) return 'attach';
|
|
|
if (instance?.can_retry_attach === true) return 'retry_attach';
|
|
|
if (instance?.can_detach === true) return 'detach';
|
|
|
if (instance?.can_retry_detach === true) return 'retry_detach';
|
|
|
return '';
|
|
|
}
|
|
|
|
|
|
function taskId(receipt) {
|
|
|
return taskUrl(receipt) ? String(receipt.task_id || '') : '';
|
|
|
}
|
|
|
|
|
|
function pendingStorageKey(instance) {
|
|
|
return `virt-cloud:pending-vpc-port:${state.userKey}:${instanceId(instance)}`;
|
|
|
}
|
|
|
|
|
|
function pendingMutationKey(instance, fingerprint) {
|
|
|
let saved = null;
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(pendingStorageKey(instance)) || 'null'); }
|
|
|
catch {}
|
|
|
const key = saved?.fingerprint === fingerprint
|
|
|
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
|
|
|
? String(saved.key) : idempotencyKey();
|
|
|
try {
|
|
|
sessionStorage.setItem(pendingStorageKey(instance), JSON.stringify({ fingerprint, key }));
|
|
|
} catch {}
|
|
|
return key;
|
|
|
}
|
|
|
|
|
|
function clearPendingMutationKey(instance) {
|
|
|
try { sessionStorage.removeItem(pendingStorageKey(instance)); } catch {}
|
|
|
}
|
|
|
|
|
|
function instancesForVpc(vpc) {
|
|
|
const key = String(vpc?.vpc_key || '');
|
|
|
return state.instances.filter(instance => String(instance?.port?.vpc_key || '') === key);
|
|
|
}
|
|
|
|
|
|
function candidatesForVpc(vpc) {
|
|
|
const regionId = Number(vpc?.region_id || 0);
|
|
|
return state.instances.filter(instance => !instance?.port
|
|
|
&& Number(instance?.region_id || 0) === regionId);
|
|
|
}
|
|
|
|
|
|
function vpcKey(vpc) {
|
|
|
return String(vpc?.vpc_key || '');
|
|
|
}
|
|
|
|
|
|
function publicIpv4(instance) {
|
|
|
return String(instance?.public_ipv4 || '').trim() || t('vpc.value.unassigned');
|
|
|
}
|
|
|
|
|
|
function publicIpv6(instance) {
|
|
|
return String(instance?.public_ipv6 || '').trim() || t('vpc.value.unassigned');
|
|
|
}
|
|
|
|
|
|
function normalizedMemberQuery(value) {
|
|
|
return String(value || '').trim().toLocaleLowerCase();
|
|
|
}
|
|
|
|
|
|
function instanceMatchesMemberQuery(instance, query) {
|
|
|
if (!query) return true;
|
|
|
return [instance?.name, instanceId(instance), publicIpv4(instance), publicIpv6(instance)]
|
|
|
.some(value => String(value || '').toLocaleLowerCase().includes(query));
|
|
|
}
|
|
|
|
|
|
function pageRoute() {
|
|
|
const hash = window.location.hash;
|
|
|
if (!hash || hash === '#') {
|
|
|
const query = new URL(window.location.href).searchParams;
|
|
|
const key = query.getAll('vpc').at(-1) ?? null;
|
|
|
const view = query.getAll('view').at(-1) ?? null;
|
|
|
if ((key !== null && !/^[a-f0-9]{32}$/.test(key))
|
|
|
|| [...query.keys()].some(name => /^(?:vpc|view)\[/.test(name))
|
|
|
|| (view !== null && !['create', 'members', 'join'].includes(view))
|
|
|
|| (!key && ['members', 'join'].includes(view))) return { page: 'missing' };
|
|
|
if (key) return { page: 'members', key, joining: view === 'join' };
|
|
|
return { page: view === 'create' ? 'create' : 'home' };
|
|
|
}
|
|
|
if (hash === '#/') return { page: 'home' };
|
|
|
if (hash === '#/create') return { page: 'create' };
|
|
|
const match = /^#\/([a-f0-9]{32})\/instances(\/join)?$/.exec(hash);
|
|
|
return match ? { page: 'members', key: match[1], joining: Boolean(match[2]) }
|
|
|
: { page: 'missing' };
|
|
|
}
|
|
|
|
|
|
function membersHref(vpc, joining = false) {
|
|
|
return `/user/cloud/vpcs?vpc=${encodeURIComponent(vpcKey(vpc))}${joining ? '&view=join' : ''}`;
|
|
|
}
|
|
|
|
|
|
function membersRouteHref(vpc, joining = false) {
|
|
|
return `#/${encodeURIComponent(vpcKey(vpc))}/instances${joining ? '/join' : ''}`;
|
|
|
}
|
|
|
|
|
|
function currentVpc() {
|
|
|
const route = pageRoute();
|
|
|
return state.items.find(vpc => vpcKey(vpc) === route.key) || null;
|
|
|
}
|
|
|
|
|
|
function routeChanged() {
|
|
|
closeBatchConfirmation(false);
|
|
|
render();
|
|
|
const route = pageRoute();
|
|
|
const heading = route.page === 'home' ? 'cloud-vpcs-title'
|
|
|
: route.page === 'create' ? 'cloud-vpc-create-title'
|
|
|
: currentVpc() ? 'cloud-vpc-members-title' : 'cloud-vpc-missing-title';
|
|
|
byId(heading)?.focus({ preventScroll: true });
|
|
|
byId('cloud-vpcs-workspace')?.scrollIntoView({ block: 'start' });
|
|
|
}
|
|
|
|
|
|
function selectionForVpc(vpc, action) {
|
|
|
const key = `${vpcKey(vpc)}:${action}`;
|
|
|
if (!state.selections.has(key)) state.selections.set(key, new Set());
|
|
|
return state.selections.get(key);
|
|
|
}
|
|
|
|
|
|
function activeBatchForVpc(vpc) {
|
|
|
const key = vpcKey(vpc);
|
|
|
return state.membershipBatches.find(batch => String(batch?.vpc_key || '') === key)
|
|
|
|| null;
|
|
|
}
|
|
|
|
|
|
function activeBatchItemForInstance(vpc, instance) {
|
|
|
const batch = activeBatchForVpc(vpc);
|
|
|
if (!batch || !Array.isArray(batch.items)) return null;
|
|
|
const id = instanceId(instance);
|
|
|
return batch.items.find(item => String(item?.instance_id || '') === id) || null;
|
|
|
}
|
|
|
|
|
|
function batchPendingStorageKey(vpc, action) {
|
|
|
return `virt-cloud:pending-vpc-batch:${state.userKey}:${vpcKey(vpc)}:${action}`;
|
|
|
}
|
|
|
|
|
|
function pendingBatchKey(vpc, action, ids) {
|
|
|
const fingerprint = `${action}:${[...ids].map(String).sort((a, b) => Number(a) - Number(b)).join(',')}`;
|
|
|
const storageKey = batchPendingStorageKey(vpc, action);
|
|
|
let saved = null;
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(storageKey) || 'null'); } catch {}
|
|
|
const key = saved?.fingerprint === fingerprint
|
|
|
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
|
|
|
? String(saved.key) : idempotencyKey();
|
|
|
try { sessionStorage.setItem(storageKey, JSON.stringify({ fingerprint, key })); } catch {}
|
|
|
return key;
|
|
|
}
|
|
|
|
|
|
function clearPendingBatchKey(vpc, action) {
|
|
|
try { sessionStorage.removeItem(batchPendingStorageKey(vpc, action)); } catch {}
|
|
|
}
|
|
|
|
|
|
function taskCenterButton() {
|
|
|
const button = element('button', 'cloud-vpc-text-button', t('vpc.task.view'));
|
|
|
button.type = 'button';
|
|
|
button.setAttribute('data-task-center-open', '');
|
|
|
button.setAttribute('aria-haspopup', 'dialog');
|
|
|
button.setAttribute('aria-controls', 'panel-task-drawer');
|
|
|
button.setAttribute('aria-expanded', 'false');
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function renderBatchStatus(vpc) {
|
|
|
const batch = activeBatchForVpc(vpc);
|
|
|
if (!batch) return null;
|
|
|
const batchState = String(batch.state || '');
|
|
|
const box = element('div', `cloud-vpc-batch-status${batchState === 'blocked' ? ' uncertain' : ''}`);
|
|
|
const content = element('div');
|
|
|
const total = Math.max(0, Number(batch.total) || 0);
|
|
|
const succeeded = Math.max(0, Number(batch.succeeded) || 0);
|
|
|
const failed = Math.max(0, Number(batch.failed) || 0);
|
|
|
const unknown = Math.max(0, Number(batch.unknown) || 0);
|
|
|
const action = t(batch.action === 'detach' ? 'vpc.action.detach' : 'vpc.action.attach');
|
|
|
const phase = t({
|
|
|
routing: 'vpc.batch.phase.routing',
|
|
|
ports: 'vpc.batch.phase.ports',
|
|
|
cleanup: 'vpc.batch.phase.cleanup',
|
|
|
blocked: batch.can_cancel === true
|
|
|
? 'vpc.batch.phase.blocked_cancelable' : 'vpc.batch.phase.blocked',
|
|
|
}[batchState] || 'vpc.batch.phase.reconciling');
|
|
|
const progress = [
|
|
|
t('vpc.batch.total', { count: total }),
|
|
|
t('vpc.batch.succeeded', { count: succeeded }),
|
|
|
failed > 0 ? t('vpc.batch.failed', { count: failed }) : '',
|
|
|
unknown > 0 ? t('vpc.batch.unknown', { count: unknown }) : '',
|
|
|
].filter(Boolean).join(t('vpc.value.list_separator'));
|
|
|
content.append(element('strong', '', t('vpc.batch.title', { action, phase })),
|
|
|
element('small', '', t('vpc.batch.progress', { progress })));
|
|
|
const actions = element('div', 'cloud-vpc-batch-actions');
|
|
|
actions.append(taskCenterButton());
|
|
|
if (batch.can_cancel === true) {
|
|
|
const cancel = element('button', 'cloud-vpc-text-button danger', t('vpc.batch.cancel'));
|
|
|
cancel.type = 'button';
|
|
|
cancel.dataset.vpcFocus = 'cancel-batch';
|
|
|
cancel.disabled = state.mutatingBatches.has(vpcKey(vpc));
|
|
|
cancel.addEventListener('click', () => void cancelMembershipBatch(vpc, batch));
|
|
|
actions.append(cancel);
|
|
|
}
|
|
|
box.append(content, actions);
|
|
|
return box;
|
|
|
}
|
|
|
|
|
|
function emptyState(title, description, href = '', action = '') {
|
|
|
const box = element('div', 'cloud-vpc-empty');
|
|
|
box.append(element('strong', '', title), element('p', '', description));
|
|
|
if (href) {
|
|
|
const link = element('a', 'button button-outline', action);
|
|
|
link.href = href;
|
|
|
box.append(link);
|
|
|
}
|
|
|
return box;
|
|
|
}
|
|
|
|
|
|
function renderNetworkCard(vpc) {
|
|
|
const link = element('a', 'cloud-vpc-network-card');
|
|
|
link.href = membersRouteHref(vpc);
|
|
|
const identity = element('span', 'cloud-vpc-network-identity');
|
|
|
const icon = element('span', 'cloud-vpc-network-icon');
|
|
|
const iconGlyph = element('i', 'mdi mdi-lan-connect');
|
|
|
iconGlyph.setAttribute('aria-hidden', 'true');
|
|
|
icon.append(iconGlyph);
|
|
|
const title = element('span', 'cloud-vpc-network-title');
|
|
|
title.append(element('strong', '', vpc.name), element('small', '', vpc.region_name));
|
|
|
identity.append(icon, title);
|
|
|
const address = element('span', 'cloud-vpc-network-address');
|
|
|
address.append(element('small', '', t('vpc.label.cidr')), element('code', '', vpc.cidr));
|
|
|
const count = element('span', 'cloud-vpc-network-count');
|
|
|
count.append(element('small', '', t('vpc.label.instances')),
|
|
|
element('strong', '', t('vpc.count.instances', { count: vpc.port_count || 0 })));
|
|
|
const [label, type] = activeBatchForVpc(vpc)
|
|
|
? [t('vpc.status.changing'), 'other'] : vpcState(vpc.state);
|
|
|
const arrow = element('span', 'cloud-vpc-network-arrow', '›');
|
|
|
arrow.setAttribute('aria-hidden', 'true');
|
|
|
link.append(identity, address, count, element('span', `state-pill ${type}`, label), arrow);
|
|
|
return link;
|
|
|
}
|
|
|
|
|
|
function renderHome() {
|
|
|
const list = byId('cloud-vpcs-list');
|
|
|
list.replaceChildren();
|
|
|
if (!state.items.length) {
|
|
|
list.append(emptyState(t('vpc.empty.title'), t('vpc.empty.body'),
|
|
|
'/user/cloud/vpcs?view=create', t('vpc.home.create')));
|
|
|
return;
|
|
|
}
|
|
|
const networks = element('div', 'cloud-vpc-network-list');
|
|
|
networks.setAttribute('aria-label', t('vpc.list.aria'));
|
|
|
networks.append(...state.items.map(renderNetworkCard));
|
|
|
list.append(networks);
|
|
|
}
|
|
|
|
|
|
function canSelectInstance(instance, action, batchBlocked) {
|
|
|
return !batchBlocked && instance[action === 'attach' ? 'can_attach' : 'can_detach'] === true
|
|
|
&& !state.mutatingInstances.has(instanceId(instance)) && !taskId(instance.active_task);
|
|
|
}
|
|
|
|
|
|
function renderInstanceRow(instance, vpc, joining, checkbox) {
|
|
|
const id = instanceId(instance);
|
|
|
const port = instance.port || {};
|
|
|
const row = element('article', 'cloud-vpc-instance-card cloud-vpc-instance-row');
|
|
|
row.setAttribute('role', 'listitem');
|
|
|
row.classList.toggle('selected', checkbox.checked);
|
|
|
const select = element('label', 'cloud-vpc-instance-select');
|
|
|
const instanceName = instance.name || t('vpc.instance.fallback', { id });
|
|
|
select.append(checkbox, element('span', 'sr-only',
|
|
|
t('vpc.member.choose', { action: t(joining ? 'vpc.action.attach' : 'vpc.action.detach'), name: instanceName })));
|
|
|
const identity = element('div', 'cloud-vpc-instance-identity');
|
|
|
const link = element('a', 'cloud-vpc-name-link', instanceName);
|
|
|
link.href = `/user/cloud/instances/${encodeURIComponent(id)}`;
|
|
|
identity.append(link);
|
|
|
const facts = element('dl', 'cloud-vpc-instance-facts');
|
|
|
const publicAddress = element('div');
|
|
|
const publicValue = element('dd');
|
|
|
publicValue.append(element('code', '', publicIpv4(instance)));
|
|
|
publicAddress.append(element('dt', '', t('vpc.label.public_ipv4')), publicValue);
|
|
|
const publicAddress6 = element('div');
|
|
|
const publicValue6 = element('dd');
|
|
|
publicValue6.append(element('code', '', publicIpv6(instance)));
|
|
|
publicAddress6.append(element('dt', '', t('vpc.label.public_ipv6')), publicValue6);
|
|
|
const privateAddress = element('div', 'cloud-vpc-private-address');
|
|
|
const privateValue = element('dd');
|
|
|
privateValue.append(element(joining ? 'span' : 'code', '', joining
|
|
|
? t('vpc.value.auto_assign') : port.private_ip || t('vpc.value.pending')));
|
|
|
privateAddress.append(element('dt', '', t(joining
|
|
|
? 'vpc.label.private_allocation' : 'vpc.label.private_ipv4')), privateValue);
|
|
|
facts.append(publicAddress, publicAddress6, privateAddress);
|
|
|
if (!joining && port.mac_address) {
|
|
|
const macAddress = element('div', 'cloud-vpc-mac-address');
|
|
|
const macValue = element('dd');
|
|
|
macValue.append(element('code', '', port.mac_address));
|
|
|
macAddress.append(element('dt', '', t('vpc.label.mac')), macValue);
|
|
|
facts.append(macAddress);
|
|
|
}
|
|
|
|
|
|
const batchItem = activeBatchItemForInstance(vpc, instance);
|
|
|
const [labelKey, type] = batchItem
|
|
|
? BATCH_ITEM_STATE_LABELS[String(batchItem.state || '')]
|
|
|
|| ['vpc.status.batch_item.waiting', 'other']
|
|
|
: joining
|
|
|
? (instance.can_attach === true
|
|
|
? ['vpc.status.can_attach', 'running'] : ['vpc.status.cannot_attach', 'other'])
|
|
|
: PORT_STATE_LABELS[String(port.state || '')] || ['vpc.status.unknown', 'other'];
|
|
|
const status = element('div', 'cloud-vpc-instance-status');
|
|
|
status.append(element('span', `state-pill ${type}`, t(labelKey)));
|
|
|
if (!batchItem && instance.action_unavailable_reason) {
|
|
|
status.append(element('small', '', t('vpc.instance.unavailable')));
|
|
|
}
|
|
|
const action = portAction(instance);
|
|
|
if (!batchItem && taskId(instance.active_task)) {
|
|
|
status.append(taskCenterButton());
|
|
|
} else if (!batchItem && (action === 'retry_attach' || action === 'retry_detach')) {
|
|
|
const retry = element('button', 'cloud-vpc-text-button',
|
|
|
t(action === 'retry_attach' ? 'vpc.retry.attach' : 'vpc.retry.detach'));
|
|
|
retry.type = 'button';
|
|
|
retry.dataset.vpcFocus = `retry-${id}`;
|
|
|
retry.disabled = Boolean(activeBatchForVpc(vpc))
|
|
|
|| state.mutatingBatches.has(vpcKey(vpc)) || state.mutatingInstances.has(id);
|
|
|
retry.addEventListener('click', () =>
|
|
|
void mutatePort(instance, vpc, action === 'retry_attach' ? 'attach' : 'detach'));
|
|
|
status.append(retry);
|
|
|
}
|
|
|
row.append(select, identity, facts, status);
|
|
|
return row;
|
|
|
}
|
|
|
|
|
|
function renderInstanceManager(vpc, joining) {
|
|
|
const action = joining ? 'attach' : 'detach';
|
|
|
const instances = joining ? candidatesForVpc(vpc) : instancesForVpc(vpc);
|
|
|
const queryKey = vpcKey(vpc);
|
|
|
const batchBlocked = Boolean(activeBatchForVpc(vpc))
|
|
|
|| state.mutatingBatches.has(vpcKey(vpc));
|
|
|
const selection = selectionForVpc(vpc, action);
|
|
|
const eligibleIds = new Set(instances.filter(item =>
|
|
|
canSelectInstance(item, action, batchBlocked)).map(instanceId));
|
|
|
for (const id of [...selection]) {
|
|
|
if (!eligibleIds.has(id)) selection.delete(id);
|
|
|
}
|
|
|
const section = element('section', 'cloud-vpc-instance-manager');
|
|
|
section.classList.toggle('joining', joining);
|
|
|
section.setAttribute('aria-label', t(joining
|
|
|
? 'vpc.member.manager_join_aria' : 'vpc.member.manager_members_aria'));
|
|
|
section.append(element('p', 'cloud-vpc-list-hint', t(joining
|
|
|
? 'vpc.member.hint_join' : 'vpc.member.hint_members')));
|
|
|
if (!instances.length) {
|
|
|
section.append(joining
|
|
|
? emptyState(t('vpc.empty.join.title'), t('vpc.empty.join.body'))
|
|
|
: emptyState(t('vpc.empty.members.title'), t('vpc.empty.members.body'),
|
|
|
membersRouteHref(vpc, true), t('vpc.empty.members.action')));
|
|
|
return section;
|
|
|
}
|
|
|
let search = null;
|
|
|
if (joining) {
|
|
|
const searchField = element('label', 'cloud-vpc-instance-search');
|
|
|
searchField.append(element('span', 'sr-only', t('vpc.member.search')));
|
|
|
search = element('input', 'cloud-vpc-instance-search-input');
|
|
|
search.type = 'search';
|
|
|
search.placeholder = t('vpc.member.search');
|
|
|
search.value = String(state.memberQueries.get(queryKey) || '');
|
|
|
search.dataset.vpcFocus = 'instance-search';
|
|
|
search.setAttribute('aria-label', t('vpc.member.search'));
|
|
|
searchField.append(search);
|
|
|
section.append(searchField);
|
|
|
}
|
|
|
const selectAll = element('input');
|
|
|
selectAll.type = 'checkbox';
|
|
|
selectAll.dataset.vpcFocus = 'select-all';
|
|
|
selectAll.setAttribute('aria-label', t(joining
|
|
|
? 'vpc.member.select_all_join' : 'vpc.member.select_all_members'));
|
|
|
selectAll.disabled = eligibleIds.size === 0;
|
|
|
const selectAllLabel = element('label', 'cloud-vpc-select-all');
|
|
|
selectAllLabel.append(selectAll, element('span', '', t(joining
|
|
|
? 'vpc.member.select_all_join' : 'vpc.member.select_all_members')));
|
|
|
const controls = element('div', 'cloud-vpc-list-controls');
|
|
|
controls.append(selectAllLabel);
|
|
|
const list = element('div', 'cloud-vpc-instance-list');
|
|
|
list.setAttribute('role', 'list');
|
|
|
list.setAttribute('aria-label', t(joining
|
|
|
? 'vpc.member.list_join' : 'vpc.member.list_members'));
|
|
|
const checks = [];
|
|
|
const countLabel = element('span');
|
|
|
countLabel.setAttribute('role', 'status');
|
|
|
const clear = element('button', 'cloud-vpc-text-button', t('vpc.member.clear'));
|
|
|
clear.type = 'button';
|
|
|
clear.dataset.vpcFocus = 'clear-selection';
|
|
|
const submit = element('button', 'button button-primary');
|
|
|
submit.type = 'button';
|
|
|
submit.dataset.vpcFocus = 'submit-selection';
|
|
|
const updateControls = () => {
|
|
|
const visibleEligibleIds = new Set(checks.filter(({ id, row }) =>
|
|
|
!row.hidden && eligibleIds.has(id)).map(({ id }) => id));
|
|
|
const selectedVisible = [...visibleEligibleIds].filter(id => selection.has(id)).length;
|
|
|
section.classList.toggle('has-selection', selection.size > 0);
|
|
|
countLabel.textContent = t('vpc.member.selected', { count: selection.size });
|
|
|
clear.hidden = selection.size === 0;
|
|
|
submit.disabled = batchBlocked || selection.size === 0;
|
|
|
const actionLabel = t(joining ? 'vpc.action.attach' : 'vpc.action.detach');
|
|
|
submit.textContent = selection.size
|
|
|
? t('vpc.member.submit_selected', { action: actionLabel, count: selection.size })
|
|
|
: t('vpc.member.submit_empty', { action: actionLabel });
|
|
|
selectAll.disabled = visibleEligibleIds.size === 0;
|
|
|
selectAll.checked = visibleEligibleIds.size > 0
|
|
|
&& selectedVisible === visibleEligibleIds.size;
|
|
|
selectAll.indeterminate = selectedVisible > 0
|
|
|
&& selectedVisible < visibleEligibleIds.size;
|
|
|
for (const { checkbox, row, id } of checks) {
|
|
|
checkbox.checked = selection.has(id);
|
|
|
row.classList.toggle('selected', checkbox.checked);
|
|
|
}
|
|
|
};
|
|
|
for (const instance of instances) {
|
|
|
const id = instanceId(instance);
|
|
|
const checkbox = element('input');
|
|
|
checkbox.type = 'checkbox';
|
|
|
checkbox.value = id;
|
|
|
checkbox.dataset.vpcFocus = `select-${id}`;
|
|
|
checkbox.checked = selection.has(id);
|
|
|
checkbox.disabled = !eligibleIds.has(id);
|
|
|
checkbox.setAttribute('aria-label', t('vpc.member.choose', {
|
|
|
action: t(joining ? 'vpc.action.attach' : 'vpc.action.detach'),
|
|
|
name: instance.name || t('vpc.instance.fallback', { id }),
|
|
|
}));
|
|
|
const row = renderInstanceRow(instance, vpc, joining, checkbox);
|
|
|
checkbox.addEventListener('change', () => {
|
|
|
if (checkbox.checked && !checkbox.disabled) selection.add(id);
|
|
|
else selection.delete(id);
|
|
|
updateControls();
|
|
|
});
|
|
|
checks.push({ id, checkbox, row, instance });
|
|
|
list.append(row);
|
|
|
}
|
|
|
selectAll.addEventListener('change', () => {
|
|
|
for (const { id, row } of checks) {
|
|
|
if (row.hidden || !eligibleIds.has(id)) continue;
|
|
|
if (selectAll.checked) selection.add(id);
|
|
|
else selection.delete(id);
|
|
|
}
|
|
|
updateControls();
|
|
|
});
|
|
|
clear.addEventListener('click', () => { selection.clear(); updateControls(); });
|
|
|
submit.addEventListener('click', () => void submitMembershipBatch(vpc, action,
|
|
|
instances.filter(item => selection.has(instanceId(item)) && eligibleIds.has(instanceId(item)))));
|
|
|
const noMatches = emptyState(t('vpc.empty.search.title'), t('vpc.empty.search.body'));
|
|
|
noMatches.classList.add('cloud-vpc-search-empty');
|
|
|
noMatches.hidden = true;
|
|
|
const applySearch = () => {
|
|
|
const query = normalizedMemberQuery(search?.value);
|
|
|
if (joining) {
|
|
|
if (query) state.memberQueries.set(queryKey, search.value);
|
|
|
else state.memberQueries.delete(queryKey);
|
|
|
}
|
|
|
let visible = 0;
|
|
|
for (const { instance, row } of checks) {
|
|
|
const matched = !joining || instanceMatchesMemberQuery(instance, query);
|
|
|
row.hidden = !matched;
|
|
|
if (matched) visible += 1;
|
|
|
}
|
|
|
noMatches.hidden = visible > 0;
|
|
|
updateControls();
|
|
|
};
|
|
|
search?.addEventListener('input', applySearch);
|
|
|
const toolbar = element('div', 'cloud-vpc-batch-toolbar');
|
|
|
toolbar.append(countLabel, clear, submit);
|
|
|
section.append(controls, list, noMatches, toolbar);
|
|
|
applySearch();
|
|
|
return section;
|
|
|
}
|
|
|
|
|
|
function renderMembers(vpc, joining) {
|
|
|
byId('cloud-vpc-members-title').textContent = vpc.name;
|
|
|
const [label, type] = vpcState(vpc.state);
|
|
|
const status = byId('cloud-vpc-members-state');
|
|
|
status.textContent = label;
|
|
|
status.className = `state-pill ${type}`;
|
|
|
const summary = byId('cloud-vpc-network-summary');
|
|
|
summary.replaceChildren();
|
|
|
for (const [label, value] of [
|
|
|
[t('vpc.label.region'), vpc.region_name], [t('vpc.label.cidr'), vpc.cidr],
|
|
|
[t('vpc.label.gateway'), vpc.gateway],
|
|
|
[t('vpc.label.joined'), t('vpc.count.instances', { count: instancesForVpc(vpc).length })],
|
|
|
]) {
|
|
|
const item = element('div');
|
|
|
item.append(element('dt', '', label), element('dd', '', value));
|
|
|
summary.append(item);
|
|
|
}
|
|
|
const batch = byId('cloud-vpc-batch-status');
|
|
|
batch.replaceChildren();
|
|
|
const batchStatus = renderBatchStatus(vpc);
|
|
|
if (batchStatus) batch.append(batchStatus);
|
|
|
const members = byId('cloud-vpc-members-link');
|
|
|
members.replaceChildren(element('span', '', t('vpc.member.joined')),
|
|
|
element('span', 'cloud-vpc-tab-count', instancesForVpc(vpc).length));
|
|
|
members.href = membersRouteHref(vpc);
|
|
|
const join = byId('cloud-vpc-join-link');
|
|
|
const joinable = candidatesForVpc(vpc).filter(instance => instance.can_attach === true).length;
|
|
|
join.replaceChildren(element('span', '', t('vpc.member.join')),
|
|
|
element('span', 'cloud-vpc-tab-count', joinable));
|
|
|
join.href = membersRouteHref(vpc, true);
|
|
|
for (const [link, active] of [[members, !joining], [join, joining]]) {
|
|
|
if (active) link.setAttribute('aria-current', 'page');
|
|
|
else link.removeAttribute('aria-current');
|
|
|
}
|
|
|
byId('cloud-vpc-instance-manager').replaceChildren(renderInstanceManager(vpc, joining));
|
|
|
byId('cloud-vpc-members-note').textContent = t('vpc.settings.delete_body');
|
|
|
const remove = byId('cloud-vpc-delete');
|
|
|
const deleteUncertain = state.deleteUncertainVpcs.has(vpcKey(vpc));
|
|
|
remove.disabled = vpc.can_delete !== true || Boolean(activeBatchForVpc(vpc))
|
|
|
|| state.mutatingVpcs.has(vpcKey(vpc)) || state.mutatingBatches.has(vpcKey(vpc))
|
|
|
|| deleteUncertain;
|
|
|
remove.title = t(deleteUncertain ? 'vpc.settings.delete_uncertain'
|
|
|
: remove.disabled ? 'vpc.settings.delete_disabled' : 'vpc.settings.delete_ready');
|
|
|
}
|
|
|
|
|
|
function render() {
|
|
|
const focused = document.activeElement?.dataset?.vpcFocus;
|
|
|
renderRegions();
|
|
|
const route = pageRoute();
|
|
|
const vpc = currentVpc();
|
|
|
const page = route.page === 'members' && !vpc ? 'missing' : route.page;
|
|
|
for (const name of ['home', 'create', 'members', 'missing']) {
|
|
|
byId(`cloud-vpcs-${name}`).hidden = page !== name;
|
|
|
}
|
|
|
byId('cloud-vpcs-back').hidden = page === 'home';
|
|
|
byId('cloud-vpcs-quota').textContent = t('vpc.quota', {
|
|
|
used: state.used,
|
|
|
maximum: state.maximum,
|
|
|
});
|
|
|
if (page === 'home') renderHome();
|
|
|
if (page === 'members') renderMembers(vpc, route.joining);
|
|
|
if (focused) {
|
|
|
[...byId('cloud-vpcs-workspace').querySelectorAll('[data-vpc-focus]')]
|
|
|
.find(node => node.dataset.vpcFocus === focused && !node.disabled)
|
|
|
?.focus({ preventScroll: true });
|
|
|
}
|
|
|
}
|
|
|
|
|
|
let pendingConfirmation = null;
|
|
|
|
|
|
function closeBatchConfirmation(confirmed) {
|
|
|
if (!pendingConfirmation) return;
|
|
|
const { resolve, opener } = pendingConfirmation;
|
|
|
pendingConfirmation = null;
|
|
|
byId('cloud-vpc-confirm').close();
|
|
|
document.documentElement.classList.remove('cloud-vpc-confirm-open');
|
|
|
if (opener?.isConnected) opener.focus({ preventScroll: true });
|
|
|
resolve(confirmed);
|
|
|
}
|
|
|
|
|
|
function confirmMembership(vpc, action, instances) {
|
|
|
const dialog = byId('cloud-vpc-confirm');
|
|
|
if (pendingConfirmation || typeof dialog?.showModal !== 'function') {
|
|
|
setPageStatus(t('vpc.confirm.unsupported'), 'error');
|
|
|
return Promise.resolve(false);
|
|
|
}
|
|
|
const word = t(action === 'attach' ? 'vpc.action.attach' : 'vpc.action.detach');
|
|
|
byId('cloud-vpc-confirm-title').textContent = t('vpc.confirm.title', {
|
|
|
action: word,
|
|
|
count: instances.length,
|
|
|
});
|
|
|
byId('cloud-vpc-confirm-note').textContent = t('vpc.confirm.note', {
|
|
|
action: word,
|
|
|
name: vpc.name,
|
|
|
});
|
|
|
const list = byId('cloud-vpc-confirm-instances');
|
|
|
list.replaceChildren();
|
|
|
for (const instance of instances) {
|
|
|
const row = element('li');
|
|
|
row.append(element('span', '', instance.name), element('code', '', publicIpv4(instance)));
|
|
|
list.append(row);
|
|
|
}
|
|
|
byId('cloud-vpc-confirm-restart').checked = false;
|
|
|
const submit = byId('cloud-vpc-confirm-submit');
|
|
|
submit.disabled = true;
|
|
|
submit.textContent = t('vpc.confirm.submit', { action: word });
|
|
|
submit.className = action === 'detach' ? 'button button-outline danger' : 'button button-primary';
|
|
|
return new Promise(resolve => {
|
|
|
pendingConfirmation = { resolve, opener: document.activeElement };
|
|
|
dialog.showModal();
|
|
|
document.documentElement.classList.add('cloud-vpc-confirm-open');
|
|
|
byId('cloud-vpc-confirm-cancel').focus();
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function bindBatchConfirmation() {
|
|
|
for (const id of ['cloud-vpc-confirm-close', 'cloud-vpc-confirm-cancel']) {
|
|
|
byId(id).addEventListener('click', () => closeBatchConfirmation(false));
|
|
|
}
|
|
|
byId('cloud-vpc-confirm-restart').addEventListener('change', event => {
|
|
|
byId('cloud-vpc-confirm-submit').disabled = !event.target.checked;
|
|
|
});
|
|
|
byId('cloud-vpc-confirm-form').addEventListener('submit', event => {
|
|
|
event.preventDefault();
|
|
|
if (byId('cloud-vpc-confirm-restart').checked) closeBatchConfirmation(true);
|
|
|
});
|
|
|
const dialog = byId('cloud-vpc-confirm');
|
|
|
dialog.addEventListener('cancel', event => {
|
|
|
event.preventDefault();
|
|
|
closeBatchConfirmation(false);
|
|
|
});
|
|
|
dialog.addEventListener('close', () => {
|
|
|
if (!dialog.open) closeBatchConfirmation(false);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function taskFailureMessage(task) {
|
|
|
const resolved = resolvedTaskFailureNotice(task);
|
|
|
if (resolved) return t('vpc.error.task_resolved');
|
|
|
const recovery = recoveryTaskFailureNotice(task);
|
|
|
if (recovery) return t('vpc.error.task_recovery');
|
|
|
if (task?.effect_may_have_applied === true) {
|
|
|
return t('vpc.error.task_uncertain');
|
|
|
}
|
|
|
return task?.safe_to_resubmit === false
|
|
|
? t('vpc.error.task_locked') : t('vpc.error.task_failed');
|
|
|
}
|
|
|
|
|
|
function observeReceipt(instance, receipt, accepted = false) {
|
|
|
const id = taskId(receipt);
|
|
|
if (!id || state.observers.has(id) || state.terminalTasks.has(id)) return null;
|
|
|
if (accepted) announceTaskAccepted(receipt, { title: t('vpc.task.single_title') });
|
|
|
const handle = observeTask(receipt, {
|
|
|
onUpdate: () => setPageStatus(t('vpc.status.task_running')),
|
|
|
onTerminal: task => {
|
|
|
state.observers.delete(id);
|
|
|
state.terminalTasks.add(id);
|
|
|
state.mutatingInstances.delete(instanceId(instance));
|
|
|
void load(true).then(() => {
|
|
|
const refreshed = state.instances.find(item =>
|
|
|
instanceId(item) === instanceId(instance));
|
|
|
const nextTask = taskId(refreshed?.active_task);
|
|
|
const portState = String(refreshed?.port?.state || '');
|
|
|
const settled = !refreshed?.port || portState === 'attached';
|
|
|
if (nextTask && nextTask !== id) {
|
|
|
setPageStatus(taskSucceededWithoutRecovery(task)
|
|
|
? t('vpc.status.next_stage')
|
|
|
: t('vpc.status.stage_unsettled'),
|
|
|
taskSucceededWithoutRecovery(task) ? '' : 'warning');
|
|
|
} else if (taskSucceededWithoutRecovery(task) && settled) {
|
|
|
setPageStatus(t('vpc.status.port_updated'), 'success');
|
|
|
toast(t('vpc.toast.operation_complete.body'), 'success',
|
|
|
t('vpc.toast.operation_complete.title'));
|
|
|
} else if (taskSucceededWithoutRecovery(task)) {
|
|
|
setPageStatus(t('vpc.status.stage_converging'));
|
|
|
} else {
|
|
|
setPageStatus(taskFailureMessage(task), 'error');
|
|
|
}
|
|
|
});
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
state.observers.delete(id);
|
|
|
state.mutatingInstances.delete(instanceId(instance));
|
|
|
if (reason !== 'pagehide') {
|
|
|
setPageStatus(t('vpc.status.observer_stopped'), 'warning');
|
|
|
void load(true);
|
|
|
}
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) return null;
|
|
|
state.observers.set(id, handle);
|
|
|
void handle.done.finally(() => state.observers.delete(id));
|
|
|
return handle;
|
|
|
}
|
|
|
|
|
|
function observeActiveTasks() {
|
|
|
const batchVpcKeys = new Set(state.membershipBatches
|
|
|
.map(batch => String(batch?.vpc_key || '')).filter(Boolean));
|
|
|
for (const instance of state.instances) {
|
|
|
if (instance?.active_task
|
|
|
&& !batchVpcKeys.has(String(instance?.port?.vpc_key || ''))) {
|
|
|
observeReceipt(instance, instance.active_task, false);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function observeBatch(batch, accepted = false) {
|
|
|
const receipt = {
|
|
|
task_id: String(batch?.task_id || ''),
|
|
|
status_url: String(batch?.status_url || ''),
|
|
|
};
|
|
|
const id = taskId(receipt);
|
|
|
const key = String(batch?.vpc_key || '');
|
|
|
if (!id || !key || String(batch?.state || '') === 'blocked'
|
|
|
|| state.observers.has(id) || state.terminalTasks.has(id)) return null;
|
|
|
if (accepted) announceTaskAccepted(receipt, { title: t('vpc.task.batch_title') });
|
|
|
const handle = observeTask(receipt, {
|
|
|
onUpdate: () => {
|
|
|
setPageStatus(t('vpc.status.batch_running'));
|
|
|
const now = Date.now();
|
|
|
if (!state.loading && now - state.batchRefreshAt >= 2000) {
|
|
|
state.batchRefreshAt = now;
|
|
|
void load(true);
|
|
|
}
|
|
|
},
|
|
|
onTerminal: task => {
|
|
|
state.observers.delete(id);
|
|
|
state.terminalTasks.add(id);
|
|
|
state.mutatingBatches.delete(key);
|
|
|
void load(true).then(() => {
|
|
|
if (taskSucceededWithoutRecovery(task)) {
|
|
|
setPageStatus(t('vpc.status.batch_complete'), 'success');
|
|
|
toast(t('vpc.toast.batch_complete.body'), 'success',
|
|
|
t('vpc.toast.batch_complete.title'));
|
|
|
} else {
|
|
|
setPageStatus(taskFailureMessage(task), 'error');
|
|
|
}
|
|
|
});
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
state.observers.delete(id);
|
|
|
state.mutatingBatches.delete(key);
|
|
|
if (reason !== 'pagehide') {
|
|
|
setPageStatus(t('vpc.status.batch_observer_stopped'), 'warning');
|
|
|
void load(true);
|
|
|
}
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) return null;
|
|
|
state.observers.set(id, handle);
|
|
|
void handle.done.finally(() => state.observers.delete(id));
|
|
|
return handle;
|
|
|
}
|
|
|
|
|
|
function observeActiveBatches() {
|
|
|
for (const batch of state.membershipBatches) observeBatch(batch, false);
|
|
|
}
|
|
|
|
|
|
function stopObservers(reason = 'pagehide') {
|
|
|
for (const observer of state.observers.values()) observer.stop(reason);
|
|
|
state.observers.clear();
|
|
|
}
|
|
|
|
|
|
async function load(force = false) {
|
|
|
if (state.loading && !force) return;
|
|
|
state.controller?.abort();
|
|
|
state.loading = true;
|
|
|
const controller = new AbortController();
|
|
|
state.controller = controller;
|
|
|
setPageStatus(t('vpc.status.loading'));
|
|
|
render();
|
|
|
try {
|
|
|
const payload = await api('/api/v1/vpcs', { signal: controller.signal });
|
|
|
if (controller.signal.aborted) return;
|
|
|
apply(payload);
|
|
|
setPageStatus();
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted) return;
|
|
|
setPageStatus(t('vpc.error.load'), 'error');
|
|
|
} finally {
|
|
|
if (state.controller === controller) {
|
|
|
state.controller = null;
|
|
|
state.loading = false;
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function submitMembershipBatch(vpc, action, instances) {
|
|
|
const key = vpcKey(vpc);
|
|
|
if (!key || !instances.length || activeBatchForVpc(vpc)
|
|
|
|| state.mutatingBatches.has(key)) return;
|
|
|
const attach = action === 'attach';
|
|
|
const ids = [...new Set(instances.map(instance => Number(instanceId(instance))))]
|
|
|
.filter(id => Number.isInteger(id) && id > 0);
|
|
|
if (!ids.length) return;
|
|
|
const confirmed = await confirmMembership(vpc, action, instances);
|
|
|
if (!confirmed || activeBatchForVpc(vpc) || state.mutatingBatches.has(key)) return;
|
|
|
// Eligibility may change while the confirmation dialog is open.
|
|
|
const current = state.items.find(item => vpcKey(item) === key);
|
|
|
const available = current && (attach ? candidatesForVpc(current) : instancesForVpc(current));
|
|
|
if (!available || ids.some(id => !available.some(instance =>
|
|
|
Number(instanceId(instance)) === id && canSelectInstance(instance, action, false)))) {
|
|
|
setPageStatus(t('vpc.status.selection_changed'), 'warning');
|
|
|
render();
|
|
|
return;
|
|
|
}
|
|
|
const requestKey = pendingBatchKey(vpc, action, ids);
|
|
|
state.mutatingBatches.add(key);
|
|
|
setPageStatus(t('vpc.status.batch_submitting', { count: ids.length }));
|
|
|
render();
|
|
|
try {
|
|
|
const receipt = await api(`/api/v1/vpcs/${encodeURIComponent(key)}/ports/batch`, {
|
|
|
method: 'POST',
|
|
|
headers: { 'Idempotency-Key': requestKey },
|
|
|
body: { action, instance_ids: ids, confirm_restart: true },
|
|
|
expectedStatus: 202,
|
|
|
requireTaskReceipt: true,
|
|
|
});
|
|
|
clearPendingBatchKey(vpc, action);
|
|
|
const batch = receipt?.batch || {
|
|
|
task_id: receipt.task_id,
|
|
|
status_url: receipt.status_url,
|
|
|
vpc_key: key,
|
|
|
action,
|
|
|
state: attach ? 'routing' : 'ports',
|
|
|
total: ids.length,
|
|
|
succeeded: 0,
|
|
|
failed: 0,
|
|
|
};
|
|
|
state.membershipBatches = state.membershipBatches
|
|
|
.filter(item => String(item?.vpc_key || '') !== key);
|
|
|
state.membershipBatches.push(batch);
|
|
|
selectionForVpc(vpc, action).clear();
|
|
|
observeBatch(batch, true);
|
|
|
if (currentVpc() && vpcKey(currentVpc()) === key) {
|
|
|
window.location.href = new URL(membersHref(vpc), window.location.href).href;
|
|
|
}
|
|
|
setPageStatus(t('vpc.status.batch_accepted', { count: ids.length }));
|
|
|
toast(t('vpc.toast.batch_accepted.body'), 'success',
|
|
|
t('vpc.toast.batch_accepted.title'));
|
|
|
await load(true);
|
|
|
} catch (error) {
|
|
|
await load(true);
|
|
|
if (transportUncertain(error)) {
|
|
|
setPageStatus(t('vpc.error.batch_uncertain'), 'warning');
|
|
|
} else {
|
|
|
clearPendingBatchKey(vpc, action);
|
|
|
setPageStatus(t('vpc.error.batch_submit'), 'error');
|
|
|
}
|
|
|
} finally {
|
|
|
state.mutatingBatches.delete(key);
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function cancelMembershipBatch(vpc, batch) {
|
|
|
const key = vpcKey(vpc);
|
|
|
const batchKey = String(batch?.batch_key || '');
|
|
|
if (!key || !/^[a-f0-9]{32}$/.test(batchKey)
|
|
|
|| batch?.can_cancel !== true || state.mutatingBatches.has(key)) return;
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('vpc.cancel.title'),
|
|
|
message: t('vpc.cancel.body'),
|
|
|
confirmText: t('vpc.cancel.confirm'),
|
|
|
tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed || state.mutatingBatches.has(key)) return;
|
|
|
state.mutatingBatches.add(key);
|
|
|
setPageStatus(t('vpc.status.canceling'));
|
|
|
render();
|
|
|
try {
|
|
|
const receipt = await api(
|
|
|
`/api/v1/vpcs/${encodeURIComponent(key)}/ports/batches/${encodeURIComponent(batchKey)}/cancel`,
|
|
|
{ method: 'POST', expectedStatus: 202, requireTaskReceipt: true }
|
|
|
);
|
|
|
const next = receipt?.batch || { ...batch, state: 'cleanup', can_cancel: false };
|
|
|
state.membershipBatches = state.membershipBatches
|
|
|
.filter(item => String(item?.batch_key || '') !== batchKey);
|
|
|
state.membershipBatches.push(next);
|
|
|
observeBatch(next, false);
|
|
|
setPageStatus(t('vpc.status.cancel_accepted'));
|
|
|
await load(true);
|
|
|
} catch (error) {
|
|
|
await load(true);
|
|
|
setPageStatus(t('vpc.error.cancel'), 'error');
|
|
|
} finally {
|
|
|
state.mutatingBatches.delete(key);
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function mutatePort(instance, vpc, requestedAction, options = {}) {
|
|
|
const id = instanceId(instance);
|
|
|
if (!id || state.mutatingInstances.has(id)) return { status: 'ignored' };
|
|
|
const action = portAction(instance);
|
|
|
const attach = requestedAction === 'attach';
|
|
|
if (attach !== ['attach', 'retry_attach'].includes(action)
|
|
|
|| (!attach && !['detach', 'retry_detach'].includes(action))) {
|
|
|
return { status: 'ignored' };
|
|
|
}
|
|
|
|
|
|
const confirmed = options.confirmed === true
|
|
|
|| await requestUserConfirmation({
|
|
|
title: t(attach ? 'vpc.port_confirm.attach_title' : 'vpc.port_confirm.detach_title'),
|
|
|
message: attach
|
|
|
? t('vpc.port_confirm.attach_body', { instance: instance.name, vpc: vpc.name })
|
|
|
: t('vpc.port_confirm.detach_body', { instance: instance.name }),
|
|
|
confirmText: t(attach
|
|
|
? 'vpc.port_confirm.attach_button' : 'vpc.port_confirm.detach_button'),
|
|
|
tone: attach ? 'default' : 'danger',
|
|
|
});
|
|
|
if (!confirmed) return { status: 'cancelled' };
|
|
|
|
|
|
const fingerprint = attach ? `attach:${vpc.vpc_key}`
|
|
|
: `detach:${String(instance?.port?.port_key || '')}`;
|
|
|
const key = pendingMutationKey(instance, fingerprint);
|
|
|
state.mutatingInstances.add(id);
|
|
|
setPageStatus(t('vpc.status.port_submitting'));
|
|
|
render();
|
|
|
try {
|
|
|
const receipt = await api(`/api/v1/vms/${encodeURIComponent(id)}/vpc`, {
|
|
|
method: attach ? 'PUT' : 'DELETE',
|
|
|
headers: { 'Idempotency-Key': key },
|
|
|
body: attach ? { vpc_key: vpc.vpc_key, confirm_restart: true }
|
|
|
: { confirm_restart: true },
|
|
|
expectedStatus: 202,
|
|
|
requireTaskReceipt: true,
|
|
|
});
|
|
|
clearPendingMutationKey(instance);
|
|
|
Object.assign(instance, {
|
|
|
active_task: receipt,
|
|
|
can_attach: false, can_detach: false,
|
|
|
can_retry_attach: false, can_retry_detach: false,
|
|
|
});
|
|
|
observeReceipt(instance, receipt, true);
|
|
|
setPageStatus(t('vpc.status.port_accepted'));
|
|
|
if (options.quiet !== true) {
|
|
|
toast(t('vpc.toast.port_accepted.body'), 'success',
|
|
|
t('vpc.toast.port_accepted.title'));
|
|
|
}
|
|
|
await load(true);
|
|
|
return { status: 'accepted' };
|
|
|
} catch (error) {
|
|
|
await load(true);
|
|
|
if (transportUncertain(error)) {
|
|
|
const message = t('vpc.error.port_uncertain');
|
|
|
setPageStatus(message, 'warning');
|
|
|
return { status: 'uncertain', message };
|
|
|
} else {
|
|
|
clearPendingMutationKey(instance);
|
|
|
const message = t('vpc.error.port_submit');
|
|
|
setPageStatus(message, 'error');
|
|
|
return { status: 'failed', message };
|
|
|
}
|
|
|
} finally {
|
|
|
state.mutatingInstances.delete(id);
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function createVpc(event) {
|
|
|
event.preventDefault();
|
|
|
if (state.creating) return;
|
|
|
const name = byId('cloud-vpc-name').value.trim();
|
|
|
const regionId = Number(byId('cloud-vpc-region').value);
|
|
|
const fingerprint = `${name}\0${regionId}`;
|
|
|
if (!name || !Number.isInteger(regionId) || regionId < 1) {
|
|
|
showError('cloud-vpc-create-error', t('vpc.error.create_fields'));
|
|
|
return;
|
|
|
}
|
|
|
if (!state.createKey || state.createFingerprint !== fingerprint) {
|
|
|
state.createKey = idempotencyKey();
|
|
|
state.createFingerprint = fingerprint;
|
|
|
}
|
|
|
state.creating = true;
|
|
|
showError('cloud-vpc-create-error', '');
|
|
|
render();
|
|
|
try {
|
|
|
const result = await api('/api/v1/vpcs', {
|
|
|
method: 'POST', expectedStatus: 201,
|
|
|
headers: { 'Idempotency-Key': state.createKey },
|
|
|
body: { name, region_id: regionId },
|
|
|
});
|
|
|
state.createKey = '';
|
|
|
state.createFingerprint = '';
|
|
|
byId('cloud-vpc-name').value = '';
|
|
|
const created = result?.vpc;
|
|
|
if (/^[a-f0-9]{32}$/.test(vpcKey(created))) {
|
|
|
if (!state.items.some(item => vpcKey(item) === vpcKey(created))) {
|
|
|
state.items.push(created);
|
|
|
state.used += 1;
|
|
|
}
|
|
|
// Keep the confirmed creation visible even if the following refresh fails.
|
|
|
if (pageRoute().page === 'create') window.location.href = new URL(membersHref(created, true), window.location.href).href;
|
|
|
}
|
|
|
await load(true);
|
|
|
toast(t('vpc.toast.created.body'), 'success', t('vpc.toast.created.title'));
|
|
|
} catch (error) {
|
|
|
showError('cloud-vpc-create-error', t('vpc.error.create'));
|
|
|
await load(true);
|
|
|
} finally {
|
|
|
state.creating = false;
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function removeVpc(vpc) {
|
|
|
const key = String(vpc?.vpc_key || '');
|
|
|
if (!key || state.mutatingVpcs.has(key) || vpc?.can_delete !== true) return;
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('vpc.delete.title'),
|
|
|
message: t('vpc.delete.body', { name: vpc.name, cidr: vpc.cidr }),
|
|
|
confirmText: t('vpc.delete.button'), tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed) return;
|
|
|
state.mutatingVpcs.add(key);
|
|
|
render();
|
|
|
try {
|
|
|
await api(`/api/v1/vpcs/${encodeURIComponent(key)}`, {
|
|
|
method: 'DELETE', expectedStatus: 200,
|
|
|
});
|
|
|
state.items = state.items.filter(item => vpcKey(item) !== key);
|
|
|
state.used = Math.max(0, state.used - 1);
|
|
|
if (pageRoute().key === key) window.location.href = new URL('/user/cloud/vpcs', window.location.href).href;
|
|
|
await load(true);
|
|
|
toast(t('vpc.toast.deleted.body'), 'success', t('vpc.toast.deleted.title'));
|
|
|
} catch (error) {
|
|
|
await load(true);
|
|
|
if (transportUncertain(error)) {
|
|
|
state.deleteUncertainVpcs.add(key);
|
|
|
setPageStatus(t('vpc.error.delete_uncertain'), 'warning');
|
|
|
} else {
|
|
|
setPageStatus(t('vpc.error.delete'), 'error');
|
|
|
}
|
|
|
} finally {
|
|
|
state.mutatingVpcs.delete(key);
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
export async function initialize() {
|
|
|
if (state.initialized) return;
|
|
|
state.initialized = true;
|
|
|
try {
|
|
|
const bootstrap = readBootstrap('cloud-vpcs-bootstrap');
|
|
|
if (!await initializeSession('vpcs', bootstrap?.user)) return;
|
|
|
state.userKey = String(bootstrap?.user?.id || bootstrap?.user?.user_id || 'unknown');
|
|
|
if (Array.isArray(bootstrap?.items) && Array.isArray(bootstrap?.instances)
|
|
|
&& Array.isArray(bootstrap?.regions)) {
|
|
|
apply(bootstrap);
|
|
|
setPageStatus();
|
|
|
} else {
|
|
|
await load();
|
|
|
}
|
|
|
byId('cloud-vpc-create-form')?.addEventListener('submit', createVpc);
|
|
|
byId('cloud-vpc-delete')?.addEventListener('click', () => {
|
|
|
const vpc = currentVpc();
|
|
|
if (vpc) void removeVpc(vpc);
|
|
|
});
|
|
|
bindBatchConfirmation();
|
|
|
window.addEventListener('hashchange', routeChanged);
|
|
|
window.addEventListener('pagehide', () => {
|
|
|
closeBatchConfirmation(false);
|
|
|
state.controller?.abort();
|
|
|
stopObservers('pagehide');
|
|
|
});
|
|
|
window.addEventListener('pageshow', event => {
|
|
|
if (event.persisted) void load(true);
|
|
|
});
|
|
|
} catch (error) {
|
|
|
showError('cloud-page-error', t('vpc.error.page'));
|
|
|
}
|
|
|
}
|