reinhardt-core 0.1.1

Core components for Reinhardt framework
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Core serialization traits and implementations
//!
//! Provides the foundational `Serializer` and `Deserializer` traits along with
//! error types for serialization operations.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Core serializer trait for converting between input and output representations
///
/// # Type Parameters
///
/// - `Input`: The source type to serialize
/// - `Output`: The target serialized representation
///
/// # Examples
///
/// ```
/// use reinhardt_core::serializers::{Serializer, JsonSerializer};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct User { id: i64, name: String }
///
/// let user = User { id: 1, name: "Alice".to_string() };
/// let serializer = JsonSerializer::<User>::new();
/// let json = serializer.serialize(&user).unwrap();
/// assert!(json.contains("Alice"));
/// ```
pub trait Serializer {
	/// The source type to serialize from.
	type Input;
	/// The target serialized representation.
	type Output;

	/// Serialize the input into the output representation.
	fn serialize(&self, input: &Self::Input) -> Result<Self::Output, SerializerError>;
	/// Deserialize the output back into the input type.
	fn deserialize(&self, output: &Self::Output) -> Result<Self::Input, SerializerError>;
}

/// Errors that can occur during validation
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidatorError {
	/// Unique constraint violation
	UniqueViolation {
		/// Name of the field with the unique constraint.
		field_name: String,
		/// The duplicate value that caused the violation.
		value: String,
		/// Human-readable error message.
		message: String,
	},
	/// Unique together constraint violation
	UniqueTogetherViolation {
		/// Names of the fields in the composite unique constraint.
		field_names: Vec<String>,
		/// Map of field names to their duplicate values.
		values: HashMap<String, String>,
		/// Human-readable error message.
		message: String,
	},
	/// Required field missing
	RequiredField {
		/// Name of the missing required field.
		field_name: String,
		/// Human-readable error message.
		message: String,
	},
	/// Field validation error
	FieldValidation {
		/// Name of the field that failed validation.
		field_name: String,
		/// The value that failed validation.
		value: String,
		/// The constraint that was violated.
		constraint: String,
		/// Human-readable error message.
		message: String,
	},
	/// Database error
	DatabaseError {
		/// Human-readable error message.
		message: String,
		/// Optional underlying error source description.
		source: Option<String>,
	},
	/// Custom validation error
	Custom {
		/// Human-readable error message.
		message: String,
	},
}

impl std::fmt::Display for ValidatorError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			ValidatorError::UniqueViolation {
				field_name,
				value,
				message,
			} => write!(
				f,
				"Unique violation on field '{}' with value '{}': {}",
				field_name, value, message
			),
			ValidatorError::UniqueTogetherViolation {
				field_names,
				values,
				message,
			} => {
				// Format field_names as [username, email]
				let fields_str = format!("[{}]", field_names.join(", "));
				// Format values as (username=alice, email=alice@example.com)
				// Sort by key to ensure deterministic order
				let mut sorted_values: Vec<_> = values.iter().collect();
				sorted_values.sort_by_key(|(k, _)| *k);
				let values_str = sorted_values
					.into_iter()
					.map(|(k, v)| format!("{}={}", k, v))
					.collect::<Vec<_>>()
					.join(", ");
				write!(
					f,
					"Unique together violation on fields {} with values ({}): {}",
					fields_str, values_str, message
				)
			}
			ValidatorError::RequiredField {
				field_name,
				message,
			} => write!(f, "Required field '{}': {}", field_name, message),
			ValidatorError::FieldValidation {
				field_name,
				value,
				constraint,
				message,
			} => write!(
				f,
				"Field '{}' with value '{}' failed constraint '{}': {}",
				field_name, value, constraint, message
			),
			ValidatorError::DatabaseError { message, source } => {
				if let Some(src) = source {
					write!(f, "Database error: {} (source: {})", message, src)
				} else {
					write!(f, "Database error: {}", message)
				}
			}
			ValidatorError::Custom { message } => write!(f, "Validation error: {}", message),
		}
	}
}

impl std::error::Error for ValidatorError {}

impl ValidatorError {
	/// Returns the error message
	pub fn message(&self) -> &str {
		match self {
			ValidatorError::UniqueViolation { message, .. } => message,
			ValidatorError::UniqueTogetherViolation { message, .. } => message,
			ValidatorError::RequiredField { message, .. } => message,
			ValidatorError::FieldValidation { message, .. } => message,
			ValidatorError::DatabaseError { message, .. } => message,
			ValidatorError::Custom { message } => message,
		}
	}

