rob-revisited/ide/ui/js/messenger.js

342 lines
22 KiB
JavaScript

// The Messenger window (Symfony Messenger): the workers, the queues, the transports and routing of messenger.yaml, the messages
// and their handlers. Workers: `messenger:consume <transports> --limit --time-limit --memory-limit -vv` started from here, in the
// site's container (or locally: the Console window's runner), several at once, their live output, stop / restart, restarted
// when they end if asked. Queues: messages waiting per transport (messenger:stats), the failed ones (messenger:failed:show:
// retry / remove one or all), the Scheduler's recurring messages (debug:scheduler), messenger:stop-workers. Transports: dsn
// (with the value .env gives it), retry strategy, failure transports, routing, written as a diff. Messages: each one's handlers
// and transports; a new message with its handler and its routing, a handler added to a message.
// The PHP side: ide/src/Symfony/MessengerCommands.php (MessengerConfig, MessengerCode, MessengerWorkers).
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t, timeAgo } from './ui.js';
import { ChangesView, fileLink, symfonyStyles } from './symfony-events.js';
const short = (cls) => String(cls || '').split('\\').pop();
export class MessengerPanel {
constructor(app) {
this.app = app;
this.node = el('div.sfc-view.sft-view');
this.tab = prefs.get('sfMessengerTab', 'workers');
this.config = null;
this.workers = [];
this.logs = new Map(); // worker id => its output
this.selected = null; // the worker whose output is shown
this.stats = null; this.failed = null; this.scheduler = null;
this.busy = false;
this.start = prefs.get('sfMessengerStart', { transports: [], limit: '', timeLimit: '3600', memoryLimit: '128M', autoRestart: true });
this.newMessage = { className: 'App\\Message\\', properties: [{ name: '', type: '' }], transports: [], attribute: false, handler: true, handlerClass: '', bus: '', fromTransport: '' };
this.handlerFor = null; // a message getting a handler: {message, className}
this.changes = new ChangesView(app, 'messenger.apply', () => this.load());
symfonyStyles();
backend.on('messenger.worker', (w) => {
if (w.removed) this.workers = this.workers.filter((x) => x.id !== w.id);
else { const i = this.workers.findIndex((x) => x.id === w.id); if (i < 0) this.workers.push(w); else this.workers[i] = w; }
if (this.tab === 'workers') this.render();
});
backend.on('messenger.output', ({ id, chunk }) => {
this.logs.set(id, ((this.logs.get(id) || '') + chunk).slice(-60000));
if (id === this.selected) {
const pre = this.node.querySelector('.sft-log');
if (pre) { const end = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 20; pre.textContent = this.logs.get(id); if (end) pre.scrollTop = pre.scrollHeight; }
}
});
this.render();
}
title() { return 'Messenger'; }
actions() {
return [el('button', { title: t('Refresh'), onclick: () => this.refresh() }, icon('refresh'))];
}
shown() { if (!this.config && !this.busy) this.load(); }
async load() {
this.busy = true; this.render();
try {
this.config = await backend.invoke('messenger.config', {});
this.workers = this.config.workers || [];
if (!this.start.transports.length) this.start.transports = this.config.transports.filter((x) => x.name !== this.config.failure_transport && !x.dsn.startsWith('sync')).map((x) => x.name).slice(0, 1);
} catch (e) { notify(e.message, 'error', { title: 'Messenger' }); }
this.busy = false;
this.render();
}
refresh() { if (this.tab === 'queues') this.loadQueues(); else this.load(); }
setTab(tab) { this.tab = tab; prefs.set('sfMessengerTab', tab); this.render(); if (tab === 'queues' && !this.stats) this.loadQueues(); }
/** a console command's answer: its error shown when it failed */
failedRun(r, title) {
if (r.code === 0) return false;
notify(r.output.trim().slice(-600) || `exit code ${r.code}`, 'error', { title });
return true;
}
async loadQueues() {
this.busy = true; this.render();
const [stats, failed, scheduler] = await Promise.all([
backend.invoke('messenger.stats', {}).catch((e) => ({ code: 1, output: e.message, transports: {} })),
backend.invoke('messenger.failed', {}).catch((e) => ({ code: 1, output: e.message, messages: [] })),
this.config?.scheduler ? backend.invoke('messenger.scheduler', {}).catch((e) => ({ code: 1, output: e.message, installed: true, schedules: [] })) : Promise.resolve({ installed: false }),
]);
this.stats = stats; this.failed = failed; this.scheduler = scheduler;
this.busy = false;
this.render();
}
async run(command, payload, title) {
this.busy = true; this.render();
try {
const r = await backend.invoke(command, payload);
if (!this.failedRun(r, title)) notify(r.output.trim().split('\n').filter(Boolean).pop() || t('Done'), 'info', { title });
} catch (e) { notify(e.message, 'error', { title }); }
this.busy = false;
if (this.tab === 'queues') this.loadQueues(); else this.render();
}
// workers ---------------------------------------------------------------------------------------------------------
async startWorker() {
prefs.set('sfMessengerStart', this.start);
try {
const w = await backend.invoke('messenger.start', { ...this.start });
if (!this.workers.some((x) => x.id === w.id)) this.workers.push(w);
this.selected = w.id;
this.render();
} catch (e) { notify(e.message, 'error', { title: t('Start a worker') }); }
}
async worker(command, id, extra = {}) {
try { await backend.invoke(command, { id, ...extra }); } catch (e) { notify(e.message, 'error'); }
}
async showLog(id) {
this.selected = id;
if (!this.logs.has(id)) {
const r = await backend.invoke('messenger.log', { id }).catch(() => ({ log: '' }));
this.logs.set(id, r.log);
}
this.render();
const pre = this.node.querySelector('.sft-log');
if (pre) pre.scrollTop = pre.scrollHeight;
}
// drawing -----------------------------------------------------------------------------------------------------------
render() {
clear(this.node);
const tabs = [['workers', 'Workers'], ['queues', 'Queues'], ['transports', 'Transports'], ['messages', 'Messages']];
this.node.append(el('div.cryo-tabs', {}, ...tabs.map(([id, label]) => el('button' + (this.tab === id ? '.on' : ''), { onclick: () => this.setTab(id) }, t(label))),
this.busy ? el('span.sfc-busy', {}, '…') : null));
if (!this.config) { this.node.append(el('div.prof-empty', {}, el('p', {}, this.busy ? t('Reading the project…') : ''))); return; }
if (this.config.error) this.node.append(el('pre.sfc-error', {}, `${this.config.file}: ${this.config.error}`));
const body = el('div.sft-body');
if (this.tab === 'workers') body.append(this.renderWorkers());
else if (this.tab === 'queues') body.append(this.renderQueues());
else if (this.tab === 'transports') body.append(this.renderTransports());
else body.append(this.renderMessages());
body.append(this.changes.node);
this.node.append(body);
}
transportChecks(selected, onChange) {
return el('span.sft-checks', {}, ...(this.config?.transports || []).map((tr) => {
const box = el('input', { type: 'checkbox', checked: selected.includes(tr.name) });
box.addEventListener('change', () => onChange(tr.name, box.checked));
return el('label.sft-check', { title: tr.value || tr.dsn }, box, tr.name);
}));
}
renderWorkers() {
const s = this.start;
const num = (key, placeholder, title) => {
const i = el('input.input.sft-num', { type: 'text', value: s[key] || '', placeholder, title, spellcheck: false });
i.addEventListener('input', () => { s[key] = i.value.trim(); });
return i;
};
const auto = el('input', { type: 'checkbox', checked: !!s.autoRestart });
auto.addEventListener('change', () => { s.autoRestart = auto.checked; });
const form = el('div.sft-card', {},
el('div.sft-row', {}, el('span.sfc-label', {}, t('Transports')),
this.transportChecks(s.transports, (name, on) => { s.transports = on ? [...s.transports, name] : s.transports.filter((x) => x !== name); })),
el('div.sft-row', {},
el('span.sfc-hint', {}, '--limit'), num('limit', '∞', t('Stop after this many messages')),
el('span.sfc-hint', {}, '--time-limit'), num('timeLimit', 's', t('Stop after this many seconds')),
el('span.sfc-hint', {}, '--memory-limit'), num('memoryLimit', '128M', t('Stop above this memory')),
el('label.sft-check', { title: t('Start it again when it ends (not after 3 quick failures)') }, auto, t('Restart when it ends'))),
el('div.sft-row', {},
el('button.btn.primary', { onclick: () => this.startWorker() }, icon('play'), t('Start a worker')),
el('button.btn', { title: 'bin/console messenger:stop-workers', onclick: () => this.run('messenger.stopWorkers', {}, 'messenger:stop-workers') }, icon('stop'), t('Stop every worker')),
el('button.btn', { title: 'bin/console messenger:setup-transports', onclick: () => this.run('messenger.setupTransports', {}, 'messenger:setup-transports') }, t('Set up the transports'))));
const list = el('div.sft-workers');
if (!this.workers.length) list.append(el('p.pub-faint', {}, t('No worker started from the IDE.')));
const states = { starting: t('starting'), running: t('running'), restarting: t('restarting'), stopping: t('stopping'), stopped: t('stopped'), failed: t('failed') };
const where = { container: t('in the site\'s container'), docker: t('in a temporary container'), local: t('with the PHP of this computer') };
for (const w of this.workers) {
const running = ['running', 'starting', 'restarting', 'stopping'].includes(w.state);
const auto = el('input', { type: 'checkbox', checked: !!w.autoRestart, title: t('Restart when it ends') });
auto.addEventListener('change', () => this.worker('messenger.autoRestart', w.id, { on: auto.checked }));
list.append(el('div.sft-worker' + (w.id === this.selected ? '.on' : ''), { onclick: (e) => { if (!e.target.closest('button, input')) this.showLog(w.id); } },
el('span.sft-state.' + w.state, { title: w.state }),
el('span.sft-worker-line', {}, (w.settings?.transports || []).join(', ')),
el('span.sfc-hint', {}, [states[w.state] || w.state, where[w.where] || '', w.started ? timeAgo(w.started) : '',
w.restarts ? t('{n} restarts', { n: w.restarts }) : '', w.code !== null && w.code !== undefined && !running ? t('code {code}', { code: w.code }) : ''].filter(Boolean).join(' · ')),
el('label.sft-check', {}, auto, t('auto')),
running ? el('button.btn.small', { onclick: () => this.worker('messenger.stop', w.id) }, icon('stop'), t('Stop')) : null,
el('button.btn.small', { onclick: () => this.worker('messenger.restart', w.id) }, icon('refresh'), running ? t('Restart') : t('Start')),
!running ? el('button.sfc-star', { title: t('Remove'), onclick: () => this.worker('messenger.remove', w.id) }, icon('trash')) : null));
}
const sel = this.workers.find((w) => w.id === this.selected);
return el('div', {}, form, list,
sel ? el('div.sft-logbox', {}, el('div.sft-row', {}, el('span.sfc-name', {}, sel.line)), el('pre.sft-log', {}, this.logs.get(sel.id) || '')) : null);
}
renderQueues() {
const box = el('div');
const st = this.stats;
box.append(el('h4', {}, t('Messages waiting')));
if (!st) box.append(el('p.pub-faint', {}, t('Reading the queues…')));
else if (st.code !== 0 && !Object.keys(st.transports || {}).length) box.append(el('pre.sfc-error', {}, st.output.trim().slice(-800)));
else {
const max = Math.max(1, ...Object.values(st.transports).map((n) => n || 0));
box.append(el('div.sft-stats', {}, ...Object.entries(st.transports).map(([name, n]) => el('div.sft-stat', {},
el('span.sfc-name', {}, name), el('span.sft-bar', {}, el('span', { style: `width:${n === null ? 0 : Math.round((n / max) * 100)}%` })),
el('span.sft-count', {}, n === null ? t('not countable') : String(n))))));
}
const fl = this.failed;
box.append(el('h4', {}, t('Failed messages'), fl?.messages?.length ? el('span.sfc-count', {}, String(fl.messages.length)) : null));
if (fl && fl.code !== 0 && !fl.messages?.length) box.append(el('pre.sfc-error', {}, fl.output.trim().slice(-800)));
else if (fl && !fl.messages.length) box.append(el('p.pub-faint', {}, t('No failed messages.')));
else if (fl) {
box.append(el('div.sft-row', {},
el('button.btn.small', { onclick: () => this.run('messenger.failedAction', { action: 'retry', ids: [] }, 'messenger:failed:retry') }, t('Retry all')),
el('button.btn.small', { onclick: () => this.run('messenger.failedAction', { action: 'remove', ids: [] }, 'messenger:failed:remove') }, icon('trash'), t('Remove all'))));
box.append(el('table.sft-table', {}, el('tr', {}, ...['Id', t('Message'), t('Failed at'), t('Error'), ''].map((h) => el('th', {}, h))),
...fl.messages.map((m) => el('tr', {}, el('td', {}, m.id), el('td.sfc-name', { title: m.class }, short(m.class)), el('td', {}, m.failedAt), el('td.sft-err', {}, m.error),
el('td', {}, el('button.btn.small', { onclick: () => this.run('messenger.failedAction', { action: 'retry', ids: [m.id] }, 'messenger:failed:retry') }, t('Retry')),
el('button.sfc-star', { title: t('Remove'), onclick: () => this.run('messenger.failedAction', { action: 'remove', ids: [m.id] }, 'messenger:failed:remove') }, icon('trash')))))));
}
if (this.scheduler?.installed) {
box.append(el('h4', {}, 'Scheduler'));
const sc = this.scheduler;
if (sc.code !== 0 && !sc.schedules?.length) box.append(el('pre.sfc-error', {}, sc.output.trim().slice(-800)));
for (const s of sc.schedules || []) {
const cols = Object.keys(s.messages[0] || {});
box.append(el('div.sfc-group-title', {}, s.name),
s.messages.length ? el('table.sft-table', {}, el('tr', {}, ...cols.map((c) => el('th', {}, c))), ...s.messages.map((m) => el('tr', {}, ...cols.map((c) => el('td', {}, m[c])))))
: el('p.pub-faint', {}, t('No recurring message.')));
}
}
return box;
}
renderTransports() {
const c = this.config;
const model = this.model ??= JSON.parse(JSON.stringify({ transports: c.transports, failure_transport: c.failure_transport || '', routing: c.routing }));
const names = model.transports.map((x) => x.name).filter(Boolean);
const input = (obj, key, attrs = {}) => {
const i = el('input.input', { type: 'text', value: obj[key] ?? '', spellcheck: false, ...attrs });
i.addEventListener('input', () => { obj[key] = i.value; });
return i;
};
const select = (obj, key, options) => el('select.input', { onchange: (e) => { obj[key] = e.target.value; } },
el('option', { value: '' }, '—'), ...options.map((o) => el('option', { value: o, selected: obj[key] === o }, o)));
const box = el('div', {}, el('p.sfc-hint', {}, fileLink(this.app, c.file, 1, c.file)));
box.append(el('label.sfc-field', {}, el('span.sfc-label', {}, t('Failure transport')), select(model, 'failure_transport', names)));
box.append(el('h4', {}, t('Transports')));
for (const [i, tr] of model.transports.entries()) {
tr.retry ??= {};
box.append(el('div.sft-card', {},
el('div.sft-row', {}, input(tr, 'name', { placeholder: t('name'), class: 'input sft-name' }), input(tr, 'dsn', { placeholder: 'doctrine://default', class: 'input sft-grow' }),
el('button.sfc-star', { title: t('Remove'), onclick: () => { model.transports.splice(i, 1); this.render(); } }, icon('trash'))),
tr.env ? el('div.sfc-hint', {}, `${tr.env} = ${tr.value ?? t('(not set in .env)')}`) : null,
el('div.sft-row', {}, el('span.sfc-hint', {}, t('Retry:')),
...['max_retries', 'delay', 'multiplier', 'max_delay'].map((k) => el('label.sft-check', {}, el('span.sfc-hint', {}, k), input(tr.retry, k, { class: 'input sft-num' }))),
el('span.sfc-hint', {}, t('failure transport')), select(tr, 'failure_transport', names.filter((n) => n !== tr.name)))));
}
box.append(el('button.btn.small', { onclick: () => { model.transports.push({ name: '', dsn: '', retry: {} }); this.render(); } }, icon('plus'), t('Transport')));
box.append(el('h4', {}, t('Routing')));
const messages = (c.messages || []).map((m) => m.class);
const listId = 'sft-msgs';
box.append(el('datalist', { id: listId }, ...messages.map((m) => el('option', { value: m }))));
for (const [i, r] of model.routing.entries()) {
box.append(el('div.sft-row', {}, input(r, 'message', { list: listId, class: 'input sft-grow' }),
this.transportChecks(r.transports, (name, on) => { r.transports = on ? [...r.transports, name] : r.transports.filter((x) => x !== name); }),
el('button.sfc-star', { title: t('Remove'), onclick: () => { model.routing.splice(i, 1); this.render(); } }, icon('trash'))));
}
box.append(el('div.sft-row', {},
el('button.btn.small', { onclick: () => { model.routing.push({ message: '', transports: [] }); this.render(); } }, icon('plus'), t('Route')),
el('button.btn.primary', { onclick: () => this.preview({ action: 'config', model }) }, t('Preview messenger.yaml')),
el('button.btn', { onclick: () => { this.model = null; this.render(); } }, t('Undo the changes'))));
return box;
}
async preview(payload) {
try {
const r = await backend.invoke('messenger.preview', payload);
if (!r.changes.length) { notify(t('Nothing to change'), 'info'); return; }
this.changes.show(r.changes);
this.model = null;
} catch (e) { notify(e.message, 'error'); }
}
renderMessages() {
const c = this.config;
const box = el('div');
const field = (label, input, hint) => el('label.sfc-field', {}, el('span.sfc-label', {}, label), input, hint ? el('span.sfc-hint', {}, hint) : null);
const input = (obj, key, attrs = {}) => {
const i = el('input.input', { type: 'text', value: obj[key] ?? '', spellcheck: false, ...attrs });
i.addEventListener('input', () => { obj[key] = i.value; });
return i;
};
for (const m of c.messages || []) {
const row = el('div.sft-card', {},
el('div.sft-row', {}, m.file ? fileLink(this.app, m.file, m.line, short(m.class)) : el('span.sfc-name', { title: m.class }, short(m.class)),
el('span.sfc-hint', { title: m.class }, m.class),
el('span.sft-pill', { title: m.via ? t('routed through {class}', { class: m.via }) : '' }, m.transports.length ? '→ ' + m.transports.join(', ') : t('sync (not routed)'))),
...m.handlers.map((h) => el('div.sft-line', {}, '↳ ', fileLink(this.app, h.file, h.line, `${short(h.class)}::${h.method}()`),
h.bus ? el('span.sfc-hint', {}, ` bus: ${h.bus}`) : null, h.fromTransport ? el('span.sfc-hint', {}, ` fromTransport: ${h.fromTransport}`) : null)),
!m.handlers.length && m.project ? el('div.sfc-hint.sft-warn', {}, t('No handler: dispatching it fails (or it waits in its transport).')) : null);
if (m.project) {
if (this.handlerFor?.message === m.class) {
const h = this.handlerFor;
row.append(field(t('Handler class'), input(h, 'className')), field('bus', input(h, 'bus', { placeholder: c.default_bus || '' }), t('optional')),
field('fromTransport', input(h, 'fromTransport'), t('optional')),
el('div.sft-row', {}, el('button.btn.primary', { onclick: () => this.preview({ action: 'handler', message: m.class, class: h.className, bus: h.bus, fromTransport: h.fromTransport }) }, t('Preview the code')),
el('button.btn', { onclick: () => { this.handlerFor = null; this.render(); } }, t('Cancel'))));
} else {
row.append(el('div.sft-row', {}, el('button.btn.small', { onclick: () => { this.handlerFor = { message: m.class, className: `App\\MessageHandler\\${short(m.class)}Handler`, bus: '', fromTransport: '' }; this.render(); } },
icon('plus'), t('Handler'))));
}
}
box.append(row);
}
if (!(c.messages || []).length) box.append(el('p.pub-faint', {}, t('No message yet.')));
const n = this.newMessage;
const props = el('div.sft-props', {}, ...n.properties.map((p, i) => el('div.sft-row', {},
input(p, 'name', { placeholder: t('name') }), input(p, 'type', { placeholder: 'int, string…' }),
el('button.sfc-star', { title: t('Remove'), onclick: () => { n.properties.splice(i, 1); this.render(); } }, icon('close')))),
el('button.btn.small', { onclick: () => { n.properties.push({ name: '', type: '' }); this.render(); } }, icon('plus'), t('Property')));
const handler = el('input', { type: 'checkbox', checked: n.handler });
handler.addEventListener('change', () => { n.handler = handler.checked; this.render(); });
const attr = el('input', { type: 'checkbox', checked: n.attribute, disabled: !c.asMessage });
attr.addEventListener('change', () => { n.attribute = attr.checked; });
box.append(el('h4', {}, t('New message')),
field(t('Class'), input(n, 'className')),
el('div.sfc-hint', {}, t('Properties')), props,
field(t('Transports'), this.transportChecks(n.transports, (name, on) => { n.transports = on ? [...n.transports, name] : n.transports.filter((x) => x !== name); }), t('none: handled at once (sync)')),
el('label.sft-check', {}, attr, t('Route it with #[AsMessage] (else in messenger.yaml)')),
el('label.sft-check', {}, handler, t('With its handler')),
n.handler ? field(t('Handler class'), input(n, 'handlerClass', { placeholder: `App\\MessageHandler\\${short(n.className) || 'X'}Handler` })) : null,
el('div.sfc-run', {}, el('button.btn.primary', { onclick: () => this.previewMessage() }, t('Preview the code'))));
return box;
}
previewMessage() {
const n = this.newMessage;
const handlerClass = n.handlerClass.trim() || `App\\MessageHandler\\${short(n.className)}Handler`;
this.preview({ action: 'message', class: n.className, properties: n.properties.filter((p) => p.name.trim()), transports: n.transports, attribute: n.attribute,
handler: n.handler ? { class: handlerClass, bus: n.bus, fromTransport: n.fromTransport } : null });
}
}