Files
image-workbench-desktop/src/runtime-recovery.js
T

45 lines
2.4 KiB
JavaScript

;(function (global) {
'use strict'
const Record = global.IWBRuntimeRecord
function own(value) { return value && typeof value === 'object' ? value : {} }
function hasNode(nodes, nodeId) { return Array.isArray(nodes) && nodes.some((node) => node && String(node.id) === String(nodeId)) }
function hasPrompt(nodes, taskId) {
if (!taskId) return true
return Array.isArray(nodes) && nodes.some((node) => {
if (!node || !node.data) return false
if (String(node.id) === String(taskId)) return true
const tasks = Array.isArray(node.data.tasks) ? node.data.tasks : []
return tasks.some((task) => task && String(task.id) === String(taskId))
})
}
function candidate(record, context) {
const value = Record ? Record.fromLegacy(record) : own(record)
const opt = context || {}
if (value.state === 'cancelled' || value.state === 'succeeded') return { ok: false, reason: 'terminal', record: value }
if (!hasNode(opt.nodes, value.nodeId)) return { ok: false, reason: 'node-missing', record: value }
if (!hasPrompt(opt.nodes, value.taskId)) return { ok: false, reason: 'task-missing', record: value }
if (value.state === 'recoverable') return { ok: true, record: value }
const next = Record ? Record.transition(value, 'recoverable', { errorClass: value.errorClass || 'lifecycle' }) : { ok: true, value }
return next.ok ? { ok: true, record: next.value } : { ok: false, reason: 'invalid-state', record: value }
}
function collect(records, context) {
const result = []
;(Array.isArray(records) ? records : []).forEach((record) => {
const marked = Record ? Record.markInterrupted(record) : { ok: true, value: record }
const item = candidate(marked.value, context)
if (item.ok) result.push(item.record)
})
return result
}
function parseStored(value, maxAgeMs, now) {
const source = typeof value === 'string' ? (() => { try { return JSON.parse(value) } catch (e) { return null } })() : value
if (!source || typeof source !== 'object') return []
const at = Number(source.at) || 0
if (maxAgeMs && (!at || (now || Date.now()) - at > maxAgeMs)) return []
const runs = Array.isArray(source.runs) ? source.runs : []
return runs.reduce((all, run) => all.concat(Array.isArray(run.jobs) && run.jobs.length ? run.jobs : [run]), [])
}
global.IWBRuntimeRecovery = { candidate, collect, parseStored }
})(typeof window !== 'undefined' ? window : globalThis)