mockforge-registry-core 0.3.137

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
//! Contract Diff / Verification / Fitness models
//! (cloud-enablement task #8 / Phase 1).
//!
//! Probe runs reuse the #4 worker pool with kind values 'contract_diff'
//! / 'verification_suite' / 'fitness_evaluation'. Drift findings raise
//! incidents through the #3 IncidentBus once integrated.
//!
//! See docs/cloud/CLOUD_CONTRACT_VERIFICATION_DESIGN.md.

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

#[cfg(feature = "postgres")]
use sqlx::{FromRow, PgPool};

#[cfg_attr(feature = "postgres", derive(FromRow))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoredService {
    pub id: Uuid,
    pub workspace_id: Uuid,
    pub name: String,
    pub base_url: String,
    #[serde(default)]
    pub openapi_spec_url: Option<String>,
    #[serde(default)]
    pub openapi_spec_inline: Option<serde_json::Value>,
    #[serde(default)]
    pub auth_config: Option<serde_json::Value>,
    pub traffic_source: String,
    #[serde(default)]
    pub traffic_source_ref: Option<String>,
    pub enabled: bool,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[cfg_attr(feature = "postgres", derive(FromRow))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractDiffRun {
    pub id: Uuid,
    pub monitored_service_id: Uuid,
    pub triggered_by: String,
    pub status: String,
    pub started_at: DateTime<Utc>,
    #[serde(default)]
    pub finished_at: Option<DateTime<Utc>>,
    pub breaking_changes_count: i32,
    pub non_breaking_changes_count: i32,
    #[serde(default)]
    pub summary: Option<serde_json::Value>,
}

#[cfg_attr(feature = "postgres", derive(FromRow))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractDiffFinding {
    pub id: Uuid,
    pub run_id: Uuid,
    pub severity: String,
    pub endpoint: String,
    #[serde(default)]
    pub method: Option<String>,
    #[serde(default)]
    pub field_path: Option<String>,
    pub description: String,
    #[serde(default)]
    pub confidence: Option<f64>,
    #[serde(default)]
    pub suggested_fix: Option<serde_json::Value>,
}

#[cfg_attr(feature = "postgres", derive(FromRow))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FitnessFunction {
    pub id: Uuid,
    pub workspace_id: Uuid,
    pub name: String,
    pub kind: String,
    pub config: serde_json::Value,
    #[serde(default)]
    pub last_evaluated_at: Option<DateTime<Utc>>,
    #[serde(default)]
    pub last_status: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[cfg_attr(feature = "postgres", derive(FromRow))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationSuite {
    pub id: Uuid,
    pub workspace_id: Uuid,
    pub name: String,
    pub contract_check_ids: Vec<Uuid>,
    pub fitness_function_ids: Vec<Uuid>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[cfg(feature = "postgres")]
pub struct CreateMonitoredService<'a> {
    pub workspace_id: Uuid,
    pub name: &'a str,
    pub base_url: &'a str,
    pub openapi_spec_url: Option<&'a str>,
    pub openapi_spec_inline: Option<&'a serde_json::Value>,
    pub auth_config: Option<&'a serde_json::Value>,
    pub traffic_source: &'a str,
    pub traffic_source_ref: Option<&'a str>,
}

#[cfg(feature = "postgres")]
impl MonitoredService {
    pub const VALID_TRAFFIC_SOURCES: &'static [&'static str] =
        &["logs", "capture_session", "probe"];

    pub fn is_valid_traffic_source(s: &str) -> bool {
        Self::VALID_TRAFFIC_SOURCES.contains(&s)
    }

    pub async fn list_by_workspace(pool: &PgPool, workspace_id: Uuid) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM monitored_services WHERE workspace_id = $1 ORDER BY name",
        )
        .bind(workspace_id)
        .fetch_all(pool)
        .await
    }

    pub async fn find_by_id(pool: &PgPool, id: Uuid) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>("SELECT * FROM monitored_services WHERE id = $1")
            .bind(id)
            .fetch_optional(pool)
            .await
    }

    pub async fn create(pool: &PgPool, input: CreateMonitoredService<'_>) -> sqlx::Result<Self> {
        sqlx::query_as::<_, Self>(
            r#"
            INSERT INTO monitored_services
                (workspace_id, name, base_url, openapi_spec_url, openapi_spec_inline,
                 auth_config, traffic_source, traffic_source_ref)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
            RETURNING *
            "#,
        )
        .bind(input.workspace_id)
        .bind(input.name)
        .bind(input.base_url)
        .bind(input.openapi_spec_url)
        .bind(input.openapi_spec_inline)
        .bind(input.auth_config)
        .bind(input.traffic_source)
        .bind(input.traffic_source_ref)
        .fetch_one(pool)
        .await
    }

    pub async fn delete(pool: &PgPool, id: Uuid) -> sqlx::Result<bool> {
        let rows = sqlx::query("DELETE FROM monitored_services WHERE id = $1")
            .bind(id)
            .execute(pool)
            .await?
            .rows_affected();
        Ok(rows > 0)
    }
}

