periplon 0.2.0

Rust SDK for building multi-agent AI workflows and automation
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! WebSocket Integration Tests
//!
//! Comprehensive tests for WebSocket execution streaming covering:
//! - WebSocket connection establishment
//! - Real-time execution status updates
//! - Log message streaming
//! - Progress updates
//! - Completion and failure notifications
//! - Ping/pong keep-alive mechanism
//! - Connection error handling
//! - Message format validation

#![cfg(feature = "server")]

use chrono::Utc;
use periplon_sdk::dsl::schema::DSLWorkflow;
use periplon_sdk::server::storage::{
    Execution, ExecutionLog, ExecutionStatus, ExecutionStorage, WorkflowMetadata, WorkflowStorage,
};
use periplon_sdk::testing::MockStorage;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;

// ============================================================================
// Test Helpers
// ============================================================================

fn create_test_workflow(name: &str) -> (DSLWorkflow, WorkflowMetadata) {
    let workflow = DSLWorkflow {
        provider: Default::default(),
        model: None,
        name: name.to_string(),
        version: "1.0.0".to_string(),
        dsl_version: "1.0.0".to_string(),
        cwd: None,
        create_cwd: None,
        secrets: HashMap::new(),
        inputs: HashMap::new(),
        outputs: HashMap::new(),
        agents: HashMap::new(),
        tasks: HashMap::new(),
        workflows: HashMap::new(),
        tools: None,
        communication: None,
        mcp_servers: HashMap::new(),
        subflows: HashMap::new(),
        imports: HashMap::new(),
        notifications: None,
        limits: None,
    };

    let metadata = WorkflowMetadata {
        id: Uuid::new_v4(),
        name: name.to_string(),
        version: "1.0.0".to_string(),
        description: Some("Test workflow".to_string()),
        created_at: Utc::now(),
        updated_at: Utc::now(),
        created_by: Some("test_user".to_string()),
        tags: vec!["test".to_string()],
        is_active: true,
    };

    (workflow, metadata)
}

fn create_test_execution(workflow_id: Uuid, status: ExecutionStatus) -> Execution {
    let status_clone = status.clone();
    Execution {
        id: Uuid::new_v4(),
        workflow_id,
        workflow_version: "1.0.0".to_string(),
        status,
        started_at: if status_clone != ExecutionStatus::Queued {
            Some(Utc::now())
        } else {
            None
        },
        completed_at: if matches!(
            status_clone,
            ExecutionStatus::Completed | ExecutionStatus::Failed | ExecutionStatus::Cancelled
        ) {
            Some(Utc::now())
        } else {
            None
        },
        created_at: Utc::now(),
        triggered_by: Some("test_user".to_string()),
        trigger_type: "manual".to_string(),
        input_params: Some(json!({"key": "value"})),
        result: if status_clone == ExecutionStatus::Completed {
            Some(json!({"result": "success"}))
        } else {
            None
        },
        error: if status_clone == ExecutionStatus::Failed {
            Some("Test error".to_string())
        } else {
            None
        },
        retry_count: 0,
        parent_execution_id: None,
    }
}

// ============================================================================
// WebSocket Message Format Tests
// ============================================================================

#[tokio::test]
async fn test_websocket_started_message_format() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    let execution = create_test_execution(workflow_id, ExecutionStatus::Running);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Simulate Started message
    let message = json!({
        "type": "started",
        "execution_id": execution_id.to_string(),
        "workflow_id": workflow_id.to_string(),
        "started_at": execution.started_at.unwrap().to_rfc3339()
    });

    assert_eq!(message["type"], "started");
    assert_eq!(message["execution_id"], execution_id.to_string());
    assert_eq!(message["workflow_id"], workflow_id.to_string());
    assert!(message["started_at"].is_string());
}

#[tokio::test]
async fn test_websocket_log_message_format() {
    let execution_id = Uuid::new_v4();
    let timestamp = Utc::now();

    let message = json!({
        "type": "log",
        "execution_id": execution_id.to_string(),
        "timestamp": timestamp.to_rfc3339(),
        "level": "INFO",
        "message": "Task execution started"
    });

    assert_eq!(message["type"], "log");
    assert_eq!(message["level"], "INFO");
    assert_eq!(message["message"], "Task execution started");
    assert!(message["timestamp"].is_string());
}

#[tokio::test]
async fn test_websocket_progress_message_format() {
    let execution_id = Uuid::new_v4();

    let message = json!({
        "type": "progress",
        "execution_id": execution_id.to_string(),
        "completed_tasks": 3,
        "total_tasks": 10,
        "percent": 30.0
    });

    assert_eq!(message["type"], "progress");
    assert_eq!(message["completed_tasks"], 3);
    assert_eq!(message["total_tasks"], 10);
    assert_eq!(message["percent"], 30.0);
}

