forge-core 0.9.0

Core types and traits for the Forge framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Test context for workflow functions.

#![allow(clippy::unwrap_used, clippy::indexing_slicing)]

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use chrono::{DateTime, Utc};
use sqlx::PgPool;
use uuid::Uuid;

use super::super::mock_http::{MockHttp, MockRequest, MockResponse};
use super::build_test_auth;
use crate::Result;
use crate::env::{EnvAccess, EnvProvider, MockEnvProvider};
use crate::function::AuthContext;

/// Step state stored during testing.
#[derive(Debug, Clone)]
pub struct TestStepState {
    /// Whether the step is completed.
    pub completed: bool,
    /// Step result (if completed).
    pub result: Option<serde_json::Value>,
}

/// Test context for workflow functions.
///
/// Provides an isolated testing environment for workflows with step tracking,
/// resume simulation, and durable sleep verification.
///
/// # Example
///
/// ```ignore
/// let ctx = TestWorkflowContext::builder("account_verification")
///     .with_run_id(Uuid::new_v4())
///     .build();
///
/// ctx.record_step_start("validate_email");
/// ctx.record_step_complete("validate_email", json!({"valid": true}));
///
/// assert!(ctx.is_step_completed("validate_email"));
/// ```
pub struct TestWorkflowContext {
    /// Workflow run ID.
    pub run_id: Uuid,
    /// Workflow name.
    pub workflow_name: String,
    /// When the workflow started.
    pub started_at: DateTime<Utc>,
    /// Deterministic workflow time.
    workflow_time: DateTime<Utc>,
    /// Whether this is a resumed execution.
    is_resumed: bool,
    /// Tenant ID (for multi-tenancy).
    tenant_id: Option<Uuid>,
    /// Authentication context.
    pub auth: AuthContext,
    /// Optional database pool.
    pool: Option<PgPool>,
    /// Mock HTTP client.
    http: Arc<MockHttp>,
    /// Step states.
    step_states: Arc<RwLock<HashMap<String, TestStepState>>>,
    /// Completed step names in order.
    completed_steps: Arc<RwLock<Vec<String>>>,
    /// Whether sleep was called.
    sleep_called: Arc<RwLock<bool>>,
    /// Mock environment provider.
    env_provider: Arc<MockEnvProvider>,
}

impl TestWorkflowContext {
    /// Create a new builder.
    pub fn builder(workflow_name: impl Into<String>) -> TestWorkflowContextBuilder {
        TestWorkflowContextBuilder::new(workflow_name)
    }

    /// Get the database pool (if available).
    pub fn db(&self) -> Option<&PgPool> {
        self.pool.as_ref()
    }

    /// Get the mock HTTP client.
    pub fn http(&self) -> &MockHttp {
        &self.http
    }

    /// Check if this is a resumed execution.
    pub fn is_resumed(&self) -> bool {
        self.is_resumed
    }

    /// Get the deterministic workflow time.
    pub fn workflow_time(&self) -> DateTime<Utc> {
        self.workflow_time
    }

    /// Get the tenant ID.
    pub fn tenant_id(&self) -> Option<Uuid> {
        self.tenant_id
    }

    /// Check if a step is completed.
    pub fn is_step_completed(&self, name: &str) -> bool {
        self.step_states
            .read()
            .unwrap()
            .get(name)
            .map(|s| s.completed)
            .unwrap_or(false)
    }

    /// Check if a step has been started (exists in step states).
    pub fn is_step_started(&self, name: &str) -> bool {
        self.step_states.read().unwrap().contains_key(name)
    }

    /// Get the result of a completed step.
    pub fn get_step_result<T: serde::de::DeserializeOwned>(&self, name: &str) -> Option<T> {
        self.step_states
            .read()
            .unwrap()
            .get(name)
            .and_then(|s| s.result.clone())
            .and_then(|v| serde_json::from_value(v).ok())
    }

    /// Record step start.
    pub fn record_step_start(&self, name: &str) {
        let mut states = self.step_states.write().unwrap();
        states
            .entry(name.to_string())
            .or_insert_with(|| TestStepState {
                completed: false,
                result: None,
            });
    }