	/// Returns the field names involved in this error
	pub fn field_names(&self) -> Vec<&str> {
		match self {
			ValidatorError::UniqueViolation { field_name, .. } => vec![field_name.as_str()],
			ValidatorError::UniqueTogetherViolation { field_names, .. } => {
				field_names.iter().map(|s| s.as_str()).collect()
			}
			ValidatorError::RequiredField { field_name, .. } => vec![field_name.as_str()],
			ValidatorError::FieldValidation { field_name, .. } => vec![field_name.as_str()],
			ValidatorError::DatabaseError { .. } => vec![],
			ValidatorError::Custom { .. } => vec![],
		}
	}

	/// Check if this is a uniqueness violation error
	pub fn is_uniqueness_violation(&self) -> bool {
		matches!(
			self,
			ValidatorError::UniqueViolation { .. } | ValidatorError::UniqueTogetherViolation { .. }
		)
	}

	/// Check if this is a database error
	pub fn is_database_error(&self) -> bool {
		matches!(self, ValidatorError::DatabaseError { .. })
	}
}

/// Errors that can occur during serialization
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SerializerError {
	/// Validation error
	Validation(ValidatorError),
	/// Serde serialization/deserialization error
	Serde {
		/// Human-readable error message from serde.
		message: String,
	},
	/// Other error
	Other {
		/// Human-readable error message.
		message: String,
	},
}

impl std::fmt::Display for SerializerError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			SerializerError::Validation(e) => write!(f, "{}", e),
			SerializerError::Serde { message } => write!(f, "Serde error: {}", message),
			SerializerError::Other { message } => write!(f, "Serialization error: {}", message),
		}
	}
}

impl std::error::Error for SerializerError {
	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
		match self {
			SerializerError::Validation(e) => Some(e),
			_ => None,
		}
	}
}

impl From<ValidatorError> for SerializerError {
	fn from(err: ValidatorError) -> Self {
		SerializerError::Validation(err)
	}
}

impl SerializerError {
	/// Create a new generic serializer error
	pub fn new(message: String) -> Self {
		SerializerError::Other { message }
	}

	/// Create a validation error from a ValidatorError
	pub fn validation(error: ValidatorError) -> Self {
		SerializerError::Validation(error)
	}

	/// Create a unique violation error
	pub fn unique_violation(field_name: String, value: String, message: String) -> Self {
		SerializerError::Validation(ValidatorError::UniqueViolation {
			field_name,
			value,
			message,
		})
	}

	/// Create a unique together violation error
	pub fn unique_together_violation(
		field_names: Vec<String>,
		values: HashMap<String, String>,
		message: String,
	) -> Self {
		SerializerError::Validation(ValidatorError::UniqueTogetherViolation {
			field_names,
			values,
			message,
		})
	}

	/// Create a required field error
	pub fn required_field(field_name: String, message: String) -> Self {
		SerializerError::Validation(ValidatorError::RequiredField {
			field_name,
			message,
		})
	}

	/// Create a field validation error
	pub fn field_validation(
		field_name: String,
		value: String,
		constraint: String,
		message: String,
	) -> Self {
		SerializerError::Validation(ValidatorError::FieldValidation {
			field_name,
			value,
			constraint,
			message,
		})
	}

	/// Create a database error
	pub fn database_error(message: String, source: Option<String>) -> Self {
		SerializerError::Validation(ValidatorError::DatabaseError { message, source })
	}

	/// Check if this is a validation error
	pub fn is_validation_error(&self) -> bool {
		matches!(self, SerializerError::Validation(_))
	}

	/// Returns the error message
	pub fn message(&self) -> String {
		match self {
			SerializerError::Validation(e) => e.message().to_string(),
			SerializerError::Serde { message } => message.clone(),
			SerializerError::Other { message } => message.clone(),
		}
	}

	/// Try to convert to ValidatorError if this is a validation error
	pub fn as_validator_error(&self) -> Option<&ValidatorError> {
		match self {
			SerializerError::Validation(e) => Some(e),
			_ => None,
		}
	}
}

// Integration with reinhardt_exception is moved to REST layer
// Base layer remains exception-agnostic

