kotoba_workflow/
ir.rs

1//! WorkflowIR - TemporalベースワークフローIR定義
2//!
3//! Kotobaのプロセスネットワークグラフモデル上に、Temporal風のワークフロー実行を
4//! 実現するためのIRを定義します。
5
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::time::Duration;
9use kotoba_core::prelude::*;
10use kotoba_core::types::{GraphRef_ as GraphRef, Value, TxId};
11
12/// ワークフロー実行ID
13#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
14pub struct WorkflowExecutionId(pub String);
15
16/// Activity実行ID
17#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
18pub struct ActivityExecutionId(pub String);
19
20/// ワークフロー定義IR
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct WorkflowIR {
23    pub id: String,
24    pub name: String,
25    pub description: Option<String>,
26    pub version: String,
27
28    /// ワークフロー入力パラメータ
29    pub inputs: Vec<WorkflowParam>,
30
31    /// ワークフロー出力パラメータ
32    pub outputs: Vec<WorkflowParam>,
33
34    /// 実行戦略(Temporalパターンをサポート)
35    pub strategy: WorkflowStrategyOp,
36
37    /// Serverless Workflow互換のアクティビティリスト
38    #[serde(skip_serializing_if = "Vec::is_empty")]
39    pub activities: Vec<ActivityIR>,
40
41    /// タイムアウト設定
42    pub timeout: Option<Duration>,
43
44    /// リトライポリシー
45    pub retry_policy: Option<RetryPolicy>,
46
47    /// メタデータ
48    pub metadata: HashMap<String, Value>,
49}
50
51/// ワークフローパラメータ
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct WorkflowParam {
54    pub name: String,
55    pub param_type: String,
56    pub required: bool,
57    pub default_value: Option<Value>,
58}
59
60/// Temporal拡張ワークフロー戦略
61#[derive(Debug, Clone, Serialize, Deserialize)]
62#[serde(tag = "op")]
63pub enum WorkflowStrategyOp {
64    /// 既存のStrategyOpを継承
65    Basic {
66        strategy: StrategyOp,
67    },
68
69    /// 順次実行
70    Seq {
71        strategies: Vec<Box<WorkflowStrategyOp>>,
72    },
73
74    /// 並列実行
75    Parallel {
76        branches: Vec<Box<WorkflowStrategyOp>>,
77        #[serde(default)]
78        completion_condition: CompletionCondition,
79    },
80
81    /// 条件分岐
82    Decision {
83        conditions: Vec<DecisionBranch>,
84        default_branch: Option<Box<WorkflowStrategyOp>>,
85    },
86
87    /// タイマー/イベント待ち
88    Wait {
89        condition: WaitCondition,
90        timeout: Option<Duration>,
91    },
92
93    /// Sagaパターン(補償トランザクション)
94    Saga {
95        main_flow: Box<WorkflowStrategyOp>,
96        compensation: Box<WorkflowStrategyOp>,
97    },
98
99    /// Activity実行
100    Activity {
101        activity_ref: String,  // extern 関数参照
102        input_mapping: HashMap<String, String>,
103        retry_policy: Option<RetryPolicy>,
104    },
105
106    /// 子ワークフロー実行
107    SubWorkflow {
108        workflow_ref: String,
109        input_mapping: HashMap<String, String>,
110    },
111}
112
113/// 並列完了条件
114#[derive(Debug, Clone, Serialize, Deserialize, Default)]
115pub enum CompletionCondition {
116    #[default]
117    /// 全てのブランチが完了するまで待つ
118    All,
119    /// いずれかのブランチが完了したら進む
120    Any,
121    /// 指定数のブランチが完了したら進む
122    AtLeast(u32),
123}
124
125/// 条件分岐ブランチ
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct DecisionBranch {
128    pub condition: String,  // 条件式(extern参照)
129    pub branch: Box<WorkflowStrategyOp>,
130}
131
132/// 待機条件
133#[derive(Debug, Clone, Serialize, Deserialize)]
134#[serde(tag = "type")]
135pub enum WaitCondition {
136    /// タイマー待機
137    Timer {
138        duration: Duration,
139    },
140    /// イベント待機
141    Event {
142        event_type: String,
143        filter: Option<HashMap<String, Value>>,
144    },
145    /// シグナル待機
146    Signal {
147        signal_name: String,
148    },
149}
150
151/// リトライポリシー
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct RetryPolicy {
154    pub initial_interval: Duration,
155    pub backoff_coefficient: f64,
156    pub maximum_interval: Option<Duration>,
157    pub maximum_attempts: u32,
158    pub non_retryable_errors: Vec<String>,
159}
160
161/// Activity定義IR
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct ActivityIR {
164    pub name: String,
165    pub description: Option<String>,
166    pub inputs: Vec<ActivityParam>,
167    pub outputs: Vec<ActivityParam>,
168    pub timeout: Option<Duration>,
169    pub retry_policy: Option<RetryPolicy>,
170    pub implementation: ActivityImplementation,
171}
172
173/// Workflow step definition for execution engine
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct WorkflowStep {
176    pub id: String,
177    pub step_type: WorkflowStepType,
178    pub body: serde_json::Value,
179}
180
181/// Workflow step types
182#[derive(Debug, Clone, Serialize, Deserialize)]
183pub enum WorkflowStepType {
184    /// HTTP call step
185    HttpCall,
186    /// Database query step
187    DbQuery,
188    /// Database rewrite step
189    DbRewrite,
190    /// Return step
191    Return,
192    /// Activity execution step
193    Activity,
194    /// Sub-workflow execution step
195    SubWorkflow,
196}
197
198/// Activityパラメータ
199#[derive(Debug, Clone, Serialize, Deserialize)]
200pub struct ActivityParam {
201    pub name: String,
202    pub param_type: String,
203    pub required: bool,
204}
205
206/// Activity実装種別
207#[derive(Debug, Clone, Serialize, Deserialize)]
208#[serde(tag = "type")]
209pub enum ActivityImplementation {
210    /// Rust関数
211    Function {
212        function_name: String,
213    },
214    /// HTTPエンドポイント
215    Http {
216        url: String,
217        method: String,
218        headers: HashMap<String, String>,
219    },
220    /// 外部プロセス
221    Process {
222        command: String,
223        args: Vec<String>,
224        env: HashMap<String, String>,
225    },
226    /// GraphQLクエリ
227    GraphQL {
228        query: String,
229        endpoint: String,
230    },
231}
232
233/// ワークフロー実行状態
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct WorkflowExecution {
236    pub id: WorkflowExecutionId,
237    pub workflow_id: String,
238    pub status: ExecutionStatus,
239    pub start_time: chrono::DateTime<chrono::Utc>,
240    pub end_time: Option<chrono::DateTime<chrono::Utc>>,
241    pub inputs: HashMap<String, serde_json::Value>,
242    pub outputs: Option<HashMap<String, serde_json::Value>>,
243    pub current_graph: GraphRef,
244    pub execution_history: Vec<ExecutionEvent>,
245    pub retry_count: u32,
246    pub timeout_at: Option<chrono::DateTime<chrono::Utc>>,
247}
248
249/// 実行状態
250#[derive(Debug, Clone, Serialize, Deserialize)]
251pub enum ExecutionStatus {
252    Running,
253    Completed,
254    Failed,
255    Cancelled,
256    TimedOut,
257    Compensating,
258}
259
260/// 実行イベント(イベントソーシング用)
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct ExecutionEvent {
263    pub id: String,
264    pub timestamp: chrono::DateTime<chrono::Utc>,
265    pub event_type: ExecutionEventType,
266    pub payload: HashMap<String, serde_json::Value>,
267}
268
269/// 実行イベント種別
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub enum ExecutionEventType {
272    Started,
273    ActivityScheduled,
274    ActivityStarted,
275    ActivityCompleted,
276    ActivityFailed,
277    DecisionMade,
278    TimerScheduled,
279    TimerFired,
280    SignalReceived,
281    WorkflowCompleted,
282    WorkflowFailed,
283    WorkflowCancelled,
284    CompensationStarted,
285    CompensationCompleted,
286}
287
288/// Sagaパターン定義
289#[derive(Debug, Clone, Serialize, Deserialize)]
290pub struct SagaPattern {
291    pub name: String,
292    pub description: Option<String>,
293    pub main_activities: Vec<String>,  // Activity名リスト
294    pub compensation_activities: Vec<String>,  // 補償Activity名リスト
295    pub timeout: Option<Duration>,
296}
297
298/// ワークフロー実行結果
299#[derive(Debug, Clone)]
300pub struct WorkflowResult {
301    pub execution_id: WorkflowExecutionId,
302    pub status: ExecutionStatus,
303    pub outputs: Option<HashMap<String, Value>>,
304    pub error: Option<String>,
305    pub execution_time: Duration,
306}
307
308/// Activity実行結果
309#[derive(Debug, Clone)]
310pub struct ActivityResult {
311    pub activity_id: ActivityExecutionId,
312    pub status: ActivityStatus,
313    pub outputs: Option<HashMap<String, Value>>,
314    pub error: Option<String>,
315    pub execution_time: Duration,
316}
317
318/// Activity実行状態
319#[derive(Debug, Clone, Serialize, Deserialize)]
320pub enum ActivityStatus {
321    Scheduled,
322    Started,
323    Completed,
324    Failed,
325    Cancelled,
326    TimedOut,
327}
328
329// GraphRef is imported from kotoba-core::types::GraphRef_