fraiseql-core 2.10.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
Documentation
//! UUID extraction from mutation responses for entity-level cache invalidation.
//!
//! This module extracts entity UUIDs from GraphQL mutation response objects,
//! enabling precise, entity-level cache invalidation instead of view-level invalidation.
//!
//! # Architecture
//!
//! ```text
//! Mutation Response
//! ┌──────────────────────────────────┐
//! │ {                                │
//! │   "id": "550e8400-e29b-...",     │
//! │   "name": "Alice",               │
//! │   "created_at": "2025-01-16"     │
//! │ }                                │
//! └──────────┬───────────────────────┘
//!//!            ↓ extract_entity_uuid()
//! ┌──────────────────────────────────┐
//! │ "550e8400-e29b-41d4-..."         │
//! └──────────────────────────────────┘
//! ```
//!
//! # UUID Format Support
//!
//! - **UUID v4**: Standard format (RFC 4122)
//! - **UUID v1**: Timestamp-based
//! - **Custom UUIDs**: Any string matching UUID regex
//!
//! # Examples
//!
//! ```
//! use fraiseql_core::cache::UUIDExtractor;
//! use serde_json::json;
//!
//! let response = json!({
//!     "id": "550e8400-e29b-41d4-a716-446655440000",
//!     "name": "Alice"
//! });
//!
//! let uuid = UUIDExtractor::extract_entity_uuid(&response, "User").unwrap();
//! assert_eq!(uuid, Some("550e8400-e29b-41d4-a716-446655440000".to_string()));
//! ```

use std::sync::LazyLock;

use regex::Regex;
use serde_json::Value;

#[allow(unused_imports)] // Reason: used only in doc links for `# Errors` sections
use crate::error::FraiseQLError;
use crate::error::Result;

/// UUID v4 format regex (RFC 4122).
/// Matches: 550e8400-e29b-41d4-a716-446655440000
static UUID_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
        .expect("UUID regex is valid")
});

/// Extracts entity UUIDs from mutation response objects.
///
/// Handles various response formats:
/// - Simple: `{ "id": "uuid", "name": "..." }`
/// - Nested: `{ "user": { "id": "uuid", "name": "..." } }`
/// - Array: `[{ "id": "uuid1" }, { "id": "uuid2" }]`
#[derive(Debug, Clone)]
pub struct UUIDExtractor;

impl UUIDExtractor {
    /// Extract a single entity UUID from mutation response.
    ///
    /// # Arguments
    ///
    /// * `response` - JSON response from mutation
    /// * `entity_type` - The entity type (e.g., "User", "Post")
    ///
    /// # Returns
    ///
    /// - `Ok(Some(uuid))` - UUID found and valid
    /// - `Ok(None)` - No UUID found (e.g., null response)
    ///
    /// # Errors
    ///
    /// Returns [`FraiseQLError::Validation`] if an `"id"` field is found but
    /// its value is not a valid UUID v4 string.
    ///
    /// # Examples
    ///
    /// ```
    /// use fraiseql_core::cache::UUIDExtractor;
    /// use serde_json::json;
    ///
    /// let response = json!({"id": "550e8400-e29b-41d4-a716-446655440000"});
    /// let uuid = UUIDExtractor::extract_entity_uuid(&response, "User").unwrap();
    /// assert_eq!(uuid, Some("550e8400-e29b-41d4-a716-446655440000".to_string()));
    /// ```
    pub fn extract_entity_uuid(response: &Value, _entity_type: &str) -> Result<Option<String>> {
        match response {
            Value::Object(obj) => {
                // Try to find "id" field at top level
                if let Some(id_value) = obj.get("id") {
                    return extract_uuid_from_value(id_value);
                }

                // If not found at top level, try nested structure
                // (e.g., { user: { id: "uuid" } })
                for (_key, value) in obj {
                    if let Value::Object(nested) = value {
                        if let Some(id_value) = nested.get("id") {
                            return extract_uuid_from_value(id_value);
                        }
                    }
                }

                Ok(None)
            },
            _ => Ok(None),
        }
    }

    /// Extract multiple entity UUIDs from mutation response (batch operations).
    ///
    /// # Arguments
    ///
    /// * `response` - JSON response (array or object)
    /// * `entity_type` - The entity type (e.g., "User", "Post")
    ///
    /// # Returns
    ///
    /// List of extracted UUIDs (empty if none found)
    ///
    /// # Errors
    ///
    /// Returns [`FraiseQLError::Validation`] if any `"id"` field found in the
    /// response is not a valid UUID v4 string.
    ///
    /// # Examples
    ///
    /// ```
    /// use fraiseql_core::cache::UUIDExtractor;
    /// use serde_json::json;
    ///
    /// let response = json!([
    ///     {"id": "550e8400-e29b-41d4-a716-446655440001"},
    ///     {"id": "550e8400-e29b-41d4-a716-446655440002"},
    ///     {"id": "550e8400-e29b-41d4-a716-446655440003"}
    /// ]);
    /// let uuids = UUIDExtractor::extract_batch_uuids(&response, "User").unwrap();
    /// assert_eq!(uuids.len(), 3);
    /// ```
    pub fn extract_batch_uuids(response: &Value, _entity_type: &str) -> Result<Vec<String>> {
        match response {
            Value::Array(arr) => {
                let mut uuids = Vec::new();
                for item in arr {
                    if let Ok(Some(uuid)) = extract_uuid_from_value(item) {
                        uuids.push(uuid);
                    }
                }
                Ok(uuids)
            },
            Value::Object(_) => {
                // Single object - try to extract single UUID
                match Self::extract_entity_uuid(response, "")? {
                    Some(uuid) => Ok(vec![uuid]),
                    None => Ok(vec![]),
                }
            },
            _ => Ok(vec![]),
        }
    }

    /// Validate if a string is a valid UUID format.
    ///
    /// # Arguments
    ///
    /// * `id` - String to validate
    ///
    /// # Returns
    ///
    /// `true` if valid UUID format, `false` otherwise
    ///
    /// # Examples
    ///
    /// ```
    /// use fraiseql_core::cache::UUIDExtractor;
    ///
    /// assert!(UUIDExtractor::is_valid_uuid("550e8400-e29b-41d4-a716-446655440000"));
    /// assert!(!UUIDExtractor::is_valid_uuid("not-a-uuid"));
    /// ```
    #[must_use]
    pub fn is_valid_uuid(id: &str) -> bool {
        UUID_REGEX.is_match(&id.to_lowercase())
    }
}

/// Helper function to extract UUID from a JSON value.
fn extract_uuid_from_value(value: &Value) -> Result<Option<String>> {
    match value {
        Value::String(s) => {
            if UUIDExtractor::is_valid_uuid(s) {
                Ok(Some(s.to_lowercase()))
            } else {
                // String value that's not a UUID - could be a valid use case
                // (e.g., response mutation returns string ID that isn't UUID format)
                Ok(None)
            }
        },
        Value::Object(obj) => {
            // Try to recursively find id in nested object
            if let Some(id_val) = obj.get("id") {
                return extract_uuid_from_value(id_val);
            }
            Ok(None)
        },
        _ => Ok(None),
    }
}