#[cfg(feature = "postgres")]
impl FitnessFunction {
    pub const VALID_KINDS: &'static [&'static str] = &[
        "latency_threshold",
        "error_rate",
        "contract_stability",
        "custom_query",
    ];

    pub fn is_valid_kind(s: &str) -> bool {
        Self::VALID_KINDS.contains(&s)
    }

    pub async fn list_by_workspace(pool: &PgPool, workspace_id: Uuid) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM fitness_functions WHERE workspace_id = $1 ORDER BY name",
        )
        .bind(workspace_id)
        .fetch_all(pool)
        .await
    }

    pub async fn find_by_id(pool: &PgPool, id: Uuid) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>("SELECT * FROM fitness_functions WHERE id = $1")
            .bind(id)
            .fetch_optional(pool)
            .await
    }

    pub async fn create(
        pool: &PgPool,
        workspace_id: Uuid,
        name: &str,
        kind: &str,
        config: &serde_json::Value,
    ) -> sqlx::Result<Self> {
        sqlx::query_as::<_, Self>(
            r#"
            INSERT INTO fitness_functions (workspace_id, name, kind, config)
            VALUES ($1, $2, $3, $4)
            RETURNING *
            "#,
        )
        .bind(workspace_id)
        .bind(name)
        .bind(kind)
        .bind(config)
        .fetch_one(pool)
        .await
    }

    pub async fn delete(pool: &PgPool, id: Uuid) -> sqlx::Result<bool> {
        let rows = sqlx::query("DELETE FROM fitness_functions WHERE id = $1")
            .bind(id)
            .execute(pool)
            .await?
            .rows_affected();
        Ok(rows > 0)
    }

    /// Replace the mutable fields (name, kind, config) on an existing
    /// fitness function. Returns `Ok(None)` if the row doesn't exist
    /// rather than erroring — caller can map that to a 404. Bumps
    /// `updated_at` (no DB trigger covers this column on the table).
    pub async fn update(
        pool: &PgPool,
        id: Uuid,
        name: &str,
        kind: &str,
        config: &serde_json::Value,
    ) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>(
            r#"
            UPDATE fitness_functions
            SET name = $2, kind = $3, config = $4, updated_at = NOW()
            WHERE id = $1
            RETURNING *
            "#,
        )
        .bind(id)
        .bind(name)
        .bind(kind)
        .bind(config)
        .fetch_optional(pool)
        .await
    }

    /// Persist a per-evaluation row + roll up `last_evaluated_at` /
    /// `last_status` on the parent function in one transaction.
    ///
    /// Called by `mirror_kind_status` when a `kind='fitness_evaluation'`
    /// test_run finishes — the run's `summary` carries the values
    /// pulled into `measured_value` / `threshold_value`. `status` must
    /// be one of `pass | fail | unknown`. The history row in
    /// `fitness_evaluations` is append-only; the `last_*` columns
    /// give the UI a fast read for the "last run" widget without
    /// scanning the timeline.
    pub async fn record_evaluation(
        pool: &PgPool,
        function_id: Uuid,
        status: &str,
        measured_value: Option<f64>,
        threshold_value: Option<f64>,
    ) -> sqlx::Result<()> {
        let mut tx = pool.begin().await?;
        sqlx::query(
            r#"
            INSERT INTO fitness_evaluations
                (function_id, status, measured_value, threshold_value)
            VALUES ($1, $2, $3, $4)
            "#,
        )
        .bind(function_id)
        .bind(status)
        .bind(measured_value)
        .bind(threshold_value)
        .execute(&mut *tx)
        .await?;
        sqlx::query(
            r#"
            UPDATE fitness_functions
            SET last_evaluated_at = NOW(),
                last_status = $2,
                updated_at = NOW()
            WHERE id = $1
            "#,
        )
        .bind(function_id)
        .bind(status)
        .execute(&mut *tx)
        .await?;
        tx.commit().await
    }
}