/// JSON serializer implementation
///
/// Provides JSON serialization/deserialization using serde_json.
///
/// # Examples
///
/// ```
/// use reinhardt_core::serializers::{Serializer, JsonSerializer};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
/// struct User { id: i64, name: String }
///
/// let user = User { id: 1, name: "Alice".to_string() };
/// let serializer = JsonSerializer::<User>::new();
///
/// let json = serializer.serialize(&user).unwrap();
/// let deserialized = serializer.deserialize(&json).unwrap();
/// assert_eq!(user.id, deserialized.id);
/// ```
#[derive(Debug, Clone)]
pub struct JsonSerializer<T> {
	_phantom: std::marker::PhantomData<T>,
}

impl<T> JsonSerializer<T> {
	/// Create a new JSON serializer
	pub fn new() -> Self {
		Self {
			_phantom: std::marker::PhantomData,
		}
	}
}

impl<T> Default for JsonSerializer<T> {
	fn default() -> Self {
		Self::new()
	}
}

impl<T> Serializer for JsonSerializer<T>
where
	T: Serialize + for<'de> Deserialize<'de>,
{
	type Input = T;
	type Output = String;

	fn serialize(&self, input: &Self::Input) -> Result<Self::Output, SerializerError> {
		serde_json::to_string(input).map_err(|e| SerializerError::Serde {
			message: format!("Serialization error: {}", e),
		})
	}

	fn deserialize(&self, output: &Self::Output) -> Result<Self::Input, SerializerError> {
		serde_json::from_str(output).map_err(|e| SerializerError::Serde {
			message: format!("Deserialization error: {}", e),
		})
	}
}

/// Deserializer trait for one-way deserialization
///
/// # Examples
///
/// ```
/// use reinhardt_core::serializers::Deserializer;
/// use serde::{Deserialize, Serialize};
///
/// struct JsonDeserializer;
///
/// impl Deserializer for JsonDeserializer {
///     type Input = String;
///     type Output = serde_json::Value;
///
///     fn deserialize(&self, input: &Self::Input) -> Result<Self::Output, reinhardt_core::serializers::SerializerError> {
///         serde_json::from_str(input).map_err(|e| reinhardt_core::serializers::SerializerError::Serde {
///             message: format!("Deserialization error: {}", e),
///         })
///     }
/// }
/// ```
pub trait Deserializer {
	/// The serialized input type to deserialize from.
	type Input;
	/// The deserialized output type.
	type Output;

	/// Deserialize the input into the output type.
	fn deserialize(&self, input: &Self::Input) -> Result<Self::Output, SerializerError>;
}

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

	#[derive(Serialize, Deserialize, PartialEq, Debug)]
	struct TestUser {
		id: i64,
		name: String,
	}

	#[test]
	fn test_json_serializer_roundtrip() {
		let user = TestUser {
			id: 1,
			name: "Alice".to_string(),
		};
		let serializer = JsonSerializer::<TestUser>::new();

		let json = serializer.serialize(&user).unwrap();
		let deserialized = serializer.deserialize(&json).unwrap();

		assert_eq!(user.id, deserialized.id);
		assert_eq!(user.name, deserialized.name);
	}

	#[test]
	fn test_json_serializer_serialize() {
		let user = TestUser {
			id: 1,
			name: "Alice".to_string(),
		};
		let serializer = JsonSerializer::<TestUser>::new();

		let json = serializer.serialize(&user).unwrap();
		assert!(json.contains("Alice"));
		assert!(json.contains("\"id\":1"));
	}

	#[test]
	fn test_json_serializer_deserialize() {
		let json = r#"{"id":1,"name":"Alice"}"#.to_string();
		let serializer = JsonSerializer::<TestUser>::new();

		let user = serializer.deserialize(&json).unwrap();
		assert_eq!(user.id, 1);
		assert_eq!(user.name, "Alice");
	}

	#[test]
	fn test_json_serializer_deserialize_error() {
		let invalid_json = r#"{"invalid"}"#.to_string();
		let serializer = JsonSerializer::<TestUser>::new();

		let result = serializer.deserialize(&invalid_json);
		assert!(result.is_err());
	}

	#[test]
	fn test_validator_error_display() {
		let err = ValidatorError::UniqueViolation {
			field_name: "email".to_string(),
			value: "test@example.com".to_string(),
			message: "Email already exists".to_string(),
		};
		assert!(err.to_string().contains("email"));
		assert!(err.to_string().contains("test@example.com"));
	}

	#[test]
	fn test_serializer_error_from_validator_error() {
		let validator_err = ValidatorError::Custom {
			message: "test error".to_string(),
		};
		let serializer_err: SerializerError = validator_err.into();

		match serializer_err {
			SerializerError::Validation(_) => {}
			_ => panic!("Expected Validation error"),
		}
	}
}