sequence-runner.js 11 KB

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