Skip to main content

allsource_core/application/services/
schema.rs

1use crate::{
2    domain::entities::event::value_heap_bytes,
3    error::{AllSourceError, Result},
4    infrastructure::memory::ledger::{
5        MapCharge, Owner, Tally, option_string_heap, string_heap, strings_heap,
6    },
7};
8use chrono::{DateTime, Utc};
9use dashmap::{DashMap, mapref::entry::Entry};
10use parking_lot::RwLock;
11use serde::{Deserialize, Serialize};
12use serde_json::Value as JsonValue;
13use std::{collections::HashMap, mem::size_of, sync::Arc};
14use uuid::Uuid;
15
16/// Compatibility mode for schema evolution
17#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
19pub enum CompatibilityMode {
20    /// No compatibility checking
21    None,
22    /// New schema must be backward compatible (new fields optional)
23    #[default]
24    Backward,
25    /// New schema must be forward compatible (old fields preserved)
26    Forward,
27    /// New schema must be both backward and forward compatible
28    Full,
29}
30
31/// Schema definition with versioning
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct Schema {
34    /// Unique schema ID
35    pub id: Uuid,
36
37    /// Subject/topic name (e.g., "user.created", "order.placed")
38    pub subject: String,
39
40    /// Schema version number
41    pub version: u32,
42
43    /// JSON Schema definition
44    pub schema: JsonValue,
45
46    /// When this schema was registered
47    pub created_at: DateTime<Utc>,
48
49    /// Schema description/documentation
50    pub description: Option<String>,
51
52    /// Tags for organization
53    pub tags: Vec<String>,
54}
55
56impl Schema {
57    pub fn new(subject: String, version: u32, schema: JsonValue) -> Self {
58        Self {
59            id: Uuid::new_v4(),
60            subject,
61            version,
62            schema,
63            created_at: Utc::now(),
64            description: None,
65            tags: Vec::new(),
66        }
67    }
68}
69
70/// Request to register a new schema
71#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct RegisterSchemaRequest {
73    pub subject: String,
74    pub schema: JsonValue,
75    pub description: Option<String>,
76    pub tags: Option<Vec<String>>,
77}
78
79/// Response from schema registration
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct RegisterSchemaResponse {
82    pub schema_id: Uuid,
83    pub subject: String,
84    pub version: u32,
85    pub created_at: DateTime<Utc>,
86}
87
88/// Request to validate an event against a schema
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct ValidateEventRequest {
91    pub subject: String,
92    pub version: Option<u32>,
93    pub payload: JsonValue,
94}
95
96/// Response from event validation
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct ValidateEventResponse {
99    pub valid: bool,
100    pub errors: Vec<String>,
101    pub schema_version: u32,
102}
103
104/// Schema compatibility check result
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct CompatibilityCheckResult {
107    pub compatible: bool,
108    pub compatibility_mode: CompatibilityMode,
109    pub issues: Vec<String>,
110}
111
112/// Statistics about the schema registry
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct SchemaRegistryStats {
115    pub total_schemas: usize,
116    pub total_subjects: usize,
117    pub validations_performed: u64,
118    pub validation_failures: u64,
119}
120
121/// Configuration for the schema registry
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct SchemaRegistryConfig {
124    /// Default compatibility mode
125    pub default_compatibility: CompatibilityMode,
126
127    /// Whether to auto-register schemas on first use
128    pub auto_register: bool,
129
130    /// Whether to enforce schema validation on ingestion
131    pub enforce_validation: bool,
132}
133
134impl Default for SchemaRegistryConfig {
135    fn default() -> Self {
136        Self {
137            default_compatibility: CompatibilityMode::Backward,
138            auto_register: false,
139            enforce_validation: false,
140        }
141    }
142}
143
144/// Owned heap of a schema: its subject, JSON document, description and tags.
145fn schema_heap(schema: &Schema) -> u64 {
146    string_heap(&schema.subject)
147        + value_heap_bytes(&schema.schema) as u64
148        + option_string_heap(&schema.description)
149        + strings_heap(&schema.tags)
150}
151
152/// Central registry for managing event schemas
153pub struct SchemaRegistry {
154    /// Schemas organized by subject and version - using DashMap for lock-free concurrent access
155    /// Key: subject -> version -> Schema
156    schemas: Arc<DashMap<String, HashMap<u32, Schema>>>,
157    schemas_charge: MapCharge,
158    /// Subject keys, the per-subject version tables and the schemas they hold.
159    schema_slots: Tally,
160
161    /// Latest version for each subject
162    latest_versions: Arc<DashMap<String, u32>>,
163    latest_versions_charge: MapCharge,
164
165    /// Compatibility mode for each subject
166    compatibility_modes: Arc<DashMap<String, CompatibilityMode>>,
167    compatibility_modes_charge: MapCharge,
168
169    /// Configuration
170    config: SchemaRegistryConfig,
171
172    /// Statistics
173    stats: Arc<RwLock<SchemaRegistryStats>>,
174}
175
176impl SchemaRegistry {
177    pub fn new(config: SchemaRegistryConfig) -> Self {
178        Self {
179            schemas: Arc::new(DashMap::new()),
180            schemas_charge: MapCharge::new(
181                Owner::Misc,
182                size_of::<(String, HashMap<u32, Schema>)>(),
183            ),
184            schema_slots: Tally::new(Owner::Misc),
185            latest_versions: Arc::new(DashMap::new()),
186            latest_versions_charge: MapCharge::new(Owner::Misc, size_of::<(String, u32)>()),
187            compatibility_modes: Arc::new(DashMap::new()),
188            compatibility_modes_charge: MapCharge::new(
189                Owner::Misc,
190                size_of::<(String, CompatibilityMode)>(),
191            ),
192            config,
193            stats: Arc::new(RwLock::new(SchemaRegistryStats {
194                total_schemas: 0,
195                total_subjects: 0,
196                validations_performed: 0,
197                validation_failures: 0,
198            })),
199        }
200    }
201
202    /// Register a new schema or return existing if identical
203    pub fn register_schema(
204        &self,
205        subject: String,
206        schema: JsonValue,
207        description: Option<String>,
208        tags: Option<Vec<String>>,
209    ) -> Result<RegisterSchemaResponse> {
210        // Determine next version
211        let next_version = self.latest_versions.get(&subject).map_or(1, |v| *v + 1);
212
213        // Check compatibility with previous version if it exists
214        if next_version > 1 {
215            let prev_version = next_version - 1;
216            if let Some(subject_schemas) = self.schemas.get(&subject)
217                && let Some(prev_schema) = subject_schemas.get(&prev_version)
218            {
219                let compatibility = self.get_compatibility_mode(&subject);
220                let check_result =
221                    self.check_compatibility(&prev_schema.schema, &schema, compatibility)?;
222
223                if !check_result.compatible {
224                    return Err(AllSourceError::ValidationError(format!(
225                        "Schema compatibility check failed: {}",
226                        check_result.issues.join(", ")
227                    )));
228                }
229            }
230        }
231
232        // Create and store the schema
233        let mut new_schema = Schema::new(subject.clone(), next_version, schema);
234        new_schema.description = description;
235        new_schema.tags = tags.unwrap_or_default();
236
237        let schema_id = new_schema.id;
238        let created_at = new_schema.created_at;
239
240        // Get or create subject entry and insert the schema
241        let heap = schema_heap(&new_schema);
242        match self.schemas.entry(subject.clone()) {
243            Entry::Occupied(mut slot) => {
244                self.insert_version(slot.get_mut(), next_version, new_schema, heap);
245            }
246            Entry::Vacant(slot) => {
247                self.schema_slots.add(string_heap(slot.key()));
248                self.insert_version(
249                    &mut slot.insert(HashMap::new()),
250                    next_version,
251                    new_schema,
252                    heap,
253                );
254            }
255        }
256        self.schemas_charge.resize(&self.schemas);
257        self.latest_versions_charge.insert(
258            &self.latest_versions,
259            subject.clone(),
260            next_version,
261            |k, _| string_heap(k),
262        );
263
264        // Update stats
265        let mut stats = self.stats.write();
266        stats.total_schemas += 1;
267        if next_version == 1 {
268            stats.total_subjects += 1;
269        }
270
271        tracing::info!(
272            "📋 Registered schema v{} for subject '{}' (ID: {})",
273            next_version,
274            subject,
275            schema_id
276        );
277
278        Ok(RegisterSchemaResponse {
279            schema_id,
280            subject,
281            version: next_version,
282            created_at,
283        })
284    }
285
286    /// Get a schema by subject and version (or latest if no version specified)
287    pub fn get_schema(&self, subject: &str, version: Option<u32>) -> Result<Schema> {
288        let subject_schemas = self.schemas.get(subject).ok_or_else(|| {
289            AllSourceError::ValidationError(format!("Subject not found: {subject}"))
290        })?;
291
292        let version = match version {
293            Some(v) => v,
294            None => *self.latest_versions.get(subject).ok_or_else(|| {
295                AllSourceError::ValidationError(format!("No versions for subject: {subject}"))
296            })?,
297        };
298
299        subject_schemas.get(&version).cloned().ok_or_else(|| {
300            AllSourceError::ValidationError(format!(
301                "Schema version {version} not found for subject: {subject}"
302            ))
303        })
304    }
305
306    /// List all versions of a schema subject
307    pub fn list_versions(&self, subject: &str) -> Result<Vec<u32>> {
308        let subject_schemas = self.schemas.get(subject).ok_or_else(|| {
309            AllSourceError::ValidationError(format!("Subject not found: {subject}"))
310        })?;
311
312        let mut versions: Vec<u32> = subject_schemas.keys().copied().collect();
313        versions.sort_unstable();
314
315        Ok(versions)
316    }
317
318    /// List all schema subjects
319    pub fn list_subjects(&self) -> Vec<String> {
320        self.schemas
321            .iter()
322            .map(|entry| entry.key().clone())
323            .collect()
324    }
325
326    /// Validate a payload against a schema
327    pub fn validate(
328        &self,
329        subject: &str,
330        version: Option<u32>,
331        payload: &JsonValue,
332    ) -> Result<ValidateEventResponse> {
333        let schema = self.get_schema(subject, version)?;
334
335        let validation_result = Self::validate_json(payload, &schema.schema);
336
337        // Update stats
338        let mut stats = self.stats.write();
339        stats.validations_performed += 1;
340        if !validation_result.is_empty() {
341            stats.validation_failures += 1;
342        }
343
344        Ok(ValidateEventResponse {
345            valid: validation_result.is_empty(),
346            errors: validation_result,
347            schema_version: schema.version,
348        })
349    }
350
351    /// Internal JSON Schema validation
352    fn validate_json(data: &JsonValue, schema: &JsonValue) -> Vec<String> {
353        let mut errors = Vec::new();
354
355        // Basic JSON Schema validation
356        // In production, use jsonschema crate, but implementing basic checks here
357
358        // Check required fields
359        if let Some(required) = schema.get("required").and_then(|r| r.as_array())
360            && let Some(obj) = data.as_object()
361        {
362            for req_field in required {
363                if let Some(field_name) = req_field.as_str()
364                    && !obj.contains_key(field_name)
365                {
366                    errors.push(format!("Missing required field: {field_name}"));
367                }
368            }
369        }
370
371        // Check type
372        if let Some(expected_type) = schema.get("type").and_then(|t| t.as_str()) {
373            let actual_type = match data {
374                JsonValue::Null => "null",
375                JsonValue::Bool(_) => "boolean",
376                JsonValue::Number(_) => "number",
377                JsonValue::String(_) => "string",
378                JsonValue::Array(_) => "array",
379                JsonValue::Object(_) => "object",
380            };
381
382            if expected_type != actual_type {
383                errors.push(format!(
384                    "Type mismatch: expected {expected_type}, got {actual_type}"
385                ));
386            }
387        }
388
389        // Check properties
390        if let (Some(properties), Some(data_obj)) = (
391            schema.get("properties").and_then(|p| p.as_object()),
392            data.as_object(),
393        ) {
394            for (key, value) in data_obj {
395                if let Some(prop_schema) = properties.get(key) {
396                    let nested_errors = Self::validate_json(value, prop_schema);
397                    for err in nested_errors {
398                        errors.push(format!("{key}.{err}"));
399                    }
400                }
401            }
402        }
403
404        errors
405    }
406
407    /// Check compatibility between two schemas
408    fn check_compatibility(
409        &self,
410        old_schema: &JsonValue,
411        new_schema: &JsonValue,
412        mode: CompatibilityMode,
413    ) -> Result<CompatibilityCheckResult> {
414        let mut issues = Vec::new();
415
416        match mode {
417            CompatibilityMode::None => {
418                return Ok(CompatibilityCheckResult {
419                    compatible: true,
420                    compatibility_mode: mode,
421                    issues: Vec::new(),
422                });
423            }
424            CompatibilityMode::Backward => {
425                // Check that all old required fields are still required
426                issues.extend(self.check_backward_compatibility(old_schema, new_schema));
427            }
428            CompatibilityMode::Forward => {
429                // Check that all new required fields were in old schema
430                issues.extend(self.check_forward_compatibility(old_schema, new_schema));
431            }
432            CompatibilityMode::Full => {
433                // Check both directions
434                issues.extend(self.check_backward_compatibility(old_schema, new_schema));
435                issues.extend(self.check_forward_compatibility(old_schema, new_schema));
436            }
437        }
438
439        Ok(CompatibilityCheckResult {
440            compatible: issues.is_empty(),
441            compatibility_mode: mode,
442            issues,
443        })
444    }
445
446    fn check_backward_compatibility(
447        &self,
448        old_schema: &JsonValue,
449        new_schema: &JsonValue,
450    ) -> Vec<String> {
451        let mut issues = Vec::new();
452
453        // Get required fields from old schema
454        if let Some(old_required) = old_schema.get("required").and_then(|r| r.as_array()) {
455            let new_required = new_schema
456                .get("required")
457                .and_then(|r| r.as_array())
458                .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>())
459                .unwrap_or_default();
460
461            for old_req in old_required {
462                if let Some(field_name) = old_req.as_str()
463                    && !new_required.contains(&field_name)
464                {
465                    issues.push(format!(
466                        "Backward compatibility: required field '{field_name}' removed"
467                    ));
468                }
469            }
470        }
471
472        issues
473    }
474
475    fn check_forward_compatibility(
476        &self,
477        old_schema: &JsonValue,
478        new_schema: &JsonValue,
479    ) -> Vec<String> {
480        let mut issues = Vec::new();
481
482        // Get required fields from new schema
483        if let Some(new_required) = new_schema.get("required").and_then(|r| r.as_array()) {
484            let old_required = old_schema
485                .get("required")
486                .and_then(|r| r.as_array())
487                .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>())
488                .unwrap_or_default();
489
490            for new_req in new_required {
491                if let Some(field_name) = new_req.as_str()
492                    && !old_required.contains(&field_name)
493                {
494                    issues.push(format!(
495                        "Forward compatibility: new required field '{field_name}' added"
496                    ));
497                }
498            }
499        }
500
501        issues
502    }
503
504    /// Set compatibility mode for a subject
505    pub fn set_compatibility_mode(&self, subject: String, mode: CompatibilityMode) {
506        self.compatibility_modes_charge
507            .insert(&self.compatibility_modes, subject, mode, |k, _| {
508                string_heap(k)
509            });
510    }
511
512    fn insert_version(
513        &self,
514        versions: &mut HashMap<u32, Schema>,
515        version: u32,
516        schema: Schema,
517        heap: u64,
518    ) {
519        let before = versions.capacity();
520        let replaced = versions.insert(version, schema);
521        self.schema_slots
522            .grow(before, versions.capacity(), size_of::<(u32, Schema)>());
523        if let Some(old) = replaced {
524            self.schema_slots.sub(schema_heap(&old));
525        }
526        self.schema_slots.add(heap);
527    }
528
529    /// Get compatibility mode for a subject (or default)
530    pub fn get_compatibility_mode(&self, subject: &str) -> CompatibilityMode {
531        self.compatibility_modes
532            .get(subject)
533            .map_or(self.config.default_compatibility, |entry| *entry.value())
534    }
535
536    /// Delete a specific schema version
537    pub fn delete_schema(&self, subject: &str, version: u32) -> Result<bool> {
538        if let Some(mut subject_schemas) = self.schemas.get_mut(subject)
539            && subject_schemas.remove(&version).is_some()
540        {
541            tracing::info!("🗑️  Deleted schema v{} for subject '{}'", version, subject);
542
543            // Update stats
544            let mut stats = self.stats.write();
545            stats.total_schemas = stats.total_schemas.saturating_sub(1);
546
547            return Ok(true);
548        }
549
550        Ok(false)
551    }
552
553    /// Get registry statistics
554    pub fn stats(&self) -> SchemaRegistryStats {
555        self.stats.read().clone()
556    }
557
558    /// Get registry configuration
559    pub fn config(&self) -> &SchemaRegistryConfig {
560        &self.config
561    }
562}
563
564#[cfg(test)]
565mod tests {
566    use super::*;
567    use serde_json::json;
568
569    #[test]
570    fn test_schema_registration() {
571        let registry = SchemaRegistry::new(SchemaRegistryConfig::default());
572
573        let schema = json!({
574            "type": "object",
575            "properties": {
576                "user_id": {"type": "string"},
577                "email": {"type": "string"}
578            },
579            "required": ["user_id", "email"]
580        });
581
582        let response = registry
583            .register_schema(
584                "user.created".to_string(),
585                schema,
586                Some("User creation event".to_string()),
587                None,
588            )
589            .unwrap();
590
591        assert_eq!(response.version, 1);
592        assert_eq!(response.subject, "user.created");
593    }
594
595    #[test]
596    fn test_schema_validation() {
597        let registry = SchemaRegistry::new(SchemaRegistryConfig::default());
598
599        let schema = json!({
600            "type": "object",
601            "properties": {
602                "user_id": {"type": "string"},
603                "email": {"type": "string"}
604            },
605            "required": ["user_id", "email"]
606        });
607
608        registry
609            .register_schema("user.created".to_string(), schema, None, None)
610            .unwrap();
611
612        // Valid payload
613        let valid_payload = json!({
614            "user_id": "123",
615            "email": "test@example.com"
616        });
617
618        let result = registry
619            .validate("user.created", None, &valid_payload)
620            .unwrap();
621        assert!(result.valid);
622
623        // Invalid payload (missing required field)
624        let invalid_payload = json!({
625            "user_id": "123"
626        });
627
628        let result = registry
629            .validate("user.created", None, &invalid_payload)
630            .unwrap();
631        assert!(!result.valid);
632        assert!(!result.errors.is_empty());
633    }
634
635    #[test]
636    fn test_backward_compatibility() {
637        let registry = SchemaRegistry::new(SchemaRegistryConfig {
638            default_compatibility: CompatibilityMode::Backward,
639            ..Default::default()
640        });
641
642        let schema_v1 = json!({
643            "type": "object",
644            "required": ["user_id", "email"]
645        });
646
647        registry
648            .register_schema("user.created".to_string(), schema_v1, None, None)
649            .unwrap();
650
651        // Compatible: adding optional field
652        let schema_v2 = json!({
653            "type": "object",
654            "required": ["user_id", "email"]
655        });
656
657        let result = registry.register_schema("user.created".to_string(), schema_v2, None, None);
658        assert!(result.is_ok());
659
660        // Incompatible: removing required field
661        let schema_v3 = json!({
662            "type": "object",
663            "required": ["user_id"]
664        });
665
666        let result = registry.register_schema("user.created".to_string(), schema_v3, None, None);
667        assert!(result.is_err());
668    }
669}