synth-ai-core 0.3.0

Rust core for Synth AI SDKs - API client, streaming, tracing, and tunnels
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
//! Job lifecycle management.
//!
//! This module provides job status enums and a state machine for tracking
//! job lifecycle events. It mirrors the Python `synth_ai.sdk.optimization.job`
//! module for portable use across SDKs.

use crate::errors::CoreError;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::time::{SystemTime, UNIX_EPOCH};

/// Job lifecycle status values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JobStatus {
    Pending,
    Queued,
    Running,
    Paused,
    Succeeded,
    Failed,
    Cancelled,
}

impl JobStatus {
    /// Check if this is a terminal (final) status.
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            JobStatus::Succeeded | JobStatus::Failed | JobStatus::Cancelled
        )
    }

    /// Check if this is a success status.
    pub fn is_success(&self) -> bool {
        *self == JobStatus::Succeeded
    }

    /// Parse a status string (case-insensitive, handles aliases).
    ///
    /// Handles common aliases:
    /// - "success", "completed", "complete" → Succeeded
    /// - "in_progress", "running" → Running
    /// - "queued", "pending" → Pending (or Queued if exact)
    /// - "cancelled", "canceled" → Cancelled
    /// - "failed", "failure", "error" → Failed
    pub fn from_str(s: &str) -> Option<Self> {
        let normalized = s.trim().to_lowercase().replace(' ', "_");
        match normalized.as_str() {
            "pending" => Some(JobStatus::Pending),
            "queued" => Some(JobStatus::Queued),
            "running" | "in_progress" => Some(JobStatus::Running),
            "paused" => Some(JobStatus::Paused),
            "succeeded" | "success" | "completed" | "complete" => Some(JobStatus::Succeeded),
            "failed" | "failure" | "error" => Some(JobStatus::Failed),
            "cancelled" | "canceled" | "cancel" => Some(JobStatus::Cancelled),
            _ => None,
        }
    }

    /// Convert to string.
    pub fn as_str(&self) -> &'static str {
        match self {
            JobStatus::Pending => "pending",
            JobStatus::Queued => "queued",
            JobStatus::Running => "running",
            JobStatus::Paused => "paused",
            JobStatus::Succeeded => "succeeded",
            JobStatus::Failed => "failed",
            JobStatus::Cancelled => "cancelled",
        }
    }
}

impl std::fmt::Display for JobStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl Default for JobStatus {
    fn default() -> Self {
        JobStatus::Pending
    }
}

/// Candidate status for optimization jobs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CandidateStatus {
    Evaluating,
    Completed,
    Accepted,
    Rejected,
    Failed,
}

impl CandidateStatus {
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            CandidateStatus::Completed
                | CandidateStatus::Accepted
                | CandidateStatus::Rejected
                | CandidateStatus::Failed
        )
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            CandidateStatus::Evaluating => "evaluating",
            CandidateStatus::Completed => "completed",
            CandidateStatus::Accepted => "accepted",
            CandidateStatus::Rejected => "rejected",
            CandidateStatus::Failed => "failed",
        }
    }
}

impl std::fmt::Display for CandidateStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Job event types following OpenResponses schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum JobEventType {
    #[serde(rename = "job.created")]
    JobCreated,
    #[serde(rename = "job.queued")]
    JobQueued,
    #[serde(rename = "job.in_progress")]
    JobInProgress,
    #[serde(rename = "job.completed")]
    JobCompleted,
    #[serde(rename = "job.failed")]
    JobFailed,
    #[serde(rename = "job.cancelled")]
    JobCancelled,
}

impl JobEventType {
    pub fn as_str(&self) -> &'static str {
        match self {
            JobEventType::JobCreated => "job.created",
            JobEventType::JobQueued => "job.queued",
            JobEventType::JobInProgress => "job.in_progress",
            JobEventType::JobCompleted => "job.completed",
            JobEventType::JobFailed => "job.failed",
            JobEventType::JobCancelled => "job.cancelled",
        }
    }
}

/// A job lifecycle event.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobEvent {
    /// Event type (e.g., "job.in_progress")
    #[serde(rename = "type")]
    pub event_type: String,
    /// Job ID this event belongs to
    pub job_id: String,
    /// Sequence number (1-indexed)
    pub seq: i64,
    /// Unix timestamp (seconds since epoch)
    pub timestamp: f64,
    /// Optional event data payload
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
    /// Optional human-readable message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// Job lifecycle state machine.
///
/// Tracks job status transitions and emits canonical events.
/// Thread-safe for single-owner use; clone for multi-threaded scenarios.
#[derive(Debug, Clone)]
pub struct JobLifecycle {
    job_id: String,
    status: JobStatus,
    events: Vec<JobEvent>,
    started_at: Option<f64>,
    ended_at: Option<f64>,
}

