57 lines
2.8 KiB
JavaScript
57 lines
2.8 KiB
JavaScript
;(function (global) {
|
|
'use strict'
|
|
|
|
const states = ['idle', 'queued', 'running', 'retrying', 'completed', 'failed', 'cancelled', 'interrupted', 'recoverable']
|
|
const transitions = {
|
|
idle: ['queued'],
|
|
queued: ['running', 'cancelled', 'interrupted'],
|
|
running: ['retrying', 'completed', 'failed', 'cancelled', 'interrupted'],
|
|
retrying: ['running', 'failed', 'cancelled', 'interrupted'],
|
|
interrupted: ['recoverable', 'queued', 'cancelled'],
|
|
recoverable: ['queued', 'cancelled'],
|
|
failed: ['queued', 'cancelled'],
|
|
completed: [],
|
|
cancelled: []
|
|
}
|
|
function createRecord(input) {
|
|
const source = input || {}
|
|
const state = states.indexOf(source.state) >= 0 ? source.state : 'idle'
|
|
return {
|
|
id: String(source.id || 'run-' + Date.now().toString(36)),
|
|
nodeId: source.nodeId ? String(source.nodeId) : '',
|
|
groupId: source.groupId ? String(source.groupId) : '',
|
|
variantIndex: Number.isInteger(source.variantIndex) ? source.variantIndex : 0,
|
|
state,
|
|
attempts: Math.max(0, Number(source.attempts) || 0),
|
|
createdAt: Number(source.createdAt) || Date.now(),
|
|
startedAt: Number(source.startedAt) || 0,
|
|
finishedAt: Number(source.finishedAt) || 0,
|
|
error: source.error || null,
|
|
cancelReason: source.cancelReason || '',
|
|
progress: source.progress && typeof source.progress === 'object' ? Object.assign({}, source.progress) : { done: 0, total: 0 }
|
|
}
|
|
}
|
|
function canTransition(from, to) {
|
|
return states.indexOf(from) >= 0 && (transitions[from] || []).indexOf(to) >= 0
|
|
}
|
|
function transition(record, next, patch) {
|
|
const current = createRecord(record)
|
|
if (!canTransition(current.state, next)) return { ok: false, error: 'invalid-transition', from: current.state, to: next, value: current }
|
|
const value = Object.assign({}, current, patch || {}, { state: next })
|
|
if (next === 'running' && !value.startedAt) value.startedAt = Date.now()
|
|
if (['completed', 'failed', 'cancelled', 'interrupted'].indexOf(next) >= 0) value.finishedAt = value.finishedAt || Date.now()
|
|
return { ok: true, value }
|
|
}
|
|
function markRetry(record) {
|
|
const next = transition(record, 'retrying', { attempts: createRecord(record).attempts + 1 })
|
|
return next.ok ? next : next
|
|
}
|
|
function summary(records) {
|
|
const list = Array.isArray(records) ? records : []
|
|
const result = { total: list.length, queued: 0, running: 0, retrying: 0, completed: 0, failed: 0, cancelled: 0, interrupted: 0, recoverable: 0 }
|
|
list.forEach((record) => { const state = createRecord(record).state; if (result[state] !== undefined) result[state]++ })
|
|
return result
|
|
}
|
|
global.IWBGenerationState = { states, transitions, createRecord, canTransition, transition, markRetry, summary }
|
|
})(typeof window !== 'undefined' ? window : globalThis)
|