mockforge-registry-core 0.3.117

Shared domain models, storage abstractions, and OSS-safe handlers for MockForge's registry backends (SaaS Postgres + OSS SQLite admin UI).
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
//! Hosted Mock deployment models
//!
//! Handles cloud-hosted mock service deployments with lifecycle management

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;

/// Hosted mock deployment status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DeploymentStatus {
    Pending,
    Deploying,
    Active,
    Stopped,
    Failed,
    Deleting,
}

impl std::fmt::Display for DeploymentStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DeploymentStatus::Pending => write!(f, "pending"),
            DeploymentStatus::Deploying => write!(f, "deploying"),
            DeploymentStatus::Active => write!(f, "active"),
            DeploymentStatus::Stopped => write!(f, "stopped"),
            DeploymentStatus::Failed => write!(f, "failed"),
            DeploymentStatus::Deleting => write!(f, "deleting"),
        }
    }
}

impl DeploymentStatus {
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "pending" => Some(DeploymentStatus::Pending),
            "deploying" => Some(DeploymentStatus::Deploying),
            "active" => Some(DeploymentStatus::Active),
            "stopped" => Some(DeploymentStatus::Stopped),
            "failed" => Some(DeploymentStatus::Failed),
            "deleting" => Some(DeploymentStatus::Deleting),
            _ => None,
        }
    }
}

/// Health status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthStatus {
    Healthy,
    Unhealthy,
    Unknown,
}

impl std::fmt::Display for HealthStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HealthStatus::Healthy => write!(f, "healthy"),
            HealthStatus::Unhealthy => write!(f, "unhealthy"),
            HealthStatus::Unknown => write!(f, "unknown"),
        }
    }
}

impl HealthStatus {
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "healthy" => Some(HealthStatus::Healthy),
            "unhealthy" => Some(HealthStatus::Unhealthy),
            "unknown" => Some(HealthStatus::Unknown),
            _ => None,
        }
    }
}

/// Hosted mock deployment
#[derive(Debug, Clone, FromRow, Serialize, Deserialize)]
pub struct HostedMock {
    pub id: Uuid,
    pub org_id: Uuid,
    pub project_id: Option<Uuid>,
    pub name: String,
    pub slug: String,
    pub description: Option<String>,
    pub config_json: serde_json::Value,
    pub openapi_spec_url: Option<String>,
    pub status: String, // Stored as VARCHAR, converted via methods
    pub deployment_url: Option<String>,
    pub internal_url: Option<String>,
    pub region: String,
    pub instance_type: String,
    pub health_check_url: Option<String>,
    pub last_health_check: Option<DateTime<Utc>>,
    pub health_status: String, // Stored as VARCHAR, converted via methods
    pub error_message: Option<String>,
    pub metadata_json: serde_json::Value,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub deleted_at: Option<DateTime<Utc>>,
}

#[cfg(feature = "postgres")]
impl HostedMock {
    /// Get status as enum
    pub fn status(&self) -> DeploymentStatus {
        DeploymentStatus::from_str(&self.status).unwrap_or(DeploymentStatus::Pending)
    }

    /// Get health status as enum
    pub fn health_status(&self) -> HealthStatus {
        HealthStatus::from_str(&self.health_status).unwrap_or(HealthStatus::Unknown)
    }

    /// Create a new hosted mock deployment
    #[allow(clippy::too_many_arguments)]
    pub async fn create(
        pool: &sqlx::PgPool,
        org_id: Uuid,
        project_id: Option<Uuid>,
        name: &str,
        slug: &str,
        description: Option<&str>,
        config_json: serde_json::Value,
        openapi_spec_url: Option<&str>,
        region: Option<&str>,
    ) -> sqlx::Result<Self> {
        let region = region.unwrap_or("iad");
        sqlx::query_as::<_, Self>(
            r#"
            INSERT INTO hosted_mocks (
                org_id, project_id, name, slug, description,
                config_json, openapi_spec_url, region, status, health_status
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', 'unknown')
            RETURNING *
            "#,
        )
        .bind(org_id)
        .bind(project_id)
        .bind(name)
        .bind(slug)
        .bind(description)
        .bind(config_json)
        .bind(openapi_spec_url)
        .bind(region)
        .fetch_one(pool)
        .await
    }

    /// Find by ID
    pub async fn find_by_id(pool: &sqlx::PgPool, id: Uuid) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>("SELECT * FROM hosted_mocks WHERE id = $1 AND deleted_at IS NULL")
            .bind(id)
            .fetch_optional(pool)
            .await
    }

