Files
OpenBench/Templates/OpenBench/pipeline_edit.html
T

454 lines
21 KiB
HTML

{% extends "OpenBench/base.html" %}
{% block page_head %}
<div>
<a class="crumb" href="{% if pipeline %}/pipelines/{{ pipeline.id }}/{% else %}/pipelines/{% endif %}"><i class="fa-solid fa-chevron-left"></i> {% if pipeline %}{{ pipeline.name }}{% else %}Pipelines{% endif %}</a>
<h1 class="page-title">{% if pipeline %}Edit pipeline{% else %}New pipeline{% endif %}</h1>
<p class="page-sub">Steps run one after another. How a step ends decides which step comes next</p>
</div>
{% endblock %}
{% block content %}
<style>
.pl-ed input, .pl-ed select, .pl-ed textarea { font: inherit; color: inherit; background: transparent; border: 1px solid rgba(128, 128, 128, .4); border-radius: 6px; padding: .35rem .5rem; box-sizing: border-box; }
.pl-ed textarea { resize: vertical; width: 100%; }
.pl-ed label { display: block; font-size: .8rem; opacity: .75; margin-bottom: .2rem; }
.pl-pad { padding: 0 .9rem .9rem; }
.pl-row { display: flex; flex-wrap: wrap; gap: .75rem 1rem; align-items: flex-end; }
.pl-box { border: 1px solid rgba(128, 128, 128, .3); border-radius: 8px; padding: .9rem; margin: 0 .9rem .9rem; }
.pl-box-head { display: flex; flex-wrap: wrap; gap: .6rem; align-items: center; margin-bottom: .7rem; }
.pl-kv-row { display: grid; grid-template-columns: minmax(8rem, 14rem) 1fr auto; gap: .4rem; margin-bottom: .4rem; align-items: start; }
.pl-empty { border-color: #d9534f !important; }
.pl-note { font-size: .85rem; opacity: .8; margin: .3rem 0; }
.pl-small { font-size: .85rem; padding: .25rem .6rem; }
.pl-edge { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; }
.pl-ed details { margin-top: .6rem; }
.pl-actions { display: flex; gap: .75rem; align-items: center; margin: 1rem 0; }
</style>
<form id="pl-form" class="pl-ed" method="post" autocomplete="off">
{% csrf_token %}
<input type="hidden" name="graph" id="pl-graph" value="">
<div class="card">
<div class="card-head"><h2 class="card-title">General</h2></div>
<div class="pl-pad">
<div class="pl-row">
<div style="flex: 1 1 18rem">
<label for="pl-name">Name</label>
<input id="pl-name" name="name" value="{{ name }}" maxlength="128" required style="width: 100%">
</div>
<div>
<label for="pl-start">First step</label>
<select id="pl-start" class="pl-step-select" data-end="0"></select>
</div>
<div>
<label for="pl-visits">Most runs of one step</label>
<input id="pl-visits" type="number" min="1" style="width: 7rem">
</div>
<div>
<label for="pl-total">Most tests in one run</label>
<input id="pl-total" type="number" min="1" style="width: 7rem">
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-head">
<h2 class="card-title">Steps</h2>
<button type="button" id="pl-add-step" class="anchorbutton btn-blue pl-small">Add step</button>
</div>
<div id="pl-steps"></div>
</div>
<div class="card">
<div class="card-head">
<h2 class="card-title">What happens next</h2>
<button type="button" id="pl-add-edge" class="anchorbutton btn-blue pl-small">Add rule</button>
</div>
<div class="pl-pad" id="pl-edges"></div>
</div>
<div class="card">
<div class="card-head">
<h2 class="card-title">Checks</h2>
<button type="button" id="pl-check" class="anchorbutton btn-start pl-small">Check</button>
</div>
<ul class="pl-checks" id="pl-checks">
{% for issue in issues %}
<li class="pl-check pl-check-{{ issue.level }}">
<i class="fa-solid {% if issue.level == 'error' %}fa-circle-exclamation{% elif issue.level == 'warning' %}fa-triangle-exclamation{% else %}fa-circle-info{% endif %}"></i>
<span>{% if issue.name %}<strong>{{ issue.name }}</strong> {% endif %}{{ issue.message }}</span>
</li>
{% endfor %}
</ul>
</div>
<div class="pl-actions">
<button type="submit" class="anchorbutton btn-blue">Save pipeline</button>
<a href="{% if pipeline %}/pipelines/{{ pipeline.id }}/{% else %}/pipelines/{% endif %}">Cancel</a>
</div>
</form>
<datalist id="pl-keys"></datalist>
{{ graph|json_script:"graph-data" }}
{{ meta|json_script:"meta-data" }}
<script>
(function () {
'use strict';
const meta = JSON.parse(document.getElementById('meta-data').textContent);
const parsed = JSON.parse(document.getElementById('graph-data').textContent);
const token = document.querySelector('#pl-form input[name=csrfmiddlewaretoken]').value;
const isObj = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const seed = isObj(parsed) ? parsed : {};
const pairsOf = obj => Object.entries(isObj(obj) ? obj : {}).map(([key, value]) => [key, String(value)]);
const KIND_LABELS = { TEST : 'Test (SPRT or fixed games)', TUNE : 'Tune (SPSA)', DATAGEN : 'Datagen' };
const OUTCOME_LABELS = { passed : 'it passes', failed : 'it fails', stopped : 'it is stopped', any : 'it ends, however it ends' };
const model = {
start : typeof seed.start === 'string' ? seed.start : '',
max_visits : seed.max_visits == null ? '' : String(seed.max_visits),
max_steps : seed.max_steps == null ? '' : String(seed.max_steps),
steps : Object.entries(isObj(seed.steps) ? seed.steps : {}).map(([id, step]) => ({
id : id,
name : (isObj(step) && step.name) || id,
kind : (isObj(step) && step.kind) || 'TEST',
payload : pairsOf(isObj(step) ? step.payload : {}),
msg : '',
})),
edges : (Array.isArray(seed.edges) ? seed.edges : []).filter(isObj).map(edge => ({
from : edge.from,
on : edge.on,
to : edge.to == null ? '' : edge.to,
set : pairsOf(edge.set),
})),
};
const defaultsFor = kind => pairsOf(meta.defaults[kind]);
const stepName = step => step.name || step.id;
if (!model.steps.length) {
model.steps.push({ id : 'step1', name : 'Step 1', kind : 'TEST', payload : defaultsFor('TEST'), msg : '' });
}
if (!model.steps.some(step => step.id === model.start)) {
model.start = model.steps[0].id;
}
// Small DOM helper. Text always goes in as text, never as HTML
function el(tag, attrs, ...kids) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(attrs || {})) {
if (value === false || value == null) continue;
if (key === 'class') node.className = value;
else node.setAttribute(key, value === true ? '' : value);
}
for (const kid of kids.flat()) {
if (kid != null) node.append(kid);
}
return node;
}
function button(label, handler, cls) {
const node = el('button', { type : 'button', class : 'anchorbutton ' + (cls || 'btn-start') + ' pl-small' }, label);
node.addEventListener('click', handler);
return node;
}
function nextId() {
const taken = new Set(model.steps.map(step => step.id));
let n = model.steps.length + 1;
while (taken.has('step' + n)) n++;
return 'step' + n;
}
// The settings that a step has to have, given its kind and test mode
function needed(step) {
const keys = (meta.required[step.kind] || []).slice();
if (step.kind === 'TEST') {
const found = step.payload.find(pair => pair[0].trim() === 'test_mode');
const mode = (found && found[1].trim()) || 'SPRT';
(meta.conditional[mode] || []).forEach(key => keys.push(key));
}
return keys;
}
function scaffold(step) {
const have = new Set(step.payload.map(pair => pair[0].trim()));
const defaults = meta.defaults[step.kind] || {};
needed(step).forEach(key => {
if (!have.has(key)) step.payload.push([key, defaults[key] == null ? '' : defaults[key]]);
});
}
// Editor for a list of [ setting, value ] pairs, changed in place
function kvEditor(pairs, onChange, isRequired) {
const box = el('div');
const draw = () => {
box.replaceChildren();
pairs.forEach((pair, index) => {
const key = el('input', { placeholder : 'setting', list : 'pl-keys', spellcheck : 'false', 'aria-label' : 'Setting' });
const val = el('textarea', { rows : String(Math.min(6, pair[1].split('\n').length)), spellcheck : 'false', 'aria-label' : 'Value' });
key.value = pair[0];
val.value = pair[1];
const flag = () => val.classList.toggle('pl-empty', !!isRequired && isRequired(pair[0]) && pair[1].trim() === '');
key.addEventListener('input', () => { pair[0] = key.value; flag(); onChange(); });
val.addEventListener('input', () => { pair[1] = val.value; flag(); onChange(); });
flag();
const del = button('\u00d7', () => { pairs.splice(index, 1); draw(); onChange(); }, 'btn-red');
del.title = 'Remove this setting';
box.append(el('div', { class : 'pl-kv-row' }, key, val, del));
});
};
draw();
return el('div', {}, box, button('Add setting', () => { pairs.push(['', '']); draw(); onChange(); }));
}
function fillSelect(select, value, allowEnd) {
select.replaceChildren();
if (allowEnd) select.append(el('option', { value : '' }, 'End the pipeline'));
model.steps.forEach(step => select.append(el('option', { value : step.id }, stepName(step))));
select.value = value;
}
function stepSelect(value, allowEnd, onChange) {
const select = el('select', { class : 'pl-step-select', 'data-end' : allowEnd ? '1' : '0' });
fillSelect(select, value, allowEnd);
select.addEventListener('change', () => onChange(select.value));
return select;
}
function refreshSelects() {
document.querySelectorAll('.pl-step-select').forEach(select => {
fillSelect(select, select.value, select.dataset.end === '1');
});
}
// Steps
const stepsBox = document.getElementById('pl-steps');
function drawSteps() {
stepsBox.replaceChildren();
model.steps.forEach(step => {
const name = el('input', { maxlength : '64', 'aria-label' : 'Step name' });
name.value = step.name;
name.addEventListener('input', () => { step.name = name.value; refreshSelects(); });
const kind = el('select', { 'aria-label' : 'Kind' },
meta.kinds.map(k => el('option', { value : k, selected : k === step.kind }, KIND_LABELS[k] || k)));
kind.addEventListener('change', () => { step.kind = kind.value; drawSteps(); });
const note = el('div', { class : 'pl-note' });
const refreshNote = () => {
const have = new Set(step.payload.map(pair => pair[0].trim()));
const missing = needed(step).filter(key => !have.has(key));
note.textContent = missing.length ? 'Missing settings: ' + missing.join(', ') : '';
};
const editor = kvEditor(step.payload, refreshNote, key => needed(step).includes(key.trim()));
refreshNote();
const head = el('div', { class : 'pl-box-head' }, name, kind,
button('Add the missing settings', () => { scaffold(step); drawSteps(); }));
if (step.kind === 'TEST') {
const number = el('input', { type : 'number', min : '1', placeholder : 'Test #', 'aria-label' : 'Test number', style : 'width: 6.5rem' });
const copy = button('Copy settings from a test', async () => {
const id = parseInt(number.value, 10);
if (!id) { step.msg = 'Type the number of a test first'; drawSteps(); return; }
try {
const response = await fetch('/pipelines/test-fields/' + id + '/', { credentials : 'same-origin' });
const data = await response.json();
if (!response.ok) { step.msg = data.error || 'Could not copy that test'; drawSteps(); return; }
step.payload.splice(0, step.payload.length, ...pairsOf(data.payload));
scaffold(step);
step.msg = 'Copied from test #' + id + '. Check the branches before saving';
} catch (error) {
step.msg = 'Could not copy that test';
}
drawSteps();
});
head.append(number, copy);
}
const remove = button('Remove step', () => {
model.steps.splice(model.steps.indexOf(step), 1);
model.edges = model.edges.filter(edge => edge.from !== step.id && edge.to !== step.id);
if (model.start === step.id) model.start = model.steps[0].id;
drawAll();
}, 'btn-red');
remove.disabled = model.steps.length < 2;
head.append(remove);
stepsBox.append(el('div', { class : 'pl-box' }, head,
step.msg ? el('div', { class : 'pl-note' }, step.msg) : null, note, editor));
});
}
// Rules between steps
const edgesBox = document.getElementById('pl-edges');
function drawEdges() {
edgesBox.replaceChildren();
if (!model.edges.length) {
edgesBox.append(el('p', { class : 'pl-note' }, 'No rules yet, so the pipeline ends after its first step.'));
}
model.edges.forEach(edge => {
const from = stepSelect(edge.from, false, value => { edge.from = value; });
const to = stepSelect(edge.to, true, value => { edge.to = value; });
const on = el('select', { 'aria-label' : 'Outcome' },
meta.outcomes.map(o => el('option', { value : o, selected : o === edge.on }, OUTCOME_LABELS[o] || o)));
on.addEventListener('change', () => { edge.on = on.value; });
const remove = button('Remove', () => {
model.edges.splice(model.edges.indexOf(edge), 1);
drawEdges();
}, 'btn-red');
const row = el('div', { class : 'pl-edge' }, 'When', from, 'ends and', on, 'then', to, remove);
const sub = el('details', { open : edge.set.length > 0 },
el('summary', {}, 'Change settings for the step that starts'),
kvEditor(edge.set, () => {}, null));
edgesBox.append(el('div', { class : 'pl-box', style : 'margin: 0 0 .9rem' }, row, sub));
});
}
const startSelect = document.getElementById('pl-start');
startSelect.addEventListener('change', () => { model.start = startSelect.value; });
function drawAll() {
drawSteps();
drawEdges();
fillSelect(startSelect, model.start, false);
}
// General settings
const nameField = document.getElementById('pl-name');
const visitsField = document.getElementById('pl-visits');
const totalField = document.getElementById('pl-total');
visitsField.max = meta.limits.visits;
totalField.max = meta.limits.total;
visitsField.value = model.max_visits;
totalField.value = model.max_steps;
visitsField.addEventListener('input', () => { model.max_visits = visitsField.value; });
totalField.addEventListener('input', () => { model.max_steps = totalField.value; });
const keyList = document.getElementById('pl-keys');
meta.allowed.forEach(key => keyList.append(el('option', { value : key })));
document.getElementById('pl-add-step').addEventListener('click', () => {
if (model.steps.length >= meta.limits.steps) return;
model.steps.push({ id : nextId(), name : 'Step ' + (model.steps.length + 1), kind : 'TEST', payload : defaultsFor('TEST'), msg : '' });
drawAll();
});
document.getElementById('pl-add-edge').addEventListener('click', () => {
const last = model.steps[model.steps.length - 1];
model.edges.push({ from : model.steps[0].id, on : 'passed', to : model.steps.length > 1 ? last.id : '', set : [] });
drawEdges();
});
// Turn the editor back into a graph
function build() {
const steps = {};
model.steps.forEach(step => {
const payload = {};
step.payload.forEach(([key, value]) => { if (key.trim()) payload[key.trim()] = value; });
steps[step.id] = { name : step.name, kind : step.kind, payload : payload };
});
const edges = model.edges.map(edge => {
const out = { from : edge.from, on : edge.on, to : edge.to === '' ? null : edge.to };
const set = {};
edge.set.forEach(([key, value]) => { if (key.trim()) set[key.trim()] = value; });
if (Object.keys(set).length) out.set = set;
return out;
});
const graph = { version : 1, start : model.start, steps : steps, edges : edges };
const visits = parseInt(model.max_visits, 10);
const total = parseInt(model.max_steps, 10);
if (!isNaN(visits)) graph.max_visits = visits;
if (!isNaN(total)) graph.max_steps = total;
return graph;
}
// Checks, from the server, so that they are the very same rules that a run uses
const checksBox = document.getElementById('pl-checks');
function showIssues(issues) {
checksBox.replaceChildren();
if (!issues.length) {
checksBox.append(el('li', { class : 'pl-check' }, el('span', {}, 'No problems found')));
return;
}
const names = {};
model.steps.forEach(step => { names[step.id] = stepName(step); });
issues.forEach(issue => {
const icon = issue.level === 'error' ? 'fa-circle-exclamation' : issue.level === 'warning' ? 'fa-triangle-exclamation' : 'fa-circle-info';
const who = typeof issue.step === 'string' ? (names[issue.step] || issue.step) : '';
checksBox.append(el('li', { class : 'pl-check pl-check-' + issue.level },
el('i', { class : 'fa-solid ' + icon }), ' ',
el('span', {}, who ? el('strong', {}, who) : null, who ? ' ' : null, issue.message)));
});
}
document.getElementById('pl-check').addEventListener('click', async () => {
const body = new FormData();
body.append('csrfmiddlewaretoken', token);
body.append('graph', JSON.stringify(build()));
try {
const response = await fetch('/pipelines/check/', { method : 'POST', body : body, credentials : 'same-origin' });
const data = await response.json();
showIssues(data.issues || [{ level : 'error', step : null, message : data.error || 'The check failed' }]);
} catch (error) {
showIssues([{ level : 'error', step : null, message : 'The check could not be done' }]);
}
});
document.getElementById('pl-form').addEventListener('submit', () => {
document.getElementById('pl-graph').value = JSON.stringify(build());
});
drawAll();
})();
</script>
{% endblock %}