Repository Public License
1// FlowEngine — persistence of run logs in the module's own table, so a failed run can be resumed.2import Foundation3import NavigatorCore4import Persistence56/// Stores `FlowRunRecord`s in `flow_runs`, a table this module creates itself through `database.sqlite`7/// (Persistence's schema is not touched). Pass it to `FlowRunner(host:observers:)`.8///9/// Not for ghost (private) contexts: a run started there must use a runner without a store.10public actor FlowRunStore: FlowRunObserver {11 /// Version of this module's own tables, kept in `database.settings`.12 public static let schemaVersionKey = SettingKey<Int>("flow.schema_version", default: 0)13 public static let currentSchemaVersion = 11415 private let database: NavigatorDatabase16 private var isPrepared = false17 /// The last error met while saving from `runDidChange` (which cannot throw); `nil` after a success.18 public private(set) var lastSaveError: (any Error)?1920 public init(database: NavigatorDatabase) { self.database = database }2122 /// Creates the table if needed. Idempotent; called automatically by every other method.23 public func prepare() async throws {24 guard !isPrepared else { return }25 try await database.sqlite.transaction { connection in26 try connection.executeScript("""27 CREATE TABLE IF NOT EXISTS flow_runs (28 id TEXT PRIMARY KEY NOT NULL,29 workflow_id TEXT,30 name TEXT NOT NULL,31 status TEXT NOT NULL,32 started_at REAL NOT NULL,33 updated_at REAL NOT NULL,34 record TEXT NOT NULL35 );36 CREATE INDEX IF NOT EXISTS flow_runs_by_workflow ON flow_runs (workflow_id, started_at);37 CREATE INDEX IF NOT EXISTS flow_runs_by_start ON flow_runs (started_at);38 """)39 }40 if try await database.settings.value(Self.schemaVersionKey) < Self.currentSchemaVersion {41 try await database.settings.set(Self.schemaVersionKey, to: Self.currentSchemaVersion)42 }43 isPrepared = true44 }4546 private static func encode(_ record: FlowRunRecord) throws -> String {47 let encoder = JSONEncoder()48 // The default strategy stores the Date's own Double, which round-trips exactly.49 encoder.outputFormatting = [.sortedKeys]50 return String(decoding: try encoder.encode(record), as: UTF8.self)51 }5253 private static func decode(_ text: String) throws -> FlowRunRecord {54 try JSONDecoder().decode(FlowRunRecord.self, from: Data(text.utf8))55 }5657 public func save(_ record: FlowRunRecord) async throws {58 try await prepare()59 let json = try Self.encode(record)60 try await database.sqlite.transaction { connection in61 try connection.upsert(into: "flow_runs", [62 "id": record.id, "workflow_id": record.workflowID, "name": record.name, "status": record.status.rawValue,63 "started_at": record.startedAt, "updated_at": record.updatedAt, "record": json,64 ])65 }66 }6768 public func runDidChange(_ record: FlowRunRecord) async {69 do {70 try await save(record)71 lastSaveError = nil72 } catch {73 lastSaveError = error74 }75 }7677 public func run(_ id: UUID) async throws -> FlowRunRecord? {78 try await prepare()79 let json = try await database.sqlite.read { try $0.scalar("SELECT record FROM flow_runs WHERE id = ?", [id], as: String.self) }80 return try json.map(Self.decode)81 }8283 /// Runs, most recent first.84 public func runs(workflow: WorkflowID? = nil, limit: Int = 100) async throws -> [FlowRunRecord] {85 try await prepare()86 let rows = try await database.sqlite.read { connection in87 try connection.query("""88 SELECT record FROM flow_runs WHERE (?1 IS NULL OR workflow_id = ?1) ORDER BY started_at DESC, id LIMIT ?289 """, [workflow, max(0, limit)]).map { try $0.get("record", as: String.self) }90 }91 return try rows.map(Self.decode)92 }9394 /// Runs that stopped before their end and can be continued with `FlowRunner.resume`.95 public func resumable() async throws -> [FlowRunRecord] {96 try await runs(limit: 1_000).filter(\.isResumable)97 }9899 public func delete(_ id: UUID) async throws {100 try await prepare()101 try await database.sqlite.transaction { _ = try $0.execute("DELETE FROM flow_runs WHERE id = ?", [id]) }102 }103104 /// Deletes every run log (part of "delete all data"; the app must call it, Persistence does not know this table).105 @discardableResult106 public func deleteAll(workflow: WorkflowID? = nil) async throws -> Int {107 try await prepare()108 return try await database.sqlite.transaction {109 try $0.execute("DELETE FROM flow_runs WHERE (?1 IS NULL OR workflow_id = ?1)", [workflow])110 }111 }112113 /// Keeps the `count` most recent runs and deletes the rest.114 @discardableResult115 public func prune(keeping count: Int) async throws -> Int {116 try await prepare()117 return try await database.sqlite.transaction {118 try $0.execute("""119 DELETE FROM flow_runs WHERE id NOT IN (SELECT id FROM flow_runs ORDER BY started_at DESC, id LIMIT ?)120 """, [max(0, count)])121 }122 }123}124