Files
stack/packages/webui/src/console-restart-http.mjs

40 lines
2.8 KiB
JavaScript

// F3: POST /api/console/restart. The owner restarts the Console from Settings.
//
// The route table's hook fence has already required a signed-in session on the page's own name,
// the exact Origin and Sec-Fetch-Site: same-origin. This handler adds the owner, --send, a JSON
// `{}` body and the trail. The Console then closes and exits RESTART_EXIT, and the supervisor in
// `mosaic console start` relaunches it on the same arguments and address. Org buses are separate
// processes and keep running. A Console with no supervisor answers not-supervised and stays up.
import { actor } from './action-trail.mjs';
const json = (res, status, body) => {
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
res.end(JSON.stringify(body));
};
const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.headersDistinct[name][0] : null);
async function emptyBody(req) {
if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(one(req, 'content-type') ?? '')) return 'JSON body required';
let text = '';
for await (const chunk of req) { text += chunk; if (text.length > 64) return 'body too large'; }
let value;
try { value = JSON.parse(text); } catch { return 'invalid JSON'; }
return value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0 ? null : 'the body is {}';
}
export async function consoleRestartHTTP(req, res, { session = null, operator = false, send = false, restart = null, trail = null, boot, log = () => {} }) {
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
if (!operator || !session) return json(res, 403, { error: 'owner-only', message: 'restarting the Console requires an instance operator' });
if (!send) return json(res, 403, { error: 'read-only', message: 'start the Console with --send to make changes' });
const invalid = await emptyBody(req);
if (invalid) return json(res, invalid === 'JSON body required' ? 415 : 400, { error: 'invalid-request', message: invalid });
if (!restart) return json(res, 409, { error: 'not-supervised', message: 'This Console was not started in the foreground by mosaic console start, so nothing would start it again. Restart it where it was started.' });
if (!trail) return json(res, 503, { error: 'trail-unavailable', message: 'this Console has no action trail, so it does not restart itself' });
try { trail({ by: actor(session), action: 'console.restart', outcome: 'restarting', boot }); }
catch { return json(res, 500, { error: 'trail-unavailable', message: 'the action trail could not be written, so the Console did not restart' }); }
log('console: restart requested by the owner');
// The answer reaches the page first; then every listener and connection closes.
res.once('finish', () => restart());
return json(res, 202, { outcome: 'restarting', boot });
}