axonml-server 0.6.0

REST API server for AxonML Machine Learning Framework
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
//! Model registry database operations for AxonML
//!
//! # File
//! `crates/axonml-server/src/db/models.rs`
//!
//! # Author
//! Andrew Jewell Sr - AutomataNexus
//!
//! # Updated
//! March 8, 2026
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

use super::{Database, DbError, DocumentQuery, TimeSeriesQuery};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// Collection names
const MODELS_COLLECTION: &str = "axonml_models";
const VERSIONS_COLLECTION: &str = "axonml_model_versions";
const ENDPOINTS_COLLECTION: &str = "axonml_endpoints";

/// Model data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Model {
    pub id: String,
    pub user_id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub model_type: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// New model creation data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewModel {
    pub user_id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub model_type: String,
}

/// Model version data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelVersion {
    pub id: String,
    pub model_id: String,
    pub version: u32,
    pub file_path: String,
    pub file_size: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metrics: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub training_run_id: Option<String>,
    pub created_at: DateTime<Utc>,
}

/// New model version data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewModelVersion {
    pub model_id: String,
    pub file_path: String,
    pub file_size: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metrics: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub training_run_id: Option<String>,
}

/// Inference endpoint status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum EndpointStatus {
    Starting,
    Running,
    #[default]
    Stopped,
    Error,
}

/// Inference endpoint data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Endpoint {
    pub id: String,
    pub model_version_id: String,
    pub name: String,
    #[serde(default)]
    pub status: EndpointStatus,
    pub port: u16,
    #[serde(default = "default_replicas")]
    pub replicas: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

fn default_replicas() -> u32 {
    1
}

/// New endpoint data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewEndpoint {
    pub model_version_id: String,
    pub name: String,
    pub port: u16,
    #[serde(default = "default_replicas")]
    pub replicas: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<serde_json::Value>,
}

/// Model repository
pub struct ModelRepository<'a> {
    db: &'a Database,
}

impl<'a> ModelRepository<'a> {
    /// Create a new model repository
    pub fn new(db: &'a Database) -> Self {
        Self { db }
    }

    // ========================================================================
    // Model Operations
    // ========================================================================

    /// Create a new model
    pub async fn create(&self, new_model: NewModel) -> Result<Model, DbError> {
        let now = Utc::now();
        let model = Model {
            id: Uuid::new_v4().to_string(),
            user_id: new_model.user_id,
            name: new_model.name,
            description: new_model.description,
            model_type: new_model.model_type,
            created_at: now,
            updated_at: now,
        };

        let model_json = serde_json::to_value(&model)?;

        self.db
            .doc_insert(MODELS_COLLECTION, Some(&model.id), model_json)
            .await?;

        Ok(model)
    }

    /// Find model by ID
    pub async fn find_by_id(&self, id: &str) -> Result<Option<Model>, DbError> {
        let doc = self.db.doc_get(MODELS_COLLECTION, id).await?;

        match doc {
            Some(data) => {
                let model: Model = serde_json::from_value(data)?;
                Ok(Some(model))
            }
            None => Ok(None),
        }
    }