    /// Find by slug and org
    pub async fn find_by_slug(
        pool: &sqlx::PgPool,
        org_id: Uuid,
        slug: &str,
    ) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM hosted_mocks WHERE org_id = $1 AND slug = $2 AND deleted_at IS NULL",
        )
        .bind(org_id)
        .bind(slug)
        .fetch_optional(pool)
        .await
    }

    /// Find an active deployment by slug (across all orgs).
    /// Used for custom domain routing where only the slug is known from the hostname.
    pub async fn find_active_by_slug(
        pool: &sqlx::PgPool,
        slug: &str,
    ) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM hosted_mocks WHERE slug = $1 AND status = 'active' AND deleted_at IS NULL LIMIT 1",
        )
        .bind(slug)
        .fetch_optional(pool)
        .await
    }

    /// Find all mocks for an organization
    pub async fn find_by_org(pool: &sqlx::PgPool, org_id: Uuid) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM hosted_mocks WHERE org_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC",
        )
        .bind(org_id)
        .fetch_all(pool)
        .await
    }

    /// Find all mocks for a project
    pub async fn find_by_project(pool: &sqlx::PgPool, project_id: Uuid) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM hosted_mocks WHERE project_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC",
        )
        .bind(project_id)
        .fetch_all(pool)
        .await
    }

    /// Update deployment status
    pub async fn update_status(
        pool: &sqlx::PgPool,
        id: Uuid,
        status: DeploymentStatus,
        error_message: Option<&str>,
    ) -> sqlx::Result<()> {
        sqlx::query(
            r#"
            UPDATE hosted_mocks
            SET status = $1, error_message = $2, updated_at = NOW()
            WHERE id = $3
            "#,
        )
        .bind(status.to_string())
        .bind(error_message)
        .bind(id)
        .execute(pool)
        .await?;
        Ok(())
    }

    /// Update deployment URLs
    pub async fn update_urls(
        pool: &sqlx::PgPool,
        id: Uuid,
        deployment_url: Option<&str>,
        internal_url: Option<&str>,
    ) -> sqlx::Result<()> {
        sqlx::query(
            r#"
            UPDATE hosted_mocks
            SET deployment_url = $1, internal_url = $2, updated_at = NOW()
            WHERE id = $3
            "#,
        )
        .bind(deployment_url)
        .bind(internal_url)
        .bind(id)
        .execute(pool)
        .await?;
        Ok(())
    }

    /// Update health status
    pub async fn update_health(
        pool: &sqlx::PgPool,
        id: Uuid,
        health_status: HealthStatus,
        health_check_url: Option<&str>,
    ) -> sqlx::Result<()> {
        sqlx::query(
            r#"
            UPDATE hosted_mocks
            SET health_status = $1, health_check_url = $2, last_health_check = NOW(), updated_at = NOW()
            WHERE id = $3
            "#,
        )
        .bind(health_status.to_string())
        .bind(health_check_url)
        .bind(id)
        .execute(pool)
        .await?;
        Ok(())
    }

    /// Soft delete (mark as deleted)
    pub async fn delete(pool: &sqlx::PgPool, id: Uuid) -> sqlx::Result<()> {
        sqlx::query(
            "UPDATE hosted_mocks SET deleted_at = NOW(), status = 'deleting', updated_at = NOW() WHERE id = $1",
        )
        .bind(id)
        .execute(pool)
        .await?;
        Ok(())
    }
}

/// Deployment log entry
#[derive(Debug, Clone, FromRow, Serialize, Deserialize)]
pub struct DeploymentLog {
    pub id: Uuid,
    pub hosted_mock_id: Uuid,
    pub level: String,
    pub message: String,
    pub metadata_json: serde_json::Value,
    pub created_at: DateTime<Utc>,
}

#[cfg(feature = "postgres")]
impl DeploymentLog {
    /// Create a new log entry
    pub async fn create(
        pool: &sqlx::PgPool,
        hosted_mock_id: Uuid,
        level: &str,
        message: &str,
        metadata: Option<serde_json::Value>,
    ) -> sqlx::Result<Self> {
        sqlx::query_as::<_, Self>(
            r#"
            INSERT INTO deployment_logs (hosted_mock_id, level, message, metadata_json)
            VALUES ($1, $2, $3, $4)
            RETURNING *
            "#,
        )
        .bind(hosted_mock_id)
        .bind(level)
        .bind(message)
        .bind(metadata.unwrap_or_else(|| serde_json::json!({})))
        .fetch_one(pool)
        .await
    }