#[tokio::test]
async fn test_websocket_task_update_message_format() {
    let execution_id = Uuid::new_v4();

    let message = json!({
        "type": "task_update",
        "execution_id": execution_id.to_string(),
        "task_id": "task_1",
        "status": "running",
        "message": "Processing data"
    });

    assert_eq!(message["type"], "task_update");
    assert_eq!(message["task_id"], "task_1");
    assert_eq!(message["status"], "running");
    assert_eq!(message["message"], "Processing data");
}

#[tokio::test]
async fn test_websocket_completed_message_format() {
    let execution_id = Uuid::new_v4();
    let completed_at = Utc::now();

    let message = json!({
        "type": "completed",
        "execution_id": execution_id.to_string(),
        "status": "completed",
        "completed_at": completed_at.to_rfc3339(),
        "result": {
            "status": "success",
            "output": "data"
        }
    });

    assert_eq!(message["type"], "completed");
    assert_eq!(message["status"], "completed");
    assert!(message["result"].is_object());
    assert_eq!(message["result"]["status"], "success");
}

#[tokio::test]
async fn test_websocket_failed_message_format() {
    let execution_id = Uuid::new_v4();
    let failed_at = Utc::now();

    let message = json!({
        "type": "failed",
        "execution_id": execution_id.to_string(),
        "error": "Task execution failed",
        "failed_at": failed_at.to_rfc3339()
    });

    assert_eq!(message["type"], "failed");
    assert_eq!(message["error"], "Task execution failed");
    assert!(message["failed_at"].is_string());
}

#[tokio::test]
async fn test_websocket_ping_pong_format() {
    let timestamp = Utc::now();

    let ping = json!({
        "type": "ping",
        "timestamp": timestamp.to_rfc3339()
    });

    let pong = json!({
        "type": "pong",
        "timestamp": timestamp.to_rfc3339()
    });

    assert_eq!(ping["type"], "ping");
    assert_eq!(pong["type"], "pong");
    assert!(ping["timestamp"].is_string());
    assert!(pong["timestamp"].is_string());
}

// ============================================================================
// Execution State Streaming Tests
// ============================================================================

#[tokio::test]
async fn test_stream_execution_state_changes() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    // Create execution and simulate state changes
    let mut execution = create_test_execution(workflow_id, ExecutionStatus::Queued);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Initial state: Queued
    let retrieved = storage.get_execution(execution_id).await.unwrap().unwrap();
    assert_eq!(retrieved.status, ExecutionStatus::Queued);

    // Transition to Running
    execution.status = ExecutionStatus::Running;
    execution.started_at = Some(Utc::now());
    storage
        .update_execution(execution_id, &execution)
        .await
        .unwrap();

    let retrieved = storage.get_execution(execution_id).await.unwrap().unwrap();
    assert_eq!(retrieved.status, ExecutionStatus::Running);

    // Transition to Completed
    execution.status = ExecutionStatus::Completed;
    execution.completed_at = Some(Utc::now());
    execution.result = Some(json!({"status": "success"}));
    storage
        .update_execution(execution_id, &execution)
        .await
        .unwrap();

    let retrieved = storage.get_execution(execution_id).await.unwrap().unwrap();
    assert_eq!(retrieved.status, ExecutionStatus::Completed);
    assert!(retrieved.result.is_some());
}

#[tokio::test]
async fn test_stream_execution_logs() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    let execution = create_test_execution(workflow_id, ExecutionStatus::Running);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Simulate log streaming
    let log_messages = [
        "Initializing workflow",
        "Starting task 1",
        "Task 1 completed",
        "Starting task 2",
        "Task 2 completed",
        "Workflow completed",
    ];

    for (i, message) in log_messages.iter().enumerate() {
        let log = ExecutionLog {
            id: None,
            execution_id,
            task_execution_id: None,
            timestamp: Utc::now(),
            level: if i == log_messages.len() - 1 {
                "INFO".to_string()
            } else {
                "DEBUG".to_string()
            },
            message: message.to_string(),
            metadata: None,
        };
        storage.store_execution_log(&log).await.unwrap();
    }

    // Retrieve all logs
    let logs = storage
        .get_execution_logs(execution_id, None)
        .await
        .unwrap();
    assert_eq!(logs.len(), 6);
    assert_eq!(logs[0].message, "Initializing workflow");
    assert_eq!(logs[5].message, "Workflow completed");
}