    /// List models for a user
    pub async fn list_by_user(
        &self,
        user_id: &str,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Vec<Model>, DbError> {
        let filter = serde_json::json!({
            "user_id": { "$eq": user_id }
        });

        let query = DocumentQuery {
            filter: Some(filter),
            sort: Some(serde_json::json!({ "field": "created_at", "ascending": false })),
            limit,
            skip: offset,
        };

        let docs = self.db.doc_query(MODELS_COLLECTION, query).await?;

        let mut models = Vec::new();
        for doc in docs {
            let model: Model = serde_json::from_value(doc)?;
            models.push(model);
        }

        Ok(models)
    }

    /// List all models
    pub async fn list_all(
        &self,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Vec<Model>, DbError> {
        let query = DocumentQuery {
            filter: None,
            sort: Some(serde_json::json!({ "field": "created_at", "ascending": false })),
            limit,
            skip: offset,
        };

        let docs = self.db.doc_query(MODELS_COLLECTION, query).await?;

        let mut models = Vec::new();
        for doc in docs {
            let model: Model = serde_json::from_value(doc)?;
            models.push(model);
        }

        Ok(models)
    }

    /// Update model
    pub async fn update(
        &self,
        id: &str,
        name: Option<String>,
        description: Option<String>,
    ) -> Result<Model, DbError> {
        let mut model = self
            .find_by_id(id)
            .await?
            .ok_or_else(|| DbError::NotFound(format!("Model {} not found", id)))?;

        if let Some(n) = name {
            model.name = n;
        }
        if let Some(d) = description {
            model.description = Some(d);
        }
        model.updated_at = Utc::now();

        let model_json = serde_json::to_value(&model)?;

        self.db
            .doc_update(MODELS_COLLECTION, id, model_json)
            .await?;

        Ok(model)
    }

    /// Delete model and all versions
    pub async fn delete(&self, id: &str) -> Result<(), DbError> {
        // Delete all versions first
        let versions = self.list_versions(id).await?;
        for version in versions {
            self.db.doc_delete(VERSIONS_COLLECTION, &version.id).await?;
        }

        // Delete the model
        self.db.doc_delete(MODELS_COLLECTION, id).await?;

        Ok(())
    }

    // ========================================================================
    // Model Version Operations
    // ========================================================================

    /// Create a new model version
    pub async fn create_version(
        &self,
        new_version: NewModelVersion,
    ) -> Result<ModelVersion, DbError> {
        // Get the next version number
        let versions = self.list_versions(&new_version.model_id).await?;
        let next_version = versions
            .iter()
            .map(|v| v.version)
            .max()
            .map(|v| v + 1)
            .unwrap_or(1);

        let version = ModelVersion {
            id: Uuid::new_v4().to_string(),
            model_id: new_version.model_id,
            version: next_version,
            file_path: new_version.file_path,
            file_size: new_version.file_size,
            metrics: new_version.metrics,
            training_run_id: new_version.training_run_id,
            created_at: Utc::now(),
        };

        let version_json = serde_json::to_value(&version)?;

        self.db
            .doc_insert(VERSIONS_COLLECTION, Some(&version.id), version_json)
            .await?;

        Ok(version)
    }

    /// Get model version by ID
    pub async fn get_version(&self, id: &str) -> Result<Option<ModelVersion>, DbError> {
        let doc = self.db.doc_get(VERSIONS_COLLECTION, id).await?;

        match doc {
            Some(data) => {
                let version: ModelVersion = serde_json::from_value(data)?;
                Ok(Some(version))
            }
            None => Ok(None),
        }
    }

    /// Get model version by model ID and version number
    pub async fn get_version_by_number(
        &self,
        model_id: &str,
        version: u32,
    ) -> Result<Option<ModelVersion>, DbError> {
        let filter = serde_json::json!({
            "model_id": { "$eq": model_id },
            "version": { "$eq": version }
        });

        let doc = self.db.doc_find_one(VERSIONS_COLLECTION, filter).await?;

        match doc {
            Some(data) => {
                let ver: ModelVersion = serde_json::from_value(data)?;
                Ok(Some(ver))
            }
            None => Ok(None),
        }
    }

    /// List versions for a model
    pub async fn list_versions(&self, model_id: &str) -> Result<Vec<ModelVersion>, DbError> {
        let filter = serde_json::json!({
            "model_id": { "$eq": model_id }
        });

        let query = DocumentQuery {
            filter: Some(filter),
            sort: Some(serde_json::json!({ "field": "version", "ascending": false })),
            limit: None,
            skip: None,
        };

        let docs = self.db.doc_query(VERSIONS_COLLECTION, query).await?;

        let mut versions = Vec::new();
        for doc in docs {
            let version: ModelVersion = serde_json::from_value(doc)?;
            versions.push(version);
        }

        Ok(versions)
    }

    /// Delete a model version
    pub async fn delete_version(&self, id: &str) -> Result<(), DbError> {
        self.db.doc_delete(VERSIONS_COLLECTION, id).await
    }

    // ========================================================================
    // Endpoint Operations
    // ========================================================================

    /// Create an inference endpoint
    pub async fn create_endpoint(&self, new_endpoint: NewEndpoint) -> Result<Endpoint, DbError> {
        // Check if name already exists
        let existing = self.get_endpoint_by_name(&new_endpoint.name).await?;
        if existing.is_some() {
            return Err(DbError::AlreadyExists(format!(
                "Endpoint with name {} already exists",
                new_endpoint.name
            )));
        }

        let now = Utc::now();
        let endpoint = Endpoint {
            id: Uuid::new_v4().to_string(),
            model_version_id: new_endpoint.model_version_id,
            name: new_endpoint.name,
            status: EndpointStatus::Stopped,
            port: new_endpoint.port,
            replicas: new_endpoint.replicas,
            config: new_endpoint.config,
            error_message: None,
            created_at: now,
            updated_at: now,
        };

        let endpoint_json = serde_json::to_value(&endpoint)?;

        self.db
            .doc_insert(ENDPOINTS_COLLECTION, Some(&endpoint.id), endpoint_json)
            .await?;

        Ok(endpoint)
    }

    /// Get endpoint by ID
    pub async fn get_endpoint(&self, id: &str) -> Result<Option<Endpoint>, DbError> {
        let doc = self.db.doc_get(ENDPOINTS_COLLECTION, id).await?;

        match doc {
            Some(data) => {
                let endpoint: Endpoint = serde_json::from_value(data)?;
                Ok(Some(endpoint))
            }
            None => Ok(None),
        }
    }

    /// Get endpoint by name
    pub async fn get_endpoint_by_name(&self, name: &str) -> Result<Option<Endpoint>, DbError> {
        let filter = serde_json::json!({
            "name": { "$eq": name }
        });

        let doc = self.db.doc_find_one(ENDPOINTS_COLLECTION, filter).await?;

        match doc {
            Some(data) => {
                let endpoint: Endpoint = serde_json::from_value(data)?;
                Ok(Some(endpoint))
            }
            None => Ok(None),
        }
    }

    /// List all endpoints
    pub async fn list_endpoints(&self) -> Result<Vec<Endpoint>, DbError> {
        let query = DocumentQuery {
            filter: None,
            sort: Some(serde_json::json!({ "field": "created_at", "ascending": false })),
            limit: None,
            skip: None,
        };

        let docs = self.db.doc_query(ENDPOINTS_COLLECTION, query).await?;

        let mut endpoints = Vec::new();
        for doc in docs {
            let endpoint: Endpoint = serde_json::from_value(doc)?;
            endpoints.push(endpoint);
        }

        Ok(endpoints)
    }

    /// Update endpoint status
    pub async fn update_endpoint_status(
        &self,
        id: &str,
        status: EndpointStatus,
        error_message: Option<String>,
    ) -> Result<Endpoint, DbError> {
        let mut endpoint = self
            .get_endpoint(id)
            .await?
            .ok_or_else(|| DbError::NotFound(format!("Endpoint {} not found", id)))?;

        endpoint.status = status;
        endpoint.error_message = error_message;
        endpoint.updated_at = Utc::now();

        let endpoint_json = serde_json::to_value(&endpoint)?;

        self.db
            .doc_update(ENDPOINTS_COLLECTION, id, endpoint_json)
            .await?;

        Ok(endpoint)
    }

    /// Update endpoint configuration
    pub async fn update_endpoint(
        &self,
        id: &str,
        replicas: Option<u32>,
        config: Option<serde_json::Value>,
    ) -> Result<Endpoint, DbError> {
        let mut endpoint = self
            .get_endpoint(id)
            .await?
            .ok_or_else(|| DbError::NotFound(format!("Endpoint {} not found", id)))?;

        if let Some(r) = replicas {
            endpoint.replicas = r;
        }
        if let Some(c) = config {
            endpoint.config = Some(c);
        }
        endpoint.updated_at = Utc::now();

        let endpoint_json = serde_json::to_value(&endpoint)?;

        self.db
            .doc_update(ENDPOINTS_COLLECTION, id, endpoint_json)
            .await?;

        Ok(endpoint)
    }

    /// Delete endpoint
    pub async fn delete_endpoint(&self, id: &str) -> Result<(), DbError> {
        // Note: Time series inference metrics are retained for historical analysis
        self.db.doc_delete(ENDPOINTS_COLLECTION, id).await
    }

    // ========================================================================
    // Inference Metrics (Time Series)
    // ========================================================================

    /// Record inference metrics to time series
    pub async fn record_inference_metrics(
        &self,
        endpoint_id: &str,
        requests_total: u64,
        requests_success: u64,
        requests_error: u64,
        latency_p50: f64,
        latency_p95: f64,
        latency_p99: f64,
    ) -> Result<(), DbError> {
        let mut tags: HashMap<String, String> = HashMap::new();
        tags.insert("endpoint_id".to_string(), endpoint_id.to_string());

        // Record request metrics
        let mut req_tags = tags.clone();
        req_tags.insert("metric".to_string(), "requests_total".to_string());
        self.db
            .ts_write_one(
                &format!("axonml.inference.{}.requests_total", endpoint_id),
                requests_total as f64,
                req_tags,
            )
            .await?;

        let mut success_tags = tags.clone();
        success_tags.insert("metric".to_string(), "requests_success".to_string());
        self.db
            .ts_write_one(
                &format!("axonml.inference.{}.requests_success", endpoint_id),
                requests_success as f64,
                success_tags,
            )
            .await?;

        let mut error_tags = tags.clone();
        error_tags.insert("metric".to_string(), "requests_error".to_string());
        self.db
            .ts_write_one(
                &format!("axonml.inference.{}.requests_error", endpoint_id),
                requests_error as f64,
                error_tags,
            )
            .await?;

        // Record latency metrics
        let mut p50_tags = tags.clone();
        p50_tags.insert("metric".to_string(), "latency_p50".to_string());
        self.db
            .ts_write_one(
                &format!("axonml.inference.{}.latency_p50", endpoint_id),
                latency_p50,
                p50_tags,
            )
            .await?;

        let mut p95_tags = tags.clone();
        p95_tags.insert("metric".to_string(), "latency_p95".to_string());
        self.db
            .ts_write_one(
                &format!("axonml.inference.{}.latency_p95", endpoint_id),
                latency_p95,
                p95_tags,
            )
            .await?;

        let mut p99_tags = tags.clone();
        p99_tags.insert("metric".to_string(), "latency_p99".to_string());
        self.db
            .ts_write_one(
                &format!("axonml.inference.{}.latency_p99", endpoint_id),
                latency_p99,
                p99_tags,
            )
            .await?;

        Ok(())
    }

    /// Get inference metrics history from time series
    pub async fn get_inference_metrics(
        &self,
        endpoint_id: &str,
        limit: Option<u32>,
    ) -> Result<Vec<serde_json::Value>, DbError> {
        // Query latency_p50 as the primary metric
        let query = TimeSeriesQuery {
            metric: format!("axonml.inference.{}.latency_p50", endpoint_id),
            start: None,
            end: None,
            tags: None,
            aggregation: None,
            limit,
        };

        let points = self.db.ts_query(query).await?;

        // Convert to JSON for API compatibility
        let metrics: Vec<serde_json::Value> = points
            .into_iter()
            .map(|p| {
                serde_json::json!({
                    "latency_p50": p.value,
                    "timestamp": p.timestamp.to_rfc3339()
                })
            })
            .collect();

        Ok(metrics)
    }

    /// Count running endpoints
    pub async fn count_running_endpoints(&self) -> Result<u64, DbError> {
        let filter = serde_json::json!({
            "status": { "$eq": "running" }
        });

        let query = DocumentQuery {
            filter: Some(filter),
            sort: None,
            limit: None,
            skip: None,
        };

        let docs = self.db.doc_query(ENDPOINTS_COLLECTION, query).await?;
        Ok(docs.len() as u64)
    }
}

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

    #[test]
    fn test_model_serialization() {
        let model = Model {
            id: "model-123".to_string(),
            user_id: "user-456".to_string(),
            name: "Test Model".to_string(),
            description: Some("A test model".to_string()),
            model_type: "transformer".to_string(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        let json = serde_json::to_string(&model).unwrap();
        assert!(json.contains("model-123"));
        assert!(json.contains("transformer"));
    }

    #[test]
    fn test_endpoint_status() {
        let status = EndpointStatus::Running;
        let json = serde_json::to_string(&status).unwrap();
        assert_eq!(json, "\"running\"");
    }
}