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
// Schedule handlers

#[cfg(feature = "server")]
use axum::{
    extract::{Extension, Path, Query},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
#[cfg(feature = "server")]
use chrono::Utc;
#[cfg(feature = "server")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "server")]
use serde_json::json;
#[cfg(feature = "server")]
use std::sync::Arc;
#[cfg(feature = "server")]
use uuid::Uuid;

#[cfg(feature = "server")]
use crate::server::auth::jwt::Claims;
#[cfg(feature = "server")]
use crate::server::queue::{Job, WorkQueue};
#[cfg(feature = "server")]
use crate::server::{
    storage::{Schedule, ScheduleFilter},
    Storage,
};

// Request/Response types
#[cfg(feature = "server")]
#[derive(Debug, Deserialize)]
pub struct ListSchedulesQuery {
    pub workflow_id: Option<Uuid>,
    pub is_active: Option<bool>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
}

#[cfg(feature = "server")]
#[derive(Debug, Serialize)]
pub struct ScheduleResponse {
    pub id: Uuid,
    pub workflow_id: Uuid,
    pub cron_expression: String,
    pub timezone: String,
    pub is_active: bool,
    pub input_params: Option<serde_json::Value>,
    pub created_at: String,
    pub updated_at: String,
    pub created_by: Option<String>,
    pub last_run_at: Option<String>,
    pub next_run_at: Option<String>,
    pub description: Option<String>,
}

#[cfg(feature = "server")]
impl From<Schedule> for ScheduleResponse {
    fn from(schedule: Schedule) -> Self {
        Self {
            id: schedule.id,
            workflow_id: schedule.workflow_id,
            cron_expression: schedule.cron_expression,
            timezone: schedule.timezone,
            is_active: schedule.is_active,
            input_params: schedule.input_params,
            created_at: schedule.created_at.to_rfc3339(),
            updated_at: schedule.updated_at.to_rfc3339(),
            created_by: schedule.created_by,
            last_run_at: schedule.last_run_at.map(|dt| dt.to_rfc3339()),
            next_run_at: schedule.next_run_at.map(|dt| dt.to_rfc3339()),
            description: schedule.description,
        }
    }
}

#[cfg(feature = "server")]
#[derive(Debug, Deserialize)]
pub struct CreateScheduleRequest {
    pub workflow_id: Uuid,
    pub cron_expression: String,
    pub timezone: Option<String>,
    pub input_params: Option<serde_json::Value>,
    pub description: Option<String>,
}

#[cfg(feature = "server")]
#[derive(Debug, Deserialize)]
pub struct UpdateScheduleRequest {
    pub cron_expression: Option<String>,
    pub timezone: Option<String>,
    pub is_active: Option<bool>,
    pub input_params: Option<serde_json::Value>,
    pub description: Option<String>,
}

// Handler implementations

/// List schedules with filtering and pagination
#[cfg(feature = "server")]
pub async fn list_schedules(
    Query(query): Query<ListSchedulesQuery>,
    Extension(storage): Extension<Arc<dyn Storage>>,
    Extension(_claims): Extension<Claims>,
) -> impl IntoResponse {
    let filter = ScheduleFilter {
        workflow_id: query.workflow_id,
        is_active: query.is_active,
        created_by: None,
        limit: query.limit,
        offset: query.offset,
    };

    match storage.list_schedules(&filter).await {
        Ok(schedules) => {
            let responses: Vec<ScheduleResponse> =
                schedules.into_iter().map(ScheduleResponse::from).collect();

            (
                StatusCode::OK,
                Json(json!({
                    "schedules": responses,
                    "total": responses.len(),
                    "offset": filter.offset.unwrap_or(0),
                    "limit": filter.limit.unwrap_or(100),
                })),
            )
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Failed to list schedules",
                "message": e.to_string()
            })),
        ),
    }
}

/// Create a new schedule
#[cfg(feature = "server")]
pub async fn create_schedule(
    Extension(storage): Extension<Arc<dyn Storage>>,
    Extension(claims): Extension<Claims>,
    Json(payload): Json<CreateScheduleRequest>,
) -> impl IntoResponse {
    // Validate workflow exists
    match storage.get_workflow(payload.workflow_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({
                    "error": "Workflow not found",
                    "workflow_id": payload.workflow_id
                })),
            );
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "Failed to validate workflow",
                    "message": e.to_string()
                })),
            );
        }
    }

    // TODO: Validate cron expression
    // For now, just accept any string

    let schedule = Schedule {
        id: Uuid::new_v4(),
        workflow_id: payload.workflow_id,
        cron_expression: payload.cron_expression,
        timezone: payload.timezone.unwrap_or_else(|| "UTC".to_string()),
        is_active: true,
        input_params: payload.input_params,
        created_at: Utc::now(),
        updated_at: Utc::now(),
        created_by: Some(claims.sub.clone()),
        last_run_at: None,
        next_run_at: None, // TODO: Calculate next run time from cron expression
        description: payload.description,
    };

    match storage.store_schedule(&schedule).await {
        Ok(id) => (
            StatusCode::CREATED,
            Json(json!({
                "id": id,
                "workflow_id": schedule.workflow_id,
                "message": "Schedule created successfully"
            })),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Failed to create schedule",
                "message": e.to_string()
            })),
        ),
    }
}

