Repository Public License
1// ORIX Secure2// File: Packages/ORIXReporting/Sources/ORIXWorkflow/WorkflowRunner.swift3// Description: Runs a workflow step by step as a stream of events, with progress, confirmation gates, time limits, prompt4// cancellation and a history of finished runs. A destructive step never runs without a confirmed gate.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXSecureModel1011public enum WorkflowEvent: Sendable {12 case started(runID: UUID, definition: WorkflowDefinition)13 case stepStarted(index: Int, step: WorkflowStep)14 case stepProgress(index: Int, fraction: Double, message: String?)15 case awaitingConfirmation(index: Int, step: WorkflowStep)16 case stepFinished(index: Int, step: WorkflowStep, output: StepOutput)17 case stepSkipped(index: Int, step: WorkflowStep, reason: String)18 case stepFailed(index: Int, step: WorkflowStep, error: String)19 case finished(WorkflowRun)20}2122public actor WorkflowRunner {23 private var tasks: [UUID: Task<Void, Never>] = [:]24 private var finishedRuns: [WorkflowRun] = []25 private let historyLimit: Int2627 public init(historyLimit: Int = 50) {28 self.historyLimit = max(1, historyLimit)29 }3031 /// Finished runs, oldest first, limited to `historyLimit`. Cancelled runs are recorded too.32 public var history: [WorkflowRun] { finishedRuns }33 public var isRunning: Bool { !tasks.isEmpty }34 public var activeRunIDs: Set<UUID> { Set(tasks.keys) }3536 /// Starts the workflow and returns its events. The stream always ends with `.finished`, unless its consumer stopped37 /// listening: that cancels the run, whose record is then only available in `history`.38 public func run(39 _ definition: WorkflowDefinition,40 handlers: WorkflowHandlerRegistry,41 initialValues: [String: String] = [:],42 confirm: @escaping @Sendable (WorkflowStep) async -> ConfirmationDecision43 ) -> AsyncStream<WorkflowEvent> {44 let runID = UUID()45 let (stream, continuation) = AsyncStream.makeStream(of: WorkflowEvent.self)46 let task = Task { [weak self] in47 let run = await Self.execute(runID: runID, definition: definition, handlers: handlers, initialValues: initialValues, confirm: confirm) {48 continuation.yield($0)49 }50 await self?.record(run)51 continuation.yield(.finished(run))52 continuation.finish()53 }54 tasks[runID] = task55 continuation.onTermination = { reason in56 if case .cancelled = reason { task.cancel() }57 }58 return stream59 }6061 /// Cancels every active run. Steps that have not started are marked `notRun`.62 public func cancel() {63 for task in tasks.values { task.cancel() }64 }6566 public func cancel(runID: UUID) {67 tasks[runID]?.cancel()68 }6970 public func clearHistory() {71 finishedRuns.removeAll()72 }7374 private func record(_ run: WorkflowRun) {75 tasks[run.id] = nil76 finishedRuns.append(run)77 if finishedRuns.count > historyLimit { finishedRuns.removeFirst(finishedRuns.count - historyLimit) }78 }7980 // MARK: - Execution8182 private static func execute(83 runID: UUID,84 definition: WorkflowDefinition,85 handlers: WorkflowHandlerRegistry,86 initialValues: [String: String],87 confirm: @escaping @Sendable (WorkflowStep) async -> ConfirmationDecision,88 emit: @escaping @Sendable (WorkflowEvent) -> Void89 ) async -> WorkflowRun {90 let startedAt = Date()91 let context = WorkflowContext(runID: runID, values: initialValues)92 var records = definition.steps.map { WorkflowStepRecord(step: $0) }93 emit(.started(runID: runID, definition: definition))9495 func finish(_ status: WorkflowRun.Status, reason: String? = nil) async -> WorkflowRun {96 let findings = await context.findings97 let sections = await context.sections98 let values = await context.values99 return WorkflowRun(id: runID, definition: definition, startedAt: startedAt, endedAt: Date(), status: status, steps: records, failureReason: reason, findings: findings, sections: sections, values: values)100 }101102 // Definitions are validated when created; they are validated again against this registry's rules.103 do {104 try definition.validate(rules: handlers.rules)105 } catch {106 return await finish(.failed, reason: error.localizedDescription)107 }108109 var stoppedBy: WorkflowRun.Status?110 var hadIssues = false111112 steps: for (index, step) in definition.steps.enumerated() {113 if Task.isCancelled {114 stoppedBy = .cancelled115 break116 }117 let stepStart = Date()118 records[index].startedAt = stepStart119 func close(_ status: WorkflowStepStatus, summary: String? = nil, error: String? = nil) {120 records[index].status = status121 records[index].duration = Date().timeIntervalSince(stepStart)122 records[index].summary = summary123 records[index].errorText = error124 }125 func fail(_ message: String) -> Bool {126 close(.failed, error: message)127 emit(.stepFailed(index: index, step: step, error: message))128 hadIssues = true129 return step.continueOnFailure130 }131132 emit(.stepStarted(index: index, step: step))133134 guard let handler = handlers.handler(for: step.kind) else {135 if fail(WorkflowError.unknownStepKind(step.kind).localizedDescription) { continue }136 stoppedBy = .failed137 break138 }139140 let destructive = step.isDestructive || handlers.rules.destructiveKinds.contains(step.kind)141 if destructive {142 // Defence in depth: validation already guarantees both conditions.143 guard step.requiresConfirmation else {144 if fail(WorkflowError.destructiveStepWithoutConfirmation.localizedDescription) { continue }145 stoppedBy = .failed146 break147 }148 if let required = handlers.rules.requiredPredecessors[step.kind] {149 let reviewed = records[..<index].contains { $0.kind == required && $0.status == .succeeded }150 if !reviewed {151 let reason = L("Not run: the review step it depends on (\(required.rawValue)) did not complete.")152 close(.skipped, summary: reason)153 emit(.stepSkipped(index: index, step: step, reason: reason))154 hadIssues = true155 continue156 }157 }158 }159160 if step.requiresConfirmation {161 emit(.awaitingConfirmation(index: index, step: step))162 let decision = await answerOrCancellation { await confirm(step) }163 guard let decision, !Task.isCancelled else {164 close(.cancelled)165 stoppedBy = .cancelled166 break167 }168 if decision == .declined {169 let reason = L("You declined the confirmation.")170 close(.declined, summary: reason)171 emit(.stepSkipped(index: index, step: step, reason: reason))172 hadIssues = true173 if step.stopsWorkflowWhenDeclined {174 stoppedBy = .declined175 break176 }177 continue178 }179 }180181 do {182 let output = try await runHandler(handler, step: step, context: context) { fraction, message in183 let clamped = fraction.isFinite ? min(1, max(0, fraction)) : 0184 emit(.stepProgress(index: index, fraction: clamped, message: message))185 }186 await context.record(output)187 close(.succeeded, summary: output.summary)188 records[index].findingCount = output.findings?.count ?? 0189 emit(.stepFinished(index: index, step: step, output: output))190 } catch {191 if error is CancellationError || Task.isCancelled {192 close(.cancelled)193 stoppedBy = .cancelled194 break steps195 }196 if fail(error.localizedDescription) { continue }197 stoppedBy = .failed198 break steps199 }200 }201202 if Task.isCancelled, stoppedBy == nil, records.contains(where: { $0.status == .notRun }) { stoppedBy = .cancelled }203 for index in records.indices where records[index].status == .notRun {204 records[index].startedAt = nil205 }206 return await finish(stoppedBy ?? (hadIssues ? .completedWithIssues : .succeeded))207 }208209 private static func runHandler(210 _ handler: any WorkflowStepHandler,211 step: WorkflowStep,212 context: WorkflowContext,213 progress: @escaping @Sendable (Double, String?) -> Void214 ) async throws -> StepOutput {215 // Last gate: nothing, and above all nothing destructive, starts once the run is cancelled.216 try Task.checkCancellation()217 guard let timeout = step.timeout, timeout > 0 else {218 return try await handler.run(step: step, context: context, progress: progress)219 }220 return try await withThrowingTaskGroup(of: StepOutput.self) { group in221 group.addTask { try await handler.run(step: step, context: context, progress: progress) }222 group.addTask {223 try await Task.sleep(for: .seconds(timeout))224 throw WorkflowError.timedOut(seconds: timeout)225 }226 defer { group.cancelAll() }227 guard let output = try await group.next() else { throw CancellationError() }228 return output229 }230 }231232 /// Waits for the user's answer, but returns `nil` as soon as the run is cancelled, even if the confirmation closure233 /// itself never returns (a dialog left open).234 private static func answerOrCancellation(_ ask: @escaping @Sendable () async -> ConfirmationDecision) async -> ConfirmationDecision? {235 let gate = AnswerGate()236 let asking = Task { gate.resolve(await ask()) }237 return await withTaskCancellationHandler {238 await withCheckedContinuation { continuation in239 gate.wait(continuation)240 }241 } onCancel: {242 asking.cancel()243 gate.resolve(nil)244 }245 }246}247248/// Resumes one continuation exactly once with the first answer it gets.249private final class AnswerGate: @unchecked Sendable {250 private let lock = NSLock()251 private var continuation: CheckedContinuation<ConfirmationDecision?, Never>?252 private var answer: ConfirmationDecision??253254 func wait(_ continuation: CheckedContinuation<ConfirmationDecision?, Never>) {255 lock.lock()256 if let answer {257 lock.unlock()258 continuation.resume(returning: answer)259 return260 }261 self.continuation = continuation262 lock.unlock()263 }264265 func resolve(_ value: ConfirmationDecision?) {266 lock.lock()267 guard answer == nil else {268 lock.unlock()269 return270 }271 answer = .some(value)272 let waiting = continuation273 continuation = nil274 lock.unlock()275 waiting?.resume(returning: value)276 }277}278