    /// Get logs for a deployment
    pub async fn find_by_mock(
        pool: &sqlx::PgPool,
        hosted_mock_id: Uuid,
        limit: Option<i64>,
    ) -> sqlx::Result<Vec<Self>> {
        let limit = limit.unwrap_or(100);
        sqlx::query_as::<_, Self>(
            "SELECT * FROM deployment_logs WHERE hosted_mock_id = $1 ORDER BY created_at DESC LIMIT $2",
        )
        .bind(hosted_mock_id)
        .bind(limit)
        .fetch_all(pool)
        .await
    }
}

/// Deployment metrics
#[derive(Debug, Clone, FromRow, Serialize, Deserialize)]
pub struct DeploymentMetrics {
    pub id: Uuid,
    pub hosted_mock_id: Uuid,
    pub period_start: chrono::NaiveDate,
    pub requests: i64,
    pub requests_2xx: i64,
    pub requests_4xx: i64,
    pub requests_5xx: i64,
    pub egress_bytes: i64,
    pub avg_response_time_ms: i64,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[cfg(feature = "postgres")]
impl DeploymentMetrics {
    /// Get or create metrics for current period
    pub async fn get_or_create_current(
        pool: &sqlx::PgPool,
        hosted_mock_id: Uuid,
    ) -> sqlx::Result<Self> {
        use chrono::Datelike;
        let now = chrono::Utc::now().date_naive();
        let period_start =
            chrono::NaiveDate::from_ymd_opt(now.year(), now.month(), 1).unwrap_or(now);

        // Try to get existing
        if let Some(metrics) = sqlx::query_as::<_, Self>(
            "SELECT * FROM deployment_metrics WHERE hosted_mock_id = $1 AND period_start = $2",
        )
        .bind(hosted_mock_id)
        .bind(period_start)
        .fetch_optional(pool)
        .await?
        {
            return Ok(metrics);
        }

        // Create new
        sqlx::query_as::<_, Self>(
            r#"
            INSERT INTO deployment_metrics (hosted_mock_id, period_start)
            VALUES ($1, $2)
            RETURNING *
            "#,
        )
        .bind(hosted_mock_id)
        .bind(period_start)
        .fetch_one(pool)
        .await
    }

    /// Increment request counters
    pub async fn increment_requests(
        pool: &sqlx::PgPool,
        hosted_mock_id: Uuid,
        status_code: u16,
        response_time_ms: u64,
    ) -> sqlx::Result<()> {
        let metrics = Self::get_or_create_current(pool, hosted_mock_id).await?;

        let (increment_2xx, increment_4xx, increment_5xx) = if (200..300).contains(&status_code) {
            (1, 0, 0)
        } else if (400..500).contains(&status_code) {
            (0, 1, 0)
        } else if status_code >= 500 {
            (0, 0, 1)
        } else {
            (0, 0, 0)
        };

        // Update average response time (simple moving average)
        let new_avg = if metrics.requests > 0 {
            ((metrics.avg_response_time_ms as f64 * metrics.requests as f64
                + response_time_ms as f64)
                / (metrics.requests + 1) as f64) as i64
        } else {
            response_time_ms as i64
        };

        sqlx::query(
            r#"
            UPDATE deployment_metrics
            SET
                requests = requests + 1,
                requests_2xx = requests_2xx + $1,
                requests_4xx = requests_4xx + $2,
                requests_5xx = requests_5xx + $3,
                avg_response_time_ms = $4,
                updated_at = NOW()
            WHERE id = $5
            "#,
        )
        .bind(increment_2xx)
        .bind(increment_4xx)
        .bind(increment_5xx)
        .bind(new_avg)
        .bind(metrics.id)
        .execute(pool)
        .await?;

        Ok(())
    }

    /// Increment egress bytes
    pub async fn increment_egress(
        pool: &sqlx::PgPool,
        hosted_mock_id: Uuid,
        bytes: i64,
    ) -> sqlx::Result<()> {
        let metrics = Self::get_or_create_current(pool, hosted_mock_id).await?;

        sqlx::query(
            r#"
            UPDATE deployment_metrics
            SET egress_bytes = egress_bytes + $1, updated_at = NOW()
            WHERE id = $2
            "#,
        )
        .bind(bytes)
        .bind(metrics.id)
        .execute(pool)
        .await?;

        Ok(())
    }
}