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#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
19pub enum CompatibilityMode {
20 None,
22 #[default]
24 Backward,
25 Forward,
27 Full,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct Schema {
34 pub id: Uuid,
36
37 pub subject: String,
39
40 pub version: u32,
42
43 pub schema: JsonValue,
45
46 pub created_at: DateTime<Utc>,
48
49 pub description: Option<String>,
51
52 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#[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct ValidateEventRequest {
91 pub subject: String,
92 pub version: Option<u32>,
93 pub payload: JsonValue,
94}
95
96#[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#[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct SchemaRegistryConfig {
124 pub default_compatibility: CompatibilityMode,
126
127 pub auto_register: bool,
129
130 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
144fn 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
152pub struct SchemaRegistry {
154 schemas: Arc<DashMap<String, HashMap<u32, Schema>>>,
157 schemas_charge: MapCharge,
158 schema_slots: Tally,
160
161 latest_versions: Arc<DashMap<String, u32>>,
163 latest_versions_charge: MapCharge,
164
165 compatibility_modes: Arc<DashMap<String, CompatibilityMode>>,
167 compatibility_modes_charge: MapCharge,
168
169 config: SchemaRegistryConfig,
171
172 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 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 let next_version = self.latest_versions.get(&subject).map_or(1, |v| *v + 1);
212
213 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 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 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 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 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 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 pub fn list_subjects(&self) -> Vec<String> {
320 self.schemas
321 .iter()
322 .map(|entry| entry.key().clone())
323 .collect()
324 }
325
326 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 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 fn validate_json(data: &JsonValue, schema: &JsonValue) -> Vec<String> {
353 let mut errors = Vec::new();
354
355 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 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 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 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 issues.extend(self.check_backward_compatibility(old_schema, new_schema));
427 }
428 CompatibilityMode::Forward => {
429 issues.extend(self.check_forward_compatibility(old_schema, new_schema));
431 }
432 CompatibilityMode::Full => {
433 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 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 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 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 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 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 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 pub fn stats(&self) -> SchemaRegistryStats {
555 self.stats.read().clone()
556 }
557
558 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 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 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 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 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}