    /// Record step completion.
    pub fn record_step_complete(&self, name: &str, result: serde_json::Value) {
        let mut states = self.step_states.write().unwrap();
        let state = states
            .entry(name.to_string())
            .or_insert_with(|| TestStepState {
                completed: false,
                result: None,
            });
        state.completed = true;
        state.result = Some(result);
        drop(states);

        let mut completed = self.completed_steps.write().unwrap();
        if !completed.contains(&name.to_string()) {
            completed.push(name.to_string());
        }
    }

    /// Record step completion (async version for API compatibility).
    pub async fn record_step_complete_async(&self, name: &str, result: serde_json::Value) {
        self.record_step_complete(name, result);
    }

    /// Get completed step names in order.
    pub fn completed_step_names(&self) -> Vec<String> {
        self.completed_steps.read().unwrap().clone()
    }

    /// Durable sleep (no-op in tests, but records the intent).
    pub async fn sleep(&self, _duration: Duration) -> Result<()> {
        *self.sleep_called.write().unwrap() = true;
        Ok(())
    }

    /// Check if sleep was called.
    pub fn sleep_called(&self) -> bool {
        *self.sleep_called.read().unwrap()
    }

    /// Get elapsed time since workflow started.
    pub fn elapsed(&self) -> chrono::Duration {
        Utc::now() - self.started_at
    }

    /// Get the mock env provider for verification.
    pub fn env_mock(&self) -> &MockEnvProvider {
        &self.env_provider
    }
}

impl EnvAccess for TestWorkflowContext {
    fn env_provider(&self) -> &dyn EnvProvider {
        self.env_provider.as_ref()
    }
}

/// Builder for TestWorkflowContext.
pub struct TestWorkflowContextBuilder {
    run_id: Option<Uuid>,
    workflow_name: String,
    started_at: DateTime<Utc>,
    workflow_time: Option<DateTime<Utc>>,
    is_resumed: bool,
    tenant_id: Option<Uuid>,
    user_id: Option<Uuid>,
    roles: Vec<String>,
    claims: HashMap<String, serde_json::Value>,
    pool: Option<PgPool>,
    http: MockHttp,
    completed_steps: HashMap<String, serde_json::Value>,
    env_vars: HashMap<String, String>,
}