#[cfg(feature = "postgres")]
impl ContractDiffRun {
    pub async fn list_by_service(
        pool: &PgPool,
        service_id: Uuid,
        limit: i64,
    ) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM contract_diff_runs WHERE monitored_service_id = $1 \
             ORDER BY started_at DESC LIMIT $2",
        )
        .bind(service_id)
        .bind(limit)
        .fetch_all(pool)
        .await
    }

    pub async fn find_by_id(pool: &PgPool, id: Uuid) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>("SELECT * FROM contract_diff_runs WHERE id = $1")
            .bind(id)
            .fetch_optional(pool)
            .await
    }
}

#[cfg(feature = "postgres")]
impl ContractDiffFinding {
    pub async fn list_by_run(pool: &PgPool, run_id: Uuid) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM contract_diff_findings WHERE run_id = $1 \
             ORDER BY CASE severity \
                 WHEN 'breaking' THEN 0 \
                 WHEN 'non_breaking' THEN 1 \
                 WHEN 'cosmetic' THEN 2 \
                 ELSE 3 END",
        )
        .bind(run_id)
        .fetch_all(pool)
        .await
    }
}

#[cfg(feature = "postgres")]
impl VerificationSuite {
    pub async fn list_by_workspace(pool: &PgPool, workspace_id: Uuid) -> sqlx::Result<Vec<Self>> {
        sqlx::query_as::<_, Self>(
            "SELECT * FROM verification_suites WHERE workspace_id = $1 ORDER BY name",
        )
        .bind(workspace_id)
        .fetch_all(pool)
        .await
    }

    pub async fn find_by_id(pool: &PgPool, id: Uuid) -> sqlx::Result<Option<Self>> {
        sqlx::query_as::<_, Self>("SELECT * FROM verification_suites WHERE id = $1")
            .bind(id)
            .fetch_optional(pool)
            .await
    }

    pub async fn create(
        pool: &PgPool,
        workspace_id: Uuid,
        name: &str,
        contract_check_ids: &[Uuid],
        fitness_function_ids: &[Uuid],
    ) -> sqlx::Result<Self> {
        sqlx::query_as::<_, Self>(
            r#"
            INSERT INTO verification_suites
                (workspace_id, name, contract_check_ids, fitness_function_ids)
            VALUES ($1, $2, $3, $4)
            RETURNING *
            "#,
        )
        .bind(workspace_id)
        .bind(name)
        .bind(contract_check_ids)
        .bind(fitness_function_ids)
        .fetch_one(pool)
        .await
    }

    pub async fn delete(pool: &PgPool, id: Uuid) -> sqlx::Result<bool> {
        let rows = sqlx::query("DELETE FROM verification_suites WHERE id = $1")
            .bind(id)
            .execute(pool)
            .await?
            .rows_affected();
        Ok(rows > 0)
    }
}

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

    #[test]
    fn traffic_sources_recognized() {
        for s in MonitoredService::VALID_TRAFFIC_SOURCES {
            assert!(MonitoredService::is_valid_traffic_source(s));
        }
        assert!(!MonitoredService::is_valid_traffic_source("WAL"));
    }

    #[test]
    fn fitness_kinds_recognized() {
        for k in FitnessFunction::VALID_KINDS {
            assert!(FitnessFunction::is_valid_kind(k));
        }
        assert!(!FitnessFunction::is_valid_kind("LATENCY_THRESHOLD"));
        assert!(!FitnessFunction::is_valid_kind(""));
    }
}