#[tokio::test]
async fn test_stream_incremental_logs() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    let execution = create_test_execution(workflow_id, ExecutionStatus::Running);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Store initial logs
    for i in 0..3 {
        let log = ExecutionLog {
            id: None,
            execution_id,
            task_execution_id: None,
            timestamp: Utc::now(),
            level: "INFO".to_string(),
            message: format!("Initial log {}", i),
            metadata: None,
        };
        storage.store_execution_log(&log).await.unwrap();
    }

    let initial_logs = storage
        .get_execution_logs(execution_id, None)
        .await
        .unwrap();
    let initial_count = initial_logs.len();
    assert_eq!(initial_count, 3);

    // Store additional logs (simulating incremental updates)
    for i in 0..2 {
        let log = ExecutionLog {
            id: None,
            execution_id,
            task_execution_id: None,
            timestamp: Utc::now(),
            level: "INFO".to_string(),
            message: format!("New log {}", i),
            metadata: None,
        };
        storage.store_execution_log(&log).await.unwrap();
    }

    let all_logs = storage
        .get_execution_logs(execution_id, None)
        .await
        .unwrap();
    assert_eq!(all_logs.len(), 5);

    // Verify we can get only new logs by tracking count
    let new_logs = &all_logs[initial_count..];
    assert_eq!(new_logs.len(), 2);
    assert_eq!(new_logs[0].message, "New log 0");
}

// ============================================================================
// Progress Tracking Tests
// ============================================================================

#[tokio::test]
async fn test_execution_progress_calculation() {
    // Simulate progress tracking
    let total_tasks = 10;
    let completed_tasks_vec = vec![0, 3, 5, 7, 10];

    for completed_tasks in completed_tasks_vec {
        let percent = (completed_tasks as f64 / total_tasks as f64) * 100.0;

        let progress_message = json!({
            "type": "progress",
            "execution_id": Uuid::new_v4().to_string(),
            "completed_tasks": completed_tasks,
            "total_tasks": total_tasks,
            "percent": percent
        });

        assert_eq!(progress_message["completed_tasks"], completed_tasks);
        assert_eq!(progress_message["total_tasks"], total_tasks);
        assert_eq!(progress_message["percent"], percent);
    }
}

#[tokio::test]
async fn test_execution_with_task_updates() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    let execution = create_test_execution(workflow_id, ExecutionStatus::Running);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Simulate task updates through logs
    let tasks = vec!["task_1", "task_2", "task_3"];
    for task_id in tasks {
        // Task start
        let start_log = ExecutionLog {
            id: None,
            execution_id,
            task_execution_id: Some(Uuid::new_v4()),
            timestamp: Utc::now(),
            level: "INFO".to_string(),
            message: format!("Starting {}", task_id),
            metadata: Some(json!({
                "task_id": task_id,
                "status": "running"
            })),
        };
        storage.store_execution_log(&start_log).await.unwrap();

        // Task complete
        let complete_log = ExecutionLog {
            id: None,
            execution_id,
            task_execution_id: Some(Uuid::new_v4()),
            timestamp: Utc::now(),
            level: "INFO".to_string(),
            message: format!("Completed {}", task_id),
            metadata: Some(json!({
                "task_id": task_id,
                "status": "completed"
            })),
        };
        storage.store_execution_log(&complete_log).await.unwrap();
    }

    let logs = storage
        .get_execution_logs(execution_id, None)
        .await
        .unwrap();
    assert_eq!(logs.len(), 6); // 3 tasks * 2 logs each

    // Verify task metadata
    let task_logs: Vec<_> = logs.iter().filter(|l| l.metadata.is_some()).collect();
    assert_eq!(task_logs.len(), 6);
}

// ============================================================================
// Connection Management Tests
// ============================================================================

#[tokio::test]
async fn test_websocket_connection_for_existing_execution() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    let execution = create_test_execution(workflow_id, ExecutionStatus::Running);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Verify execution exists for WebSocket connection
    let exists = storage.get_execution(execution_id).await.unwrap().is_some();
    assert!(exists);
}

#[tokio::test]
async fn test_websocket_connection_for_nonexistent_execution() {
    let storage = Arc::new(MockStorage::new());
    let non_existent_id = Uuid::new_v4();

    // Verify execution doesn't exist (would return 404)
    let exists = storage
        .get_execution(non_existent_id)
        .await
        .unwrap()
        .is_some();
    assert!(!exists);
}

#[tokio::test]
async fn test_websocket_invalid_execution_id_format() {
    // Test invalid UUID format
    let invalid_ids = vec![
        "not-a-uuid",
        "12345",
        "invalid-uuid-format",
        "",
        "00000000-0000-0000-0000",
    ];

    for invalid_id in invalid_ids {
        let result = Uuid::parse_str(invalid_id);
        assert!(result.is_err());
    }
}

