sequence-runner.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. const { logActionError } = require('./actions/echo-parser.js')
  2. const variableParser = require('./variable-parser.js')
  3. /**
  4. * 执行操作序列(schedule/if/for/while + 普通步骤)
  5. * 单文件 ≤500 行。ctx: executeAction, logMessage, evaluateCondition, getActionName, parseDelayString, calculateWaitTime, state
  6. * state: variableContext, globalStepCounter, currentWorkflowFolderPath, variableContextInitialized
  7. */
  8. async function executeActionSequence(
  9. actions,
  10. device,
  11. folderPath,
  12. resolution,
  13. stepInterval,
  14. onStepComplete,
  15. shouldStop,
  16. depth,
  17. ctx
  18. ) {
  19. const { executeAction, logMessage, evaluateCondition, getActionName, parseDelayString, calculateWaitTime, replaceVariablesInString, state } = ctx
  20. const variableContext = state.variableContext
  21. const DEFAULT_STEP_INTERVAL = ctx.DEFAULT_STEP_INTERVAL ?? 1000
  22. if (depth === 0) {
  23. state.globalStepCounter = 0
  24. state.variableContextInitialized = false
  25. state.currentWorkflowFolderPath = folderPath
  26. }
  27. let completedSteps = 0
  28. const interval = stepInterval ?? DEFAULT_STEP_INTERVAL
  29. for (let i = 0; i < actions.length; i++) {
  30. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  31. const action = actions[i]
  32. if (action.type === 'schedule') {
  33. const condition = action.condition || {}
  34. let intervalStr = condition.interval || '0s'
  35. if (replaceVariablesInString && typeof intervalStr === 'string') {
  36. intervalStr = replaceVariablesInString(intervalStr, variableContext)
  37. }
  38. let repeat = condition.repeat !== undefined ? condition.repeat : 1
  39. if (typeof repeat === 'string' && variableContext) {
  40. const varName = repeat.replace(/^\{|\}$/g, '').trim()
  41. const resolved = variableContext[varName]
  42. repeat = resolved !== undefined && resolved !== null && resolved !== '' ? (parseInt(resolved, 10) || 1) : 1
  43. }
  44. const actionsToExecute = action.interval || []
  45. const intervalMs = parseDelayString(intervalStr) || 0
  46. const maxIterations = repeat === -1 ? Infinity : (typeof repeat === 'number' ? repeat : 1)
  47. let iteration = 0
  48. while (iteration < maxIterations) {
  49. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  50. iteration++
  51. if (iteration > 1 && intervalMs > 0) {
  52. let remainingTime = intervalMs
  53. const countdownInterval = 100
  54. while (remainingTime > 0) {
  55. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  56. const waitTime = Math.min(countdownInterval, remainingTime)
  57. await new Promise(resolve => setTimeout(resolve, waitTime))
  58. remainingTime -= waitTime
  59. }
  60. }
  61. if (actionsToExecute.length > 0) {
  62. const result = await executeActionSequence(actionsToExecute, device, folderPath, resolution, interval, onStepComplete, shouldStop, depth + 1, ctx)
  63. if (!result.success) return result
  64. completedSteps += result.completedSteps || 0
  65. }
  66. }
  67. continue
  68. }
  69. if (action.type === 'if') {
  70. const conditionResult = evaluateCondition(action.condition, variableContext)
  71. const actionsToExecute = conditionResult ? (action.then || action.ture || []) : (action.else || action.false || [])
  72. if (actionsToExecute.length > 0) {
  73. const result = await executeActionSequence(actionsToExecute, device, folderPath, resolution, interval, onStepComplete, shouldStop, depth + 1, ctx)
  74. if (!result.success) return result
  75. completedSteps += result.completedSteps || 0
  76. }
  77. continue
  78. }
  79. if (action.type === 'for') {
  80. if (action.times != null) {
  81. let count = action.times
  82. if (typeof count === 'string') {
  83. const varName = count.replace(/^\{|\}$/g, '').trim()
  84. count = Math.max(0, parseInt(variableContext[varName], 10) || 0)
  85. } else {
  86. count = Math.max(0, parseInt(count, 10) || 0)
  87. }
  88. for (let i = 0; i < count; i++) {
  89. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  90. if (action.variable) variableContext[action.variable.replace(/^\{|\}$/g, '').trim()] = i
  91. if (action.body && action.body.length > 0) {
  92. const result = await executeActionSequence(action.body, device, folderPath, resolution, interval, onStepComplete, shouldStop, depth + 1, ctx)
  93. if (!result.success) return result
  94. completedSteps += result.completedSteps || 0
  95. }
  96. }
  97. } else {
  98. const items = Array.isArray(action.items) ? action.items : []
  99. const indexKey = action.indexVariable != null ? String(action.indexVariable).replace(/^\{|\}$/g, '').trim() : null
  100. const variableKey = action.variable != null ? String(action.variable).replace(/^\{|\}$/g, '').trim() : null
  101. for (let i = 0; i < items.length; i++) {
  102. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  103. if (indexKey !== null) variableContext[indexKey] = i
  104. if (variableKey !== null) variableContext[variableKey] = items[i]
  105. if (action.body && action.body.length > 0) {
  106. const result = await executeActionSequence(action.body, device, folderPath, resolution, interval, onStepComplete, shouldStop, depth + 1, ctx)
  107. if (!result.success) return result
  108. completedSteps += result.completedSteps || 0
  109. }
  110. }
  111. }
  112. continue
  113. }
  114. if (action.type === 'while') {
  115. while (evaluateCondition(action.condition, variableContext)) {
  116. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  117. if (action.body && action.body.length > 0) {
  118. const result = await executeActionSequence(action.body, device, folderPath, resolution, interval, onStepComplete, shouldStop, depth + 1, ctx)
  119. if (!result.success) return result
  120. completedSteps += result.completedSteps || 0
  121. }
  122. }
  123. continue
  124. }
  125. if (action.type === 'try') {
  126. const tryActions = action.try || action.body || []
  127. const successActions = action.success || []
  128. const failActions = action.fail || action.catch || []
  129. const result = tryActions.length > 0
  130. ? await executeActionSequence(tryActions, device, folderPath, resolution, interval, onStepComplete, shouldStop, depth + 1, ctx)
  131. : { success: true, completedSteps: 0 }
  132. if (result.success && successActions.length > 0) {
  133. const successResult = await executeActionSequence(successActions, device, folderPath, resolution, interval, onStepComplete, shouldStop, depth + 1, ctx)
  134. if (!successResult.success) return successResult
  135. completedSteps += (result.completedSteps || 0) + (successResult.completedSteps || 0)
  136. } else if (result.success) {
  137. completedSteps += result.completedSteps || 0
  138. } else {
  139. const errMsg = (result.error != null && result.error !== '') ? String(result.error) : 'Unknown error'
  140. const timeStr = new Date().toISOString().replace('T', ' ').slice(0, 19)
  141. await logMessage(`[sequence-runner] [try failed] ${timeStr} ${errMsg}`, folderPath).catch(() => {})
  142. if (failActions.length > 0) {
  143. const failResult = await executeActionSequence(failActions, device, folderPath, resolution, interval, onStepComplete, shouldStop, depth + 1, ctx)
  144. if (!failResult.success) return failResult
  145. completedSteps += (result.completedSteps || 0) + (failResult.completedSteps || 0)
  146. } else {
  147. return result
  148. }
  149. }
  150. continue
  151. }
  152. const times = action.times || 1
  153. if (onStepComplete) onStepComplete(i + 1, actions.length, getActionName(action), 0, times, 0)
  154. const waitTime = calculateWaitTime(action.data, action.delay)
  155. if (waitTime > 0) {
  156. let remainingTime = waitTime
  157. const countdownInterval = 100
  158. const stepName = getActionName(action)
  159. while (remainingTime > 0) {
  160. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  161. if (onStepComplete) onStepComplete(i + 1, actions.length, stepName, remainingTime, times, 0)
  162. const waitTimeChunk = Math.min(countdownInterval, remainingTime)
  163. await new Promise(resolve => setTimeout(resolve, waitTimeChunk))
  164. remainingTime -= waitTimeChunk
  165. }
  166. }
  167. for (let t = 0; t < times; t++) {
  168. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  169. if (onStepComplete) onStepComplete(i + 1, actions.length, getActionName(action), 0, times, t + 1)
  170. state.globalStepCounter++
  171. const typeName = getActionName(action)
  172. // inVars/outVars 引用的变量必须在 workflow.variables 中声明,否则写 log 并失败
  173. if ((action.inVars && action.inVars.length > 0) || (action.outVars && action.outVars.length > 0)) {
  174. const declared = state.declaredVariableNames || []
  175. const validation = variableParser.validateInOutVars(action, declared)
  176. if (!validation.valid) {
  177. const errMsg = `inVars/outVars 引用了未在 variables 中声明的变量: ${validation.undeclared.join(', ')}`
  178. await logActionError(action, { success: false, error: errMsg }, { getActionName, logMessage, folderPath }).catch(() => {})
  179. return { success: false, error: errMsg, completedSteps: i }
  180. }
  181. }
  182. const result = await executeAction(action, device, folderPath, resolution)
  183. if (result.success && result.skipped) { /* 步骤跳过不写 log */ }
  184. // 统一由 echo-parser.logActionError 打印结点报错,各结点只需 return { success: false, error } 即可
  185. if (!result.success) {
  186. await logActionError(action, result, { getActionName, logMessage, folderPath }).catch(() => {})
  187. const errDetail = result.error != null && result.error !== '' ? String(result.error) : 'unknown'
  188. return { success: false, error: errDetail, completedSteps: i }
  189. }
  190. if (t < times - 1) await new Promise(resolve => setTimeout(resolve, 500))
  191. }
  192. completedSteps++
  193. if (onStepComplete) onStepComplete(i + 1, actions.length, getActionName(action), 0, times, times)
  194. if (i < actions.length - 1) {
  195. let remainingTime = interval
  196. const countdownInterval = 100
  197. const nextStepName = getActionName(actions[i + 1])
  198. const nextTimes = actions[i + 1].times || 1
  199. while (remainingTime > 0) {
  200. if (shouldStop && shouldStop()) return { success: false, error: 'Execution stopped', completedSteps }
  201. if (onStepComplete) onStepComplete(i + 1, actions.length, nextStepName, remainingTime, nextTimes, 0)
  202. const waitTime = Math.min(countdownInterval, remainingTime)
  203. await new Promise(resolve => setTimeout(resolve, waitTime))
  204. remainingTime -= waitTime
  205. }
  206. }
  207. }
  208. return { success: true, completedSteps }
  209. }
  210. module.exports = { executeActionSequence }