impl TestWorkflowContextBuilder {
    /// Create a new builder.
    pub fn new(workflow_name: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            run_id: None,
            workflow_name: workflow_name.into(),
            started_at: now,
            workflow_time: None,
            is_resumed: false,
            tenant_id: None,
            user_id: None,
            roles: Vec::new(),
            claims: HashMap::new(),
            pool: None,
            http: MockHttp::new(),
            completed_steps: HashMap::new(),
            env_vars: HashMap::new(),
        }
    }

    /// Set a specific run ID.
    pub fn with_run_id(mut self, id: Uuid) -> Self {
        self.run_id = Some(id);
        self
    }

    /// Set the workflow time (for deterministic testing).
    pub fn with_workflow_time(mut self, time: DateTime<Utc>) -> Self {
        self.workflow_time = Some(time);
        self
    }

    /// Mark as a resumed execution.
    pub fn as_resumed(mut self) -> Self {
        self.is_resumed = true;
        self
    }

    /// Add a completed step (for resume testing).
    pub fn with_completed_step(
        mut self,
        name: impl Into<String>,
        result: serde_json::Value,
    ) -> Self {
        self.completed_steps.insert(name.into(), result);
        self
    }

    /// Set the tenant ID.
    pub fn with_tenant(mut self, tenant_id: Uuid) -> Self {
        self.tenant_id = Some(tenant_id);
        self
    }

    /// Set the authenticated user with a UUID.
    pub fn as_user(mut self, id: Uuid) -> Self {
        self.user_id = Some(id);
        self
    }

    /// For non-UUID auth providers (Firebase, Clerk, etc.).
    pub fn as_subject(mut self, subject: impl Into<String>) -> Self {
        self.claims
            .insert("sub".to_string(), serde_json::json!(subject.into()));
        self
    }

    /// Add a role.
    pub fn with_role(mut self, role: impl Into<String>) -> Self {
        self.roles.push(role.into());
        self
    }

    /// Set the database pool.
    pub fn with_pool(mut self, pool: PgPool) -> Self {
        self.pool = Some(pool);
        self
    }

    /// Add an HTTP mock.
    pub fn mock_http<F>(self, pattern: &str, handler: F) -> Self
    where
        F: Fn(&MockRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.http.add_mock_sync(pattern, handler);
        self
    }

    /// Add an HTTP mock that returns a JSON response.
    pub fn mock_http_json<T: serde::Serialize>(self, pattern: &str, response: T) -> Self {
        let json = serde_json::to_value(response).unwrap_or(serde_json::Value::Null);
        self.mock_http(pattern, move |_| MockResponse::json(json.clone()))
    }

    /// Set a single environment variable.
    pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env_vars.insert(key.into(), value.into());
        self
    }

    /// Set multiple environment variables.
    pub fn with_envs(mut self, vars: HashMap<String, String>) -> Self {
        self.env_vars.extend(vars);
        self
    }

    /// Build the test context.
    pub fn build(self) -> TestWorkflowContext {
        let step_states: HashMap<String, TestStepState> = self
            .completed_steps
            .iter()
            .map(|(name, result)| {
                (
                    name.clone(),
                    TestStepState {
                        completed: true,
                        result: Some(result.clone()),
                    },
                )
            })
            .collect();

        let completed_steps: Vec<String> = self.completed_steps.keys().cloned().collect();

        TestWorkflowContext {
            run_id: self.run_id.unwrap_or_else(Uuid::new_v4),
            workflow_name: self.workflow_name,
            started_at: self.started_at,
            workflow_time: self.workflow_time.unwrap_or(self.started_at),
            is_resumed: self.is_resumed,
            tenant_id: self.tenant_id,
            auth: build_test_auth(self.user_id, self.roles, self.claims),
            pool: self.pool,
            http: Arc::new(self.http),
            step_states: Arc::new(RwLock::new(step_states)),
            completed_steps: Arc::new(RwLock::new(completed_steps)),
            sleep_called: Arc::new(RwLock::new(false)),
            env_provider: Arc::new(MockEnvProvider::with_vars(self.env_vars)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_workflow_context_creation() {
        let ctx = TestWorkflowContext::builder("test_workflow").build();

        assert_eq!(ctx.workflow_name, "test_workflow");
        assert!(!ctx.is_resumed());
    }

    #[test]
    fn test_step_tracking() {
        let ctx = TestWorkflowContext::builder("test").build();

        assert!(!ctx.is_step_completed("step1"));

        ctx.record_step_start("step1");
        ctx.record_step_complete("step1", serde_json::json!({"result": "ok"}));

        assert!(ctx.is_step_completed("step1"));

        let result: Option<serde_json::Value> = ctx.get_step_result("step1");
        assert!(result.is_some());
    }

    #[test]
    fn test_resumed_with_completed_steps() {
        let ctx = TestWorkflowContext::builder("test")
            .as_resumed()
            .with_completed_step("step1", serde_json::json!({"id": 123}))
            .with_completed_step("step2", serde_json::json!({"status": "ok"}))
            .build();

        assert!(ctx.is_resumed());
        assert!(ctx.is_step_completed("step1"));
        assert!(ctx.is_step_completed("step2"));
        assert!(!ctx.is_step_completed("step3"));
    }

    #[test]
    fn test_step_order() {
        let ctx = TestWorkflowContext::builder("test").build();

        ctx.record_step_complete("step1", serde_json::json!({}));
        ctx.record_step_complete("step2", serde_json::json!({}));
        ctx.record_step_complete("step3", serde_json::json!({}));

        let completed = ctx.completed_step_names();
        assert_eq!(completed, vec!["step1", "step2", "step3"]);
    }

    #[tokio::test]
    async fn test_durable_sleep() {
        let ctx = TestWorkflowContext::builder("test").build();

        assert!(!ctx.sleep_called());
        ctx.sleep(Duration::from_secs(3600)).await.unwrap();
        assert!(ctx.sleep_called());
    }

    #[test]
    fn test_deterministic_time() {
        let fixed_time = Utc::now();
        let ctx = TestWorkflowContext::builder("test")
            .with_workflow_time(fixed_time)
            .build();

        assert_eq!(ctx.workflow_time(), fixed_time);
    }

    #[test]
    fn test_tenant() {
        let tenant_id = Uuid::new_v4();
        let ctx = TestWorkflowContext::builder("test")
            .with_tenant(tenant_id)
            .build();

        assert_eq!(ctx.tenant_id(), Some(tenant_id));
    }
}