impl JobLifecycle {
    /// Create a new job lifecycle tracker.
    pub fn new(job_id: &str) -> Self {
        Self {
            job_id: job_id.to_string(),
            status: JobStatus::Pending,
            events: Vec::new(),
            started_at: None,
            ended_at: None,
        }
    }

    /// Get the current job status.
    pub fn status(&self) -> JobStatus {
        self.status
    }

    /// Get the job ID.
    pub fn job_id(&self) -> &str {
        &self.job_id
    }

    /// Get elapsed time in seconds, if the job has started.
    pub fn elapsed_seconds(&self) -> Option<f64> {
        let start = self.started_at?;
        let end = self.ended_at.unwrap_or_else(now_timestamp);
        Some(end - start)
    }

    /// Get the history of events.
    pub fn events(&self) -> &[JobEvent] {
        &self.events
    }

    /// Emit an event and record it in history.
    fn emit(
        &mut self,
        event_type: JobEventType,
        data: Option<Value>,
        message: Option<&str>,
    ) -> JobEvent {
        let event = JobEvent {
            event_type: event_type.as_str().to_string(),
            job_id: self.job_id.clone(),
            seq: (self.events.len() + 1) as i64,
            timestamp: now_timestamp(),
            data,
            message: message.map(String::from),
        };
        self.events.push(event.clone());
        event
    }

    /// Start the job (transition from Pending to Running).
    ///
    /// Returns the job.in_progress event.
    pub fn start(&mut self) -> Result<JobEvent, CoreError> {
        self.start_with_data(None, None)
    }

    /// Start the job with optional data and message.
    pub fn start_with_data(
        &mut self,
        data: Option<Value>,
        message: Option<&str>,
    ) -> Result<JobEvent, CoreError> {
        if self.status != JobStatus::Pending {
            return Err(CoreError::Job(crate::errors::JobErrorInfo {
                job_id: self.job_id.clone(),
                message: format!("Cannot start job in {} status", self.status),
                code: Some("INVALID_TRANSITION".to_string()),
            }));
        }

        self.status = JobStatus::Running;
        self.started_at = Some(now_timestamp());

        Ok(self.emit(
            JobEventType::JobInProgress,
            data,
            Some(message.unwrap_or("Job started")),
        ))
    }

    /// Complete the job successfully (transition from Running to Succeeded).
    ///
    /// Returns the job.completed event.
    pub fn complete(&mut self, data: Option<Value>) -> Result<JobEvent, CoreError> {
        self.complete_with_message(data, None)
    }

    /// Complete the job with optional message.
    pub fn complete_with_message(
        &mut self,
        data: Option<Value>,
        message: Option<&str>,
    ) -> Result<JobEvent, CoreError> {
        if self.status != JobStatus::Running {
            return Err(CoreError::Job(crate::errors::JobErrorInfo {
                job_id: self.job_id.clone(),
                message: format!("Cannot complete job in {} status", self.status),
                code: Some("INVALID_TRANSITION".to_string()),
            }));
        }

        self.status = JobStatus::Succeeded;
        self.ended_at = Some(now_timestamp());

        // Add elapsed time to data
        let mut event_data = data.unwrap_or_else(|| Value::Object(Default::default()));
        if let Value::Object(ref mut map) = event_data {
            if let Some(elapsed) = self.elapsed_seconds() {
                map.insert("elapsed_seconds".to_string(), Value::from(elapsed));
            }
        }

        Ok(self.emit(
            JobEventType::JobCompleted,
            Some(event_data),
            Some(message.unwrap_or("Job completed successfully")),
        ))
    }

    /// Fail the job (transition from Running to Failed).
    ///
    /// Returns the job.failed event.
    pub fn fail(&mut self, error: Option<&str>) -> Result<JobEvent, CoreError> {
        self.fail_with_data(error, None)
    }

    /// Fail the job with optional data.
    pub fn fail_with_data(
        &mut self,
        error: Option<&str>,
        data: Option<Value>,
    ) -> Result<JobEvent, CoreError> {
        if self.status != JobStatus::Running && self.status != JobStatus::Pending {
            return Err(CoreError::Job(crate::errors::JobErrorInfo {
                job_id: self.job_id.clone(),
                message: format!("Cannot fail job in {} status", self.status),
                code: Some("INVALID_TRANSITION".to_string()),
            }));
        }

        self.status = JobStatus::Failed;
        self.ended_at = Some(now_timestamp());

        let mut event_data = data.unwrap_or_else(|| Value::Object(Default::default()));
        if let Value::Object(ref mut map) = event_data {
            if let Some(err) = error {
                map.insert("error".to_string(), Value::String(err.to_string()));
            }
            if let Some(elapsed) = self.elapsed_seconds() {
                map.insert("elapsed_seconds".to_string(), Value::from(elapsed));
            }
        }

        Ok(self.emit(
            JobEventType::JobFailed,
            Some(event_data),
            Some(error.unwrap_or("Job failed")),
        ))
    }

