1use axum::{
6 extract::{Path, Query, State},
7 http::StatusCode,
8 response::Json,
9};
10use mockforge_core::ai_contract_diff::{ContractDiffAnalyzer, ContractDiffConfig};
11use mockforge_core::incidents::semantic_manager::{SemanticIncident, SemanticIncidentManager};
12use mockforge_core::openapi::OpenApiSpec;
13use serde::{Deserialize, Serialize};
14use std::sync::Arc;
15
16#[cfg(feature = "database")]
17use chrono::{DateTime, Utc};
18#[cfg(feature = "database")]
19use uuid::Uuid;
20
21use crate::database::Database;
22
23#[cfg(feature = "database")]
25fn map_row_to_semantic_incident(
26 row: &sqlx::postgres::PgRow,
27) -> Result<SemanticIncident, sqlx::Error> {
28 use mockforge_core::ai_contract_diff::semantic_analyzer::SemanticChangeType;
29 use mockforge_core::incidents::types::{IncidentSeverity, IncidentStatus};
30 use sqlx::Row;
31
32 let id: uuid::Uuid = row.try_get("id")?;
33 let workspace_id: Option<uuid::Uuid> = row.try_get("workspace_id").ok();
34 let endpoint: String = row.try_get("endpoint")?;
35 let method: String = row.try_get("method")?;
36 let semantic_change_type_str: String = row.try_get("semantic_change_type")?;
37 let severity_str: String = row.try_get("severity")?;
38 let status_str: String = row.try_get("status")?;
39 let semantic_confidence: f64 = row.try_get("semantic_confidence")?;
40 let soft_breaking_score: f64 = row.try_get("soft_breaking_score")?;
41 let llm_analysis: serde_json::Value = row.try_get("llm_analysis").unwrap_or_default();
42 let before_semantic_state: serde_json::Value =
43 row.try_get("before_semantic_state").unwrap_or_default();
44 let after_semantic_state: serde_json::Value =
45 row.try_get("after_semantic_state").unwrap_or_default();
46 let details_json: serde_json::Value = row.try_get("details").unwrap_or_default();
47 let related_drift_incident_id: Option<uuid::Uuid> =
48 row.try_get("related_drift_incident_id").ok();
49 let contract_diff_id: Option<String> = row.try_get("contract_diff_id").ok();
50 let external_ticket_id: Option<String> = row.try_get("external_ticket_id").ok();
51 let external_ticket_url: Option<String> = row.try_get("external_ticket_url").ok();
52 let detected_at: DateTime<Utc> = row.try_get("detected_at")?;
53 let created_at: DateTime<Utc> = row.try_get("created_at")?;
54 let acknowledged_at: Option<DateTime<Utc>> = row.try_get("acknowledged_at").ok();
55 let resolved_at: Option<DateTime<Utc>> = row.try_get("resolved_at").ok();
56 let closed_at: Option<DateTime<Utc>> = row.try_get("closed_at").ok();
57 let updated_at: DateTime<Utc> = row.try_get("updated_at")?;
58
59 let semantic_change_type = match semantic_change_type_str.as_str() {
61 "description_change" => SemanticChangeType::DescriptionChange,
62 "enum_narrowing" => SemanticChangeType::EnumNarrowing,
63 "nullability_change" => SemanticChangeType::NullableChange,
64 "error_code_removed" => SemanticChangeType::ErrorCodeRemoved,
65 "meaning_shift" => SemanticChangeType::MeaningShift,
66 _ => SemanticChangeType::MeaningShift, };
68
69 let severity = match severity_str.as_str() {
71 "low" => IncidentSeverity::Low,
72 "medium" => IncidentSeverity::Medium,
73 "high" => IncidentSeverity::High,
74 "critical" => IncidentSeverity::Critical,
75 _ => IncidentSeverity::Medium, };
77
78 let status = match status_str.as_str() {
80 "open" => IncidentStatus::Open,
81 "acknowledged" => IncidentStatus::Acknowledged,
82 "resolved" => IncidentStatus::Resolved,
83 "closed" => IncidentStatus::Closed,
84 _ => IncidentStatus::Open, };
86
87 Ok(SemanticIncident {
88 id: id.to_string(),
89 workspace_id: workspace_id.map(|u| u.to_string()),
90 endpoint,
91 method,
92 semantic_change_type,
93 severity,
94 status,
95 semantic_confidence,
96 soft_breaking_score,
97 llm_analysis,
98 before_semantic_state,
99 after_semantic_state,
100 details: details_json,
101 related_drift_incident_id: related_drift_incident_id.map(|u| u.to_string()),
102 contract_diff_id,
103 external_ticket_id,
104 external_ticket_url,
105 detected_at: detected_at.timestamp(),
106 created_at: created_at.timestamp(),
107 acknowledged_at: acknowledged_at.map(|dt| dt.timestamp()),
108 resolved_at: resolved_at.map(|dt| dt.timestamp()),
109 closed_at: closed_at.map(|dt| dt.timestamp()),
110 updated_at: updated_at.timestamp(),
111 })
112}
113
114#[derive(Clone)]
116pub struct SemanticDriftState {
117 pub manager: Arc<SemanticIncidentManager>,
119 pub database: Option<Database>,
121}
122
123#[derive(Debug, Deserialize)]
125pub struct ListSemanticIncidentsQuery {
126 pub workspace_id: Option<String>,
128 pub endpoint: Option<String>,
130 pub method: Option<String>,
132 pub status: Option<String>,
134 pub limit: Option<usize>,
136}
137
138#[derive(Debug, Serialize)]
140pub struct SemanticIncidentListResponse {
141 pub incidents: Vec<SemanticIncident>,
143 pub total: usize,
145}
146
147pub async fn list_semantic_incidents(
151 State(state): State<SemanticDriftState>,
152 Query(params): Query<ListSemanticIncidentsQuery>,
153) -> Result<Json<SemanticIncidentListResponse>, StatusCode> {
154 #[cfg(feature = "database")]
156 if let Some(pool) = state.database.as_ref().and_then(|db| db.pool()) {
157 let mut query = String::from(
158 "SELECT id, workspace_id, endpoint, method, semantic_change_type, severity, status,
159 semantic_confidence, soft_breaking_score, llm_analysis, before_semantic_state,
160 after_semantic_state, details, related_drift_incident_id, contract_diff_id,
161 external_ticket_id, external_ticket_url, detected_at, created_at, acknowledged_at,
162 resolved_at, closed_at, updated_at
163 FROM semantic_drift_incidents WHERE 1=1",
164 );
165
166 let mut bind_index = 1;
167
168 if let Some(_ws_id) = ¶ms.workspace_id {
169 query.push_str(&format!(" AND workspace_id = ${}", bind_index));
170 bind_index += 1;
171 }
172
173 if let Some(_ep) = ¶ms.endpoint {
174 query.push_str(&format!(" AND endpoint = ${}", bind_index));
175 bind_index += 1;
176 }
177
178 if let Some(_m) = ¶ms.method {
179 query.push_str(&format!(" AND method = ${}", bind_index));
180 bind_index += 1;
181 }
182
183 if let Some(_status_str) = ¶ms.status {
184 query.push_str(&format!(" AND status = ${}", bind_index));
185 }
186
187 let limit = params.limit.unwrap_or(100);
188 query.push_str(&format!(" ORDER BY detected_at DESC LIMIT {}", limit));
189
190 let rows = sqlx::query(&query).fetch_all(pool).await.map_err(|e| {
192 tracing::error!("Failed to query semantic incidents: {}", e);
193 StatusCode::INTERNAL_SERVER_ERROR
194 })?;
195
196 let mut incidents = Vec::new();
198 for row in rows {
199 match map_row_to_semantic_incident(&row) {
200 Ok(incident) => incidents.push(incident),
201 Err(e) => {
202 tracing::warn!("Failed to map semantic incident row: {}", e);
203 continue;
204 }
205 }
206 }
207 if !incidents.is_empty() {
208 return Ok(Json(SemanticIncidentListResponse {
209 total: incidents.len(),
210 incidents,
211 }));
212 }
213 }
215
216 let status = params.status.as_deref().and_then(|s| match s {
218 "open" => Some(mockforge_core::incidents::types::IncidentStatus::Open),
219 "acknowledged" => Some(mockforge_core::incidents::types::IncidentStatus::Acknowledged),
220 "resolved" => Some(mockforge_core::incidents::types::IncidentStatus::Resolved),
221 "closed" => Some(mockforge_core::incidents::types::IncidentStatus::Closed),
222 _ => None,
223 });
224
225 let incidents = state
226 .manager
227 .list_incidents(
228 params.workspace_id.as_deref(),
229 params.endpoint.as_deref(),
230 params.method.as_deref(),
231 status,
232 params.limit,
233 )
234 .await;
235
236 Ok(Json(SemanticIncidentListResponse {
237 total: incidents.len(),
238 incidents,
239 }))
240}
241
242pub async fn get_semantic_incident(
246 State(state): State<SemanticDriftState>,
247 Path(id): Path<String>,
248) -> Result<Json<SemanticIncident>, StatusCode> {
249 #[cfg(feature = "database")]
251 if let Some(pool) = state.database.as_ref().and_then(|db| db.pool()) {
252 let row = sqlx::query("SELECT * FROM semantic_drift_incidents WHERE id = $1")
253 .bind(&id)
254 .fetch_optional(pool)
255 .await
256 .map_err(|e| {
257 tracing::error!("Failed to query semantic incident: {}", e);
258 StatusCode::INTERNAL_SERVER_ERROR
259 })?;
260
261 if let Some(row) = row {
262 match map_row_to_semantic_incident(&row) {
263 Ok(incident) => return Ok(Json(incident)),
264 Err(e) => {
265 tracing::warn!("Failed to map semantic incident: {}", e);
266 }
268 }
269 }
270 }
271
272 match state.manager.get_incident(&id).await {
274 Some(incident) => Ok(Json(incident)),
275 None => Err(StatusCode::NOT_FOUND),
276 }
277}
278
279#[derive(Debug, Deserialize)]
281pub struct AnalyzeSemanticDriftRequest {
282 pub before_spec: String,
284 pub after_spec: String,
286 pub endpoint: String,
288 pub method: String,
290 pub workspace_id: Option<String>,
292}
293
294pub async fn analyze_semantic_drift(
298 State(state): State<SemanticDriftState>,
299 Json(request): Json<AnalyzeSemanticDriftRequest>,
300) -> Result<Json<serde_json::Value>, StatusCode> {
301 let before_spec = OpenApiSpec::from_string(&request.before_spec, None)
303 .map_err(|_| StatusCode::BAD_REQUEST)?;
304 let after_spec =
305 OpenApiSpec::from_string(&request.after_spec, None).map_err(|_| StatusCode::BAD_REQUEST)?;
306
307 let config = ContractDiffConfig::default();
309 let analyzer =
310 ContractDiffAnalyzer::new(config).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
311
312 let semantic_result = analyzer
314 .compare_specs(&before_spec, &after_spec, &request.endpoint, &request.method)
315 .await
316 .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
317
318 if let Some(result) = semantic_result {
319 if result.semantic_confidence >= 0.65 {
321 let incident = state
322 .manager
323 .create_incident(
324 &result,
325 request.endpoint.clone(),
326 request.method.clone(),
327 request.workspace_id.clone(),
328 None, None, )
331 .await;
332
333 #[cfg(feature = "database")]
335 if let Some(pool) = state.database.as_ref().and_then(|db| db.pool()) {
336 if let Err(e) = store_semantic_incident(pool, &incident).await {
337 tracing::warn!("Failed to store semantic incident in database: {}", e);
338 }
339 }
340
341 return Ok(Json(serde_json::json!({
342 "success": true,
343 "semantic_drift_detected": true,
344 "incident_id": incident.id,
345 "semantic_confidence": result.semantic_confidence,
346 "soft_breaking_score": result.soft_breaking_score,
347 "change_type": format!("{:?}", result.change_type),
348 })));
349 }
350 }
351
352 Ok(Json(serde_json::json!({
353 "success": true,
354 "semantic_drift_detected": false,
355 "message": "No significant semantic drift detected"
356 })))
357}
358
359#[cfg(feature = "database")]
361async fn store_semantic_incident(
362 pool: &sqlx::PgPool,
363 incident: &SemanticIncident,
364) -> Result<(), sqlx::Error> {
365 let id = Uuid::parse_str(&incident.id).unwrap_or_else(|_| Uuid::new_v4());
366 let workspace_uuid = incident.workspace_id.as_ref().and_then(|id| Uuid::parse_str(id).ok());
367 let related_uuid = incident
368 .related_drift_incident_id
369 .as_ref()
370 .and_then(|id| Uuid::parse_str(id).ok());
371
372 sqlx::query(
373 r#"
374 INSERT INTO semantic_drift_incidents (
375 id, workspace_id, endpoint, method, semantic_change_type, severity, status,
376 semantic_confidence, soft_breaking_score, llm_analysis, before_semantic_state,
377 after_semantic_state, details, related_drift_incident_id, contract_diff_id,
378 external_ticket_id, external_ticket_url, detected_at, created_at, updated_at
379 ) VALUES (
380 $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20
381 )
382 ON CONFLICT (id) DO UPDATE SET
383 status = EXCLUDED.status,
384 acknowledged_at = EXCLUDED.acknowledged_at,
385 resolved_at = EXCLUDED.resolved_at,
386 closed_at = EXCLUDED.closed_at,
387 updated_at = EXCLUDED.updated_at
388 "#,
389 )
390 .bind(id)
391 .bind(workspace_uuid)
392 .bind(&incident.endpoint)
393 .bind(&incident.method)
394 .bind(format!("{:?}", incident.semantic_change_type))
395 .bind(format!("{:?}", incident.severity))
396 .bind(format!("{:?}", incident.status))
397 .bind(incident.semantic_confidence)
398 .bind(incident.soft_breaking_score)
399 .bind(&incident.llm_analysis)
400 .bind(&incident.before_semantic_state)
401 .bind(&incident.after_semantic_state)
402 .bind(&incident.details)
403 .bind(related_uuid)
404 .bind(incident.contract_diff_id.as_deref())
405 .bind(incident.external_ticket_id.as_deref())
406 .bind(incident.external_ticket_url.as_deref())
407 .bind(DateTime::<Utc>::from_timestamp(incident.detected_at, 0).unwrap_or_else(Utc::now))
408 .bind(DateTime::<Utc>::from_timestamp(incident.created_at, 0).unwrap_or_else(Utc::now))
409 .bind(DateTime::<Utc>::from_timestamp(incident.updated_at, 0).unwrap_or_else(Utc::now))
410 .execute(pool)
411 .await?;
412
413 Ok(())
414}
415
416pub fn semantic_drift_router(state: SemanticDriftState) -> axum::Router {
418 use axum::routing::{get, post};
419 use axum::Router;
420
421 Router::new()
422 .route("/api/v1/semantic-drift/incidents", get(list_semantic_incidents))
423 .route("/api/v1/semantic-drift/incidents/{id}", get(get_semantic_incident))
424 .route("/api/v1/semantic-drift/analyze", post(analyze_semantic_drift))
425 .with_state(state)
426}