phase 2 rework

This commit is contained in:
admin_rb committed 2026-10-23 18:19:44 +02:00
1 parent 20054198f3
commit b397ea9256
44 files changed
+5528 -1377

No files matched your search

+432
View File
@@ -0,0 +1,432 @@
(() => {
'use strict';
const MAX_VISIBLE_LOG_BYTES = 64 * 1024;
const POLL_INTERVAL = 10_000;
const LOG_PREFIX = '[Earlier log output omitted]\n';
function validWorkerName(name) {
return typeof name === 'string' && /^[A-Za-z0-9][\w-]{0,63}$/.test(name) && name.toLowerCase() !== 'all';
}
function boundedLog(text) {
const encoder = new TextEncoder();
const encoded = encoder.encode(text);
if (encoded.length <= MAX_VISIBLE_LOG_BYTES) return text;
let start = encoded.length - (MAX_VISIBLE_LOG_BYTES - encoder.encode(LOG_PREFIX).length);
while (start < encoded.length && (encoded[start] & 0xc0) === 0x80) start++;
return LOG_PREFIX + new TextDecoder().decode(encoded.subarray(start));
}
function statusClass(status) {
if (['online', 'running'].includes(status)) return 'status-online';
if (['stopped', 'errored', 'offline'].includes(status)) return 'status-stopped';
return 'status-pending';
}
function startWorkerPage({ document, window, fetch, WebSocket, setTimeout, clearTimeout, AbortController }) {
const get = id => document.getElementById(id);
const list = get('process-list');
if (!list) return null;
const elements = {
output: get('control-output'), listState: get('worker-refresh-state'),
empty: get('workers-empty'), count: get('worker-counts'),
controls: get('control-centre'), placeholder: get('worker-placeholder'),
createForm: get('create-worker-form'), nameInput: get('worker-name'),
logs: get('logs'), follow: get('follow-logs'), connection: get('log-connection-state'),
reconnect: get('reconnect-logs'), refresh: get('refresh-list'),
quickAdd: get('btn-quick-add'),
};
const rows = new Map();
const records = new Map();
let selectedKey = null;
let commandInFlight = false;
let listRequest = null;
let pollTimer = null;
let socket = null;
let socketGeneration = 0;
let connectionTimer = null;
let connecting = false;
let disposed = false;
const keyFor = worker => `${worker.pm_id}:${worker.name}`;
const selected = () => selectedKey ? records.get(selectedKey) : null;
const string = value => value == null ? '—' : String(value);
function text(id, value) { get(id).textContent = string(value); }
function showResult(message, state = '') {
elements.output.textContent = message;
elements.output.hidden = !message;
elements.output.classList.toggle('is-error', state === 'error');
elements.output.classList.toggle('is-success', state === 'success');
}
function updateButtons() {
const worker = selected();
const online = worker && ['online', 'running', 'launching'].includes(worker.status);
get('btn-create').disabled = commandInFlight;
elements.quickAdd.disabled = commandInFlight;
elements.nameInput.disabled = commandInFlight;
get('clear-selection').disabled = commandInFlight;
elements.refresh.disabled = commandInFlight || !!listRequest;
for (const cmd of ['start', 'stop', 'restart', 'delete']) {
get(`btn-${cmd}`).disabled = commandInFlight || !worker
|| (cmd === 'start' && online) || (cmd === 'stop' && worker.status === 'stopped');
}
for (const [key, row] of rows) {
row.disabled = commandInFlight || !validWorkerName(records.get(key)?.name);
row.classList.toggle('is-selected', key === selectedKey);
row.setAttribute('aria-pressed', String(key === selectedKey));
}
elements.reconnect.disabled = !worker || connecting;
}
function populateControls() {
const worker = selected();
elements.controls.hidden = !worker;
elements.placeholder.hidden = !!worker;
if (worker) {
text('cc-name', worker.name);
text('cc-sub', `PM2 ${worker.pm_id} · ${worker.status}`);
for (const [id, field] of Object.entries({
'detail-pmid': 'pm_id', 'detail-pid': 'pid', 'detail-status': 'status',
'detail-cpu': 'cpu', 'detail-mem': 'memoryMB', 'detail-uptime': 'uptime', 'detail-exec': 'execPath',
})) text(id, worker[field]);
}
updateButtons();
}
function appendLog(message) {
const value = String(message ?? '');
const line = `[${new Date().toLocaleTimeString()}] ${value}${value.endsWith('\n') ? '' : '\n'}`;
elements.logs.textContent = boundedLog(elements.logs.textContent + line);
if (elements.follow.checked) elements.logs.scrollTop = elements.logs.scrollHeight;
}
function closeSocket() {
socketGeneration++;
clearTimeout(connectionTimer);
connectionTimer = null;
connecting = false;
const previous = socket;
socket = null;
if (!previous) return;
try {
if (previous.readyState === WebSocket.OPEN) previous.send(JSON.stringify({ type: 'stop-logs' }));
previous.close();
} catch { /* The old connection is already closed. */ }
}
function openLogs(clear = false) {
closeSocket();
const worker = selected();
if (!worker || disposed) return;
const generation = socketGeneration;
const workerKey = selectedKey;
if (clear) elements.logs.textContent = `Connecting to ${worker.name}…\n`;
connecting = true;
elements.connection.textContent = 'Connecting…';
updateButtons();
let current;
try {
current = new WebSocket(`${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}`);
} catch {
connecting = false;
elements.connection.textContent = 'Log connection unavailable';
updateButtons();
return;
}
socket = current;
const active = () => !disposed && socket === current && socketGeneration === generation && selectedKey === workerKey;
connectionTimer = setTimeout(() => {
if (!active() || current.readyState === WebSocket.OPEN) return;
closeSocket();
elements.connection.textContent = 'Connection timed out — reconnect to try again';
updateButtons();
}, 10_000);
current.addEventListener('open', () => {
if (!active()) return;
clearTimeout(connectionTimer);
connecting = false;
try {
current.send(JSON.stringify({ type: 'logs', name: worker.name }));
elements.connection.textContent = `Connected to ${worker.name}`;
} catch {
elements.connection.textContent = 'Log request could not be sent — reconnect to try again';
}
updateButtons();
});
current.addEventListener('message', event => {
if (!active()) return;
let payload;
try { payload = JSON.parse(event.data); } catch { return; }
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return;
if (['stdout', 'stderr'].includes(payload.type)) appendLog(payload.data || '');
else if (payload.type === 'info') appendLog(`[info] ${payload.message || ''}`);
else if (payload.type === 'error') {
elements.connection.textContent = 'Log stream unavailable — reconnect to try again';
appendLog(`[error] ${payload.error || 'The log stream failed.'}`);
} else if (payload.type === 'close') {
elements.connection.textContent = 'Log stream ended — reconnect to continue';
appendLog('[Log stream ended]');
}
});
const disconnected = () => {
if (!active()) return;
clearTimeout(connectionTimer);
connecting = false;
elements.connection.textContent = 'Disconnected — reconnect to continue';
updateButtons();
};
current.addEventListener('close', disconnected);
current.addEventListener('error', disconnected);
}
function clearSelection() {
selectedKey = null;
closeSocket();
elements.connection.textContent = 'No worker selected';
elements.logs.textContent = 'Select a worker to view its logs.';
populateControls();
}
function selectWorker(key) {
if (commandInFlight || !records.has(key) || !validWorkerName(records.get(key).name)) return;
if (selectedKey === key) return;
selectedKey = key;
populateControls();
openLogs(true);
}
function makeElement(tag, className, value) {
const node = document.createElement(tag);
if (className) node.className = className;
if (value !== undefined) node.textContent = string(value);
return node;
}
function createRow(worker) {
const item = makeElement('li', 'worker-list-item');
const row = makeElement('button', 'worker-row');
row.type = 'button';
const heading = makeElement('span', 'worker-row-heading');
heading.append(makeElement('strong', 'worker-name'));
const badge = makeElement('span', 'badge');
badge.dataset.workerStatus = '';
heading.append(badge);
const meta = makeElement('span', 'worker-row-meta');
meta.dataset.workerMetrics = '';
row.append(heading, meta);
item.append(row);
row.dataset.key = keyFor(worker);
row.addEventListener('click', () => selectWorker(row.dataset.key));
list.append(item);
return row;
}
function renderWorkers(workers) {
const present = new Set();
for (const worker of workers) {
const key = keyFor(worker);
present.add(key);
records.set(key, worker);
let row = rows.get(key);
if (!row) { row = createRow(worker); rows.set(key, row); }
row.dataset.name = string(worker.name);
row.querySelector('.worker-name').textContent = string(worker.name);
const badge = row.querySelector('[data-worker-status]');
badge.textContent = string(worker.status);
badge.className = `badge ${statusClass(worker.status)}`;
row.querySelector('[data-worker-metrics]').textContent = `CPU ${string(worker.cpu)} · ${string(worker.memoryMB)} · ${string(worker.uptime)}`;
}
for (const [key, row] of rows) {
if (!present.has(key)) {
row.parentElement.remove();
rows.delete(key);
records.delete(key);
}
}
elements.empty.hidden = workers.length > 0;
const online = workers.filter(worker => ['online', 'running'].includes(worker.status)).length;
elements.count.textContent = `${online} online · ${workers.length} total`;
if (selectedKey && !records.has(selectedKey)) {
clearSelection();
if (!commandInFlight) showResult('The selected worker is no longer available. Choose another worker.');
}
populateControls();
}
async function requestJson(url, options = {}, timeout = 12_000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { ...options, cache: 'no-store', signal: controller.signal });
const result = await response.json();
return { response, result };
} finally { clearTimeout(timer); }
}
function schedulePoll() {
clearTimeout(pollTimer);
if (!disposed && !document.hidden) {
pollTimer = setTimeout(async () => {
if (!commandInFlight) await refreshList();
schedulePoll();
}, POLL_INTERVAL);
}
}
function refreshList() {
if (disposed) return Promise.resolve(false);
if (listRequest) return listRequest;
listRequest = (async () => {
try {
const { response, result } = await requestJson('/pm2/list-json');
if (!response.ok || !result?.ok || !Array.isArray(result.processes)) throw new Error('List unavailable');
if (disposed) return false;
renderWorkers(result.processes);
elements.listState.textContent = `Updated ${new Date().toLocaleTimeString()}`;
return true;
} catch {
if (!disposed) elements.listState.textContent = 'Could not refresh workers. Showing the last available list.';
return false;
} finally {
listRequest = null;
if (!disposed) updateButtons();
}
})();
updateButtons();
return listRequest;
}
async function execCommand(command, name) {
const automatic = command === 'quick-add';
const creating = automatic || command === 'create';
if (disposed || commandInFlight || (!automatic && !validWorkerName(name))) return false;
commandInFlight = true;
updateButtons();
showResult(automatic ? 'Creating the next numbered worker…' : `${creating ? 'Creating' : 'Updating'} ${name}…`);
try {
// Let any earlier read finish before mutating so stale list responses
// cannot replace the result of this command.
if (listRequest) await listRequest;
if (disposed) return false;
const { response, result } = await requestJson(automatic ? '/pm2/quick-add' : '/pm2/command', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(automatic ? {} : { cmd: command, name }),
}, automatic ? 45_000 : 15_000);
if (disposed) return false;
if (!response.ok || !result?.ok) {
showResult(String(result?.error || result?.message || 'The worker command could not be completed.').slice(0, 500), 'error');
return false;
}
if (automatic) {
if (!validWorkerName(result.name) || !/^proxer-worker-\d+$/.test(result.name)) {
showResult('The worker command completed, but its name could not be confirmed. Refresh the worker list before trying again.', 'error');
await refreshList();
return false;
}
name = result.name;
}
showResult(command === 'delete' ? `${name} was deleted.`
: creating ? `${name} was created and started.` : `${name}: ${command} completed.`, 'success');
const refreshed = await refreshList();
if (!refreshed) showResult('The command completed, but the worker list could not be refreshed. Refresh it before your next action.', 'error');
if (creating && refreshed) {
const created = [...records.entries()].find(([, worker]) => worker.name === name);
if (created) {
selectedKey = created[0];
populateControls();
openLogs(true);
}
if (!automatic) elements.nameInput.value = '';
}
return true;
} catch {
if (!disposed) showResult('Could not confirm the worker command. Refresh the worker list before trying again.', 'error');
return false;
} finally {
commandInFlight = false;
if (!disposed) updateButtons();
}
}
for (const row of list.querySelectorAll('.worker-row')) {
const data = row.dataset;
const worker = { name: data.name, pm_id: data.pmid, pid: data.pid, status: data.status,
cpu: data.cpu, memoryMB: data.memory, uptime: data.uptime, execPath: data.exec };
const key = keyFor(worker);
records.set(key, worker);
rows.set(key, row);
row.addEventListener('click', () => selectWorker(key));
}
elements.createForm.addEventListener('submit', async event => {
event.preventDefault();
if (commandInFlight) return;
const name = elements.nameInput.value.trim();
elements.nameInput.value = name;
const inUse = [...records.values()].some(worker => worker.name === name);
elements.nameInput.setCustomValidity(!validWorkerName(name)
? 'Use 1–64 letters, numbers, underscores or hyphens, starting with a letter or number. “all” is reserved.'
: inUse ? 'A worker with that name already exists.' : '');
if (!elements.createForm.reportValidity()) return;
await execCommand('create', name);
});
elements.nameInput.addEventListener('input', () => elements.nameInput.setCustomValidity(''));
elements.quickAdd.addEventListener('click', () => execCommand('quick-add'));
const confirmations = {
stop: name => `Stop ${name}? An active download may be interrupted.`,
restart: name => `Restart ${name}? An active download may be interrupted.`,
delete: name => `Delete ${name} from the worker list? This stops the worker and may interrupt an active download. Downloaded files are kept.`,
};
for (const command of ['start', 'stop', 'restart', 'delete']) {
get(`btn-${command}`).addEventListener('click', () => {
const worker = selected();
if (!worker || commandInFlight) return;
if (confirmations[command] && !window.confirm(confirmations[command](worker.name))) return;
execCommand(command, worker.name);
});
}
get('clear-selection').addEventListener('click', () => { if (!commandInFlight) clearSelection(); });
elements.refresh.addEventListener('click', () => { refreshList(); });
elements.reconnect.addEventListener('click', () => openLogs(false));
get('clear-logs').addEventListener('click', () => { elements.logs.textContent = ''; });
elements.follow.addEventListener('change', () => {
if (elements.follow.checked) elements.logs.scrollTop = elements.logs.scrollHeight;
});
elements.logs.addEventListener('scroll', () => {
if (elements.logs.scrollHeight - elements.logs.scrollTop - elements.logs.clientHeight > 40) elements.follow.checked = false;
});
document.addEventListener('visibilitychange', () => {
clearTimeout(pollTimer);
if (!document.hidden) {
if (!commandInFlight) refreshList();
schedulePoll();
}
});
function dispose() {
disposed = true;
clearTimeout(pollTimer);
closeSocket();
}
window.addEventListener('pagehide', dispose);
window.addEventListener('pageshow', event => {
if (event.persisted) window.location.reload();
});
populateControls();
schedulePoll();
return { refreshList, execCommand, selectWorker, clearSelection, appendLog, dispose };
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = { startWorkerPage, validWorkerName, boundedLog, statusClass, MAX_VISIBLE_LOG_BYTES };
}
if (typeof document !== 'undefined' && document.getElementById('process-list')) {
startWorkerPage({ document, window, fetch: window.fetch.bind(window), WebSocket: window.WebSocket,
setTimeout: window.setTimeout.bind(window), clearTimeout: window.clearTimeout.bind(window),
AbortController: window.AbortController });
}
})();