/// Get a specific schedule by ID
#[cfg(feature = "server")]
pub async fn get_schedule(
    Path(id): Path<Uuid>,
    Extension(storage): Extension<Arc<dyn Storage>>,
    Extension(_claims): Extension<Claims>,
) -> impl IntoResponse {
    match storage.get_schedule(id).await {
        Ok(Some(schedule)) => {
            let response = ScheduleResponse::from(schedule);
            (StatusCode::OK, Json(json!(response)))
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(json!({
                "error": "Schedule not found",
                "id": id
            })),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Failed to get schedule",
                "message": e.to_string()
            })),
        ),
    }
}

/// Update an existing schedule
#[cfg(feature = "server")]
pub async fn update_schedule(
    Path(id): Path<Uuid>,
    Extension(storage): Extension<Arc<dyn Storage>>,
    Extension(_claims): Extension<Claims>,
    Json(payload): Json<UpdateScheduleRequest>,
) -> impl IntoResponse {
    // Get existing schedule
    let mut schedule = match storage.get_schedule(id).await {
        Ok(Some(schedule)) => schedule,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({
                    "error": "Schedule not found",
                    "id": id
                })),
            );
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "Failed to get schedule",
                    "message": e.to_string()
                })),
            );
        }
    };

    // Update fields
    if let Some(cron_expression) = payload.cron_expression {
        // TODO: Validate cron expression
        schedule.cron_expression = cron_expression;
        schedule.next_run_at = None; // TODO: Recalculate next run time
    }

    if let Some(timezone) = payload.timezone {
        schedule.timezone = timezone;
        schedule.next_run_at = None; // TODO: Recalculate next run time
    }

    if let Some(is_active) = payload.is_active {
        schedule.is_active = is_active;
    }

    if let Some(input_params) = payload.input_params {
        schedule.input_params = Some(input_params);
    }

    if let Some(description) = payload.description {
        schedule.description = Some(description);
    }

    schedule.updated_at = Utc::now();

    match storage.update_schedule(id, &schedule).await {
        Ok(_) => (
            StatusCode::OK,
            Json(json!({
                "id": id,
                "message": "Schedule updated successfully",
                "updated_at": schedule.updated_at.to_rfc3339()
            })),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Failed to update schedule",
                "message": e.to_string()
            })),
        ),
    }
}

/// Delete a schedule
#[cfg(feature = "server")]
pub async fn delete_schedule(
    Path(id): Path<Uuid>,
    Extension(storage): Extension<Arc<dyn Storage>>,
    Extension(_claims): Extension<Claims>,
) -> impl IntoResponse {
    // Check if schedule exists
    match storage.get_schedule(id).await {
        Ok(Some(_)) => {
            // Schedule exists, proceed with deletion
            match storage.delete_schedule(id).await {
                Ok(_) => (StatusCode::NO_CONTENT, Json(json!({}))),
                Err(e) => (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({
                        "error": "Failed to delete schedule",
                        "message": e.to_string()
                    })),
                ),
            }
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(json!({
                "error": "Schedule not found",
                "id": id
            })),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Failed to check schedule",
                "message": e.to_string()
            })),
        ),
    }
}

/// Manually trigger a scheduled workflow
#[cfg(feature = "server")]
pub async fn trigger_schedule(
    Path(id): Path<Uuid>,
    Extension(storage): Extension<Arc<dyn Storage>>,
    Extension(queue): Extension<Arc<dyn WorkQueue>>,
    Extension(claims): Extension<Claims>,
) -> impl IntoResponse {
    // Get schedule
    let schedule = match storage.get_schedule(id).await {
        Ok(Some(schedule)) => schedule,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({
                    "error": "Schedule not found",
                    "id": id
                })),
            );
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "Failed to get schedule",
                    "message": e.to_string()
                })),
            );
        }
    };

    // Get workflow
    let (workflow, _) = match storage.get_workflow(schedule.workflow_id).await {
        Ok(Some(wf)) => wf,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({
                    "error": "Workflow not found",
                    "workflow_id": schedule.workflow_id
                })),
            );
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "Failed to get workflow",
                    "message": e.to_string()
                })),
            );
        }
    };

    // Create execution record (similar to create_execution handler)
    use crate::server::storage::{Execution, ExecutionStatus};

    let execution = Execution {
        id: Uuid::new_v4(),
        workflow_id: schedule.workflow_id,
        workflow_version: workflow.version.clone(),
        status: ExecutionStatus::Queued,
        started_at: None,
        completed_at: None,
        created_at: Utc::now(),
        triggered_by: Some(claims.sub.clone()),
        trigger_type: "scheduled_manual".to_string(),
        input_params: schedule.input_params.clone(),
        result: None,
        error: None,
        retry_count: 0,
        parent_execution_id: None,
    };

    let execution_id = match storage.store_execution(&execution).await {
        Ok(id) => id,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "Failed to create execution",
                    "message": e.to_string()
                })),
            );
        }
    };

    // Create job for queue
    let job_payload = json!({
        "workflow": workflow,
        "input_params": schedule.input_params,
    });

    let job = Job::new(schedule.workflow_id, execution_id, job_payload);

    // Enqueue job
    match queue.enqueue(job).await {
        Ok(_) => (
            StatusCode::CREATED,
            Json(json!({
                "schedule_id": id,
                "execution_id": execution_id,
                "workflow_id": schedule.workflow_id,
                "status": "queued",
                "message": "Schedule triggered successfully"
            })),
        ),
        Err(e) => {
            // Mark execution as failed
            let mut failed_execution = execution;
            failed_execution.status = ExecutionStatus::Failed;
            failed_execution.error = Some(format!("Failed to queue job: {}", e));
            let _ = storage
                .update_execution(execution_id, &failed_execution)
                .await;

            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": "Failed to queue execution",
                    "message": e.to_string()
                })),
            )
        }
    }
}