Pipelines: create and edit pipelines from the web UI
This commit is contained in:
1 parent
011add1f23
commit
2ed44ca053
5 files changed
+672
-2
No files matched your search
@@ -35,6 +35,10 @@ import OpenBench.pipeline_layout as drawing
|
||||
import OpenBench.pipelines
|
||||
import OpenBench.views
|
||||
|
||||
import copy
|
||||
import json
|
||||
|
||||
from django.http import JsonResponse
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from OpenBench.models import LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test
|
||||
@@ -381,3 +385,206 @@ def pipeline_run_cancel(request, run_id):
|
||||
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), error='This run is already over')
|
||||
|
||||
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), status='Run cancelled')
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# EDITING #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
# Anybody with an enabled account may make a Pipeline, just like they may make a
|
||||
# Test. Changing one later is the same can_manage() rule as everything else.
|
||||
# The editor page builds the graph in the browser. Whatever it sends is never
|
||||
# trusted: it is validated here by exactly the code that validates a run.
|
||||
|
||||
MAX_GRAPH_BYTES = 262144
|
||||
|
||||
_GENERAL_DEFAULTS = {
|
||||
'upload_pgns' : 'FALSE', 'priority' : '0', 'throughput' : '1000',
|
||||
'syzygy_wdl' : 'OPTIONAL', 'syzygy_adj' : 'OPTIONAL',
|
||||
'win_adj' : 'movecount=3 score=400',
|
||||
'draw_adj' : 'movenumber=40 movecount=8 score=10',
|
||||
}
|
||||
|
||||
PAYLOAD_DEFAULTS = {
|
||||
'TEST' : dict(_GENERAL_DEFAULTS, workload_size='32', test_mode='SPRT', test_bounds='[0.00, 3.00]', test_confidence='[0.05, 0.05]'),
|
||||
'TUNE' : dict(_GENERAL_DEFAULTS),
|
||||
'DATAGEN' : dict(_GENERAL_DEFAULTS, workload_size='32'),
|
||||
}
|
||||
|
||||
def _blank_graph():
|
||||
return {
|
||||
'version' : graphs.SCHEMA_VERSION,
|
||||
'start' : 'step1',
|
||||
'max_visits' : graphs.DEFAULT_MAX_VISITS,
|
||||
'max_steps' : graphs.DEFAULT_MAX_STEPS,
|
||||
'steps' : { 'step1' : { 'name' : 'Step 1', 'kind' : 'TEST', 'payload' : dict(PAYLOAD_DEFAULTS['TEST']) } },
|
||||
'edges' : [],
|
||||
}
|
||||
|
||||
def _parse_graph(raw):
|
||||
|
||||
if not isinstance(raw, str) or len(raw) > MAX_GRAPH_BYTES:
|
||||
return None
|
||||
|
||||
try: graph = json.loads(raw)
|
||||
except ValueError: return None
|
||||
|
||||
return graph if isinstance(graph, dict) else None
|
||||
|
||||
def _tidy(graph):
|
||||
keys = ('version', 'start', 'max_visits', 'max_steps', 'steps', 'edges')
|
||||
return { key : graph[key] for key in keys if key in graph }
|
||||
|
||||
def _check(graph):
|
||||
|
||||
# validate_graph() is built for garbage, but a page that talks to the browser
|
||||
# should never answer with a 500 because of what the browser sent
|
||||
try: return graphs.validate_graph(graph)
|
||||
except Exception: return [graphs.issue('error', 'graph.invalid', 'The pipeline is not valid')]
|
||||
|
||||
def _named(issues, graph):
|
||||
|
||||
steps = graph.get('steps') if isinstance(graph, dict) else None
|
||||
steps = steps if isinstance(steps, dict) else {}
|
||||
|
||||
named = []
|
||||
for entry in issues:
|
||||
step = steps.get(entry['step']) if isinstance(entry['step'], str) else None
|
||||
name = step.get('name') if isinstance(step, dict) else None
|
||||
named.append(dict(entry, name=name or entry['step']))
|
||||
|
||||
return named
|
||||
|
||||
def _editor(request, pipeline, name, graph, issues=None, error=None):
|
||||
|
||||
data = {
|
||||
'pipeline' : pipeline,
|
||||
'name' : name,
|
||||
'graph' : graph,
|
||||
'issues' : _named(issues or [], graph),
|
||||
'meta' : {
|
||||
'kinds' : list(graphs.KINDS),
|
||||
'outcomes' : list(graphs.EDGE_CONDITIONS),
|
||||
'required' : graphs.REQUIRED_FIELDS,
|
||||
'conditional' : graphs.CONDITIONAL_FIELDS,
|
||||
'allowed' : sorted(graphs.ALLOWED_FIELDS),
|
||||
'defaults' : PAYLOAD_DEFAULTS,
|
||||
'limits' : { 'steps' : graphs.LIMIT_STEPS, 'visits' : graphs.LIMIT_MAX_VISITS, 'total' : graphs.LIMIT_MAX_STEPS },
|
||||
},
|
||||
}
|
||||
|
||||
return OpenBench.views.render(request, 'pipeline_edit.html', data, error=error)
|
||||
|
||||
def _submit(request, profile, found):
|
||||
|
||||
""" Shared by creating and editing. Saves, or shows the editor again with what was wrong """
|
||||
|
||||
name = (request.POST.get('name') or '').strip()
|
||||
graph = _parse_graph(request.POST.get('graph'))
|
||||
errors = []
|
||||
|
||||
if not (1 <= len(name) <= 128):
|
||||
errors.append('Give the pipeline a name of up to 128 characters')
|
||||
|
||||
if graph is None:
|
||||
errors.append('The pipeline could not be read. Reload the page and try again')
|
||||
return _editor(request, found, name, _blank_graph(), error='\n'.join(errors))
|
||||
|
||||
issues = _check(graph)
|
||||
|
||||
if graphs.has_errors(issues):
|
||||
errors.append('The pipeline has problems, see the checks below')
|
||||
|
||||
if errors:
|
||||
return _editor(request, found, name, graph, issues, error='\n'.join(errors))
|
||||
|
||||
graph = _tidy(graph)
|
||||
|
||||
if found is None:
|
||||
found = Pipeline.objects.create(name=name, author=profile.user.username, graph=graph)
|
||||
action = 'CREATED'
|
||||
else:
|
||||
found.name = name
|
||||
found.graph = graph
|
||||
found.save()
|
||||
action = 'EDITED'
|
||||
|
||||
_audit(profile.user.username, 'PIPELINE #%d %s' % (found.id, action))
|
||||
return OpenBench.views.redirect(request, '/pipelines/%d/' % (found.id), status='Pipeline saved')
|
||||
|
||||
def pipeline_new(request):
|
||||
|
||||
profile = viewer(request)
|
||||
if profile is None:
|
||||
return _turn_away(request, profile)
|
||||
|
||||
if request.method != 'POST':
|
||||
return _editor(request, None, '', _blank_graph())
|
||||
|
||||
return _submit(request, profile, None)
|
||||
|
||||
def pipeline_edit(request, id):
|
||||
|
||||
profile = viewer(request)
|
||||
if profile is None:
|
||||
return _turn_away(request, profile)
|
||||
|
||||
found = Pipeline.objects.filter(id=id, deleted=False).first()
|
||||
if found is None:
|
||||
return _missing(request)
|
||||
|
||||
if not can_manage(profile, found):
|
||||
return _turn_away(request, profile, id, 'edit')
|
||||
|
||||
# Runs that are going work from a snapshot of the graph, so this is safe at any time
|
||||
if request.method != 'POST':
|
||||
return _editor(request, found, found.name, copy.deepcopy(found.graph))
|
||||
|
||||
return _submit(request, profile, found)
|
||||
|
||||
@require_POST
|
||||
def pipeline_check(request):
|
||||
|
||||
""" Validates a graph without saving it, for the Check button of the editor """
|
||||
|
||||
if viewer(request) is None:
|
||||
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
|
||||
|
||||
graph = _parse_graph(request.POST.get('graph'))
|
||||
if graph is None:
|
||||
return JsonResponse({ 'issues' : [graphs.issue('error', 'graph.invalid', 'The pipeline could not be read')] })
|
||||
|
||||
return JsonResponse({ 'issues' : _check(graph) })
|
||||
|
||||
def pipeline_test_fields(request, test_id):
|
||||
|
||||
""" The settings of an existing SPRT or Games test, as the settings of a step """
|
||||
|
||||
if viewer(request) is None:
|
||||
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
|
||||
|
||||
test = Test.objects.select_related('dev', 'base').filter(id=test_id).first()
|
||||
if test is None or test.test_mode not in ('SPRT', 'GAMES'):
|
||||
return JsonResponse({ 'error' : 'There is no SPRT or Games test with that number' }, status=404)
|
||||
|
||||
fields = {
|
||||
'dev_engine' : test.dev_engine, 'base_engine' : test.base_engine,
|
||||
'dev_repo' : test.dev_repo, 'base_repo' : test.base_repo,
|
||||
'dev_branch' : test.dev.name, 'base_branch' : test.base.name,
|
||||
'dev_network' : test.dev_network, 'base_network' : test.base_network,
|
||||
'dev_options' : test.dev_options, 'base_options' : test.base_options,
|
||||
'dev_time_control' : test.dev_time_control, 'base_time_control' : test.base_time_control,
|
||||
'book_name' : test.book_name, 'upload_pgns' : test.upload_pgns,
|
||||
'priority' : test.priority, 'throughput' : test.throughput,
|
||||
'workload_size' : test.workload_size, 'test_mode' : test.test_mode,
|
||||
'syzygy_wdl' : test.syzygy_wdl, 'syzygy_adj' : test.syzygy_adj,
|
||||
'win_adj' : test.win_adj, 'draw_adj' : test.draw_adj,
|
||||
}
|
||||
|
||||
if test.test_mode == 'SPRT':
|
||||
fields['test_bounds'] = '[%.2f, %.2f]' % (test.elolower, test.eloupper)
|
||||
fields['test_confidence'] = '[%.2f, %.2f]' % (test.beta, test.alpha)
|
||||
else:
|
||||
fields['test_max_games'] = test.max_games
|
||||
|
||||
return JsonResponse({ 'payload' : { key : str(value) for key, value in fields.items() } })
|
||||
@@ -48,6 +48,10 @@ urlpatterns = [
|
||||
django.urls.path(r'pipelines/<int:id>/start/', OpenBench.pipeline_views.pipeline_start),
|
||||
django.urls.path(r'pipelines/<int:id>/toggle/', OpenBench.pipeline_views.pipeline_toggle),
|
||||
django.urls.path(r'pipelines/<int:id>/delete/', OpenBench.pipeline_views.pipeline_delete),
|
||||
django.urls.path(r'pipelines/<int:id>/edit/', OpenBench.pipeline_views.pipeline_edit),
|
||||
django.urls.path(r'pipelines/new/', OpenBench.pipeline_views.pipeline_new),
|
||||
django.urls.path(r'pipelines/check/', OpenBench.pipeline_views.pipeline_check),
|
||||
django.urls.path(r'pipelines/test-fields/<int:test_id>/', OpenBench.pipeline_views.pipeline_test_fields),
|
||||
django.urls.path(r'pipelines/run/<int:run_id>/', OpenBench.pipeline_views.pipeline_run),
|
||||
django.urls.path(r'pipelines/run/<int:run_id>/cancel/', OpenBench.pipeline_views.pipeline_run_cancel),
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
title="{% if usable %}Resume the pipeline to start it{% else %}Fix the pipeline settings first{% endif %}">Start run</button>
|
||||
{% endif %}
|
||||
|
||||
<a class="anchorbutton btn-start" href="/pipelines/{{ pipeline.id }}/edit/">Edit</a>
|
||||
|
||||
<form method="post" action="/pipelines/{{ pipeline.id }}/toggle/">
|
||||
{% csrf_token %}
|
||||
<button class="anchorbutton btn-start" type="submit">{% if pipeline.enabled %}Pause{% else %}Resume{% endif %}</button>
|
||||
@@ -54,7 +56,7 @@
|
||||
|
||||
<div class="banner error-message" role="alert">
|
||||
<i class="fa-solid fa-circle-exclamation banner-icon"></i>
|
||||
<pre>This pipeline cannot run because its settings are damaged. An administrator can fix them on the admin site.</pre>
|
||||
<pre>This pipeline cannot run because its settings are damaged. Use Edit to fix them.</pre>
|
||||
</div>
|
||||
|
||||
{% endif %}
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
{% 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 %}
|
||||
@@ -5,6 +5,10 @@
|
||||
<h1 class="page-title">Pipelines</h1>
|
||||
<p class="page-sub">Run a test, then let its result decide what runs next</p>
|
||||
</div>
|
||||
|
||||
<div class="page-actions">
|
||||
<a class="anchorbutton btn-blue" href="/pipelines/new/">New pipeline</a>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
@@ -63,7 +67,7 @@
|
||||
<div class="empty-state">
|
||||
<i class="fa-solid fa-diagram-project"></i>
|
||||
<p>No pipelines yet.</p>
|
||||
<p class="muted-small">A pipeline starts a test and picks the next one from the result. An administrator adds them on the admin site for now.</p>
|
||||
<p class="muted-small">A pipeline starts a test and picks the next one from the result. Use New pipeline to create the first one.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in new issue
Block a user