    /// Cancel the job (transition to Cancelled from any non-terminal state).
    ///
    /// Returns the job.cancelled event.
    pub fn cancel(&mut self) -> Result<JobEvent, CoreError> {
        self.cancel_with_message(None)
    }

    /// Cancel the job with optional message.
    pub fn cancel_with_message(&mut self, message: Option<&str>) -> Result<JobEvent, CoreError> {
        if self.status.is_terminal() {
            return Err(CoreError::Job(crate::errors::JobErrorInfo {
                job_id: self.job_id.clone(),
                message: format!("Cannot cancel job in {} status", self.status),
                code: Some("INVALID_TRANSITION".to_string()),
            }));
        }

        self.status = JobStatus::Cancelled;
        self.ended_at = Some(now_timestamp());

        let mut event_data = Value::Object(Default::default());
        if let Value::Object(ref mut map) = event_data {
            if let Some(elapsed) = self.elapsed_seconds() {
                map.insert("elapsed_seconds".to_string(), Value::from(elapsed));
            }
        }

        Ok(self.emit(
            JobEventType::JobCancelled,
            Some(event_data),
            Some(message.unwrap_or("Job cancelled")),
        ))
    }
}

/// Get current Unix timestamp in seconds.
fn now_timestamp() -> f64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs_f64())
        .unwrap_or(0.0)
}

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

    #[test]
    fn test_job_status_from_str() {
        assert_eq!(JobStatus::from_str("pending"), Some(JobStatus::Pending));
        assert_eq!(JobStatus::from_str("RUNNING"), Some(JobStatus::Running));
        assert_eq!(JobStatus::from_str("in_progress"), Some(JobStatus::Running));
        assert_eq!(JobStatus::from_str("paused"), Some(JobStatus::Paused));
        assert_eq!(JobStatus::from_str("success"), Some(JobStatus::Succeeded));
        assert_eq!(JobStatus::from_str("completed"), Some(JobStatus::Succeeded));
        assert_eq!(JobStatus::from_str("failed"), Some(JobStatus::Failed));
        assert_eq!(JobStatus::from_str("cancelled"), Some(JobStatus::Cancelled));
        assert_eq!(JobStatus::from_str("canceled"), Some(JobStatus::Cancelled));
        assert_eq!(JobStatus::from_str("unknown"), None);
    }

    #[test]
    fn test_job_status_is_terminal() {
        assert!(!JobStatus::Pending.is_terminal());
        assert!(!JobStatus::Queued.is_terminal());
        assert!(!JobStatus::Running.is_terminal());
        assert!(!JobStatus::Paused.is_terminal());
        assert!(JobStatus::Succeeded.is_terminal());
        assert!(JobStatus::Failed.is_terminal());
        assert!(JobStatus::Cancelled.is_terminal());
    }

    #[test]
    fn test_job_lifecycle_happy_path() {
        let mut lifecycle = JobLifecycle::new("test-job-123");
        assert_eq!(lifecycle.status(), JobStatus::Pending);

        let start_event = lifecycle.start().unwrap();
        assert_eq!(lifecycle.status(), JobStatus::Running);
        assert_eq!(start_event.event_type, "job.in_progress");
        assert_eq!(start_event.seq, 1);

        let complete_event = lifecycle.complete(None).unwrap();
        assert_eq!(lifecycle.status(), JobStatus::Succeeded);
        assert_eq!(complete_event.event_type, "job.completed");
        assert_eq!(complete_event.seq, 2);

        assert!(lifecycle.elapsed_seconds().is_some());
    }

    #[test]
    fn test_job_lifecycle_fail() {
        let mut lifecycle = JobLifecycle::new("test-job-456");
        lifecycle.start().unwrap();

        let fail_event = lifecycle.fail(Some("Something went wrong")).unwrap();
        assert_eq!(lifecycle.status(), JobStatus::Failed);
        assert_eq!(fail_event.event_type, "job.failed");

        if let Some(data) = &fail_event.data {
            assert!(data.get("error").is_some());
        }
    }

    #[test]
    fn test_job_lifecycle_cancel() {
        let mut lifecycle = JobLifecycle::new("test-job-789");
        lifecycle.start().unwrap();

        let cancel_event = lifecycle.cancel().unwrap();
        assert_eq!(lifecycle.status(), JobStatus::Cancelled);
        assert_eq!(cancel_event.event_type, "job.cancelled");
    }

    #[test]
    fn test_invalid_transitions() {
        let mut lifecycle = JobLifecycle::new("test-job-invalid");

        // Can't complete before starting
        assert!(lifecycle.complete(None).is_err());

        lifecycle.start().unwrap();

        // Can't start twice
        assert!(lifecycle.start().is_err());

        lifecycle.complete(None).unwrap();

        // Can't fail after completing
        assert!(lifecycle.fail(None).is_err());

        // Can't cancel after completing
        assert!(lifecycle.cancel().is_err());
    }
}