// ============================================================================
// Multiple Concurrent Connections Tests
// ============================================================================

#[tokio::test]
async fn test_multiple_concurrent_websocket_streams() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    // Create multiple executions
    let mut execution_ids = Vec::new();
    for i in 0..5 {
        let status = if i % 2 == 0 {
            ExecutionStatus::Running
        } else {
            ExecutionStatus::Queued
        };
        let execution = create_test_execution(workflow_id, status);
        execution_ids.push(execution.id);
        storage.store_execution(&execution).await.unwrap();
    }

    // Verify all executions can be accessed (simulating multiple WS connections)
    for execution_id in execution_ids {
        let exists = storage.get_execution(execution_id).await.unwrap().is_some();
        assert!(exists);
    }
}

#[tokio::test]
async fn test_websocket_message_ordering() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    let execution = create_test_execution(workflow_id, ExecutionStatus::Running);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Store logs in order
    let messages = vec!["First", "Second", "Third", "Fourth", "Fifth"];
    for message in &messages {
        let log = ExecutionLog {
            id: None,
            execution_id,
            task_execution_id: None,
            timestamp: Utc::now(),
            level: "INFO".to_string(),
            message: message.to_string(),
            metadata: None,
        };
        storage.store_execution_log(&log).await.unwrap();
        // Small delay to ensure timestamp ordering
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
    }

    // Retrieve and verify order
    let logs = storage
        .get_execution_logs(execution_id, None)
        .await
        .unwrap();
    assert_eq!(logs.len(), 5);
    for (i, log) in logs.iter().enumerate() {
        assert_eq!(log.message, messages[i]);
    }
}

// ============================================================================
// Error and Edge Case Tests
// ============================================================================

#[tokio::test]
async fn test_websocket_stream_for_completed_execution() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    // Create already completed execution
    let execution = create_test_execution(workflow_id, ExecutionStatus::Completed);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Should be able to connect and get final state
    let retrieved = storage.get_execution(execution_id).await.unwrap().unwrap();
    assert_eq!(retrieved.status, ExecutionStatus::Completed);
    assert!(retrieved.completed_at.is_some());
    assert!(retrieved.result.is_some());
}

#[tokio::test]
async fn test_websocket_stream_for_failed_execution() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    let execution = create_test_execution(workflow_id, ExecutionStatus::Failed);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // Should be able to connect and get error state
    let retrieved = storage.get_execution(execution_id).await.unwrap().unwrap();
    assert_eq!(retrieved.status, ExecutionStatus::Failed);
    assert!(retrieved.completed_at.is_some());
    assert!(retrieved.error.is_some());
}

#[tokio::test]
async fn test_websocket_with_no_logs() {
    let storage = Arc::new(MockStorage::new());
    let (workflow, metadata) = create_test_workflow("test-workflow");
    let workflow_id = metadata.id;

    storage.store_workflow(&workflow, &metadata).await.unwrap();

    let execution = create_test_execution(workflow_id, ExecutionStatus::Running);
    let execution_id = execution.id;
    storage.store_execution(&execution).await.unwrap();

    // No logs stored yet
    let logs = storage
        .get_execution_logs(execution_id, None)
        .await
        .unwrap();
    assert_eq!(logs.len(), 0);
}

#[tokio::test]
async fn test_websocket_message_serialization() {
    let execution_id = Uuid::new_v4();
    let workflow_id = Uuid::new_v4();

    // Test all message types can be serialized
    let messages: Vec<Value> = vec![
        json!({
            "type": "started",
            "execution_id": execution_id.to_string(),
            "workflow_id": workflow_id.to_string(),
            "started_at": Utc::now().to_rfc3339()
        }),
        json!({
            "type": "log",
            "execution_id": execution_id.to_string(),
            "timestamp": Utc::now().to_rfc3339(),
            "level": "INFO",
            "message": "Test log"
        }),
        json!({
            "type": "progress",
            "execution_id": execution_id.to_string(),
            "completed_tasks": 5,
            "total_tasks": 10,
            "percent": 50.0
        }),
        json!({
            "type": "completed",
            "execution_id": execution_id.to_string(),
            "status": "completed",
            "completed_at": Utc::now().to_rfc3339(),
            "result": {"status": "success"}
        }),
    ];

    for message in messages {
        let serialized = serde_json::to_string(&message);
        assert!(serialized.is_ok());

        let deserialized: Result<Value, _> = serde_json::from_str(&serialized.unwrap());
        assert!(deserialized.is_ok());
    }
}