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
//! Thread-safe registry for custom scalar implementations.
//!
//! This module provides a global registry for managing custom scalar implementations
//! at runtime, allowing applications to register their own scalar types.
use std::{
collections::HashMap,
sync::{Arc, RwLock},
};
use super::custom_scalar::CustomScalar;
/// Thread-safe registry for custom scalar implementations.
///
/// Uses `Arc<RwLock<HashMap>>` for concurrent read access with exclusive write access.
pub struct CustomScalarRegistry {
scalars: Arc<RwLock<HashMap<String, Arc<dyn CustomScalar>>>>,
}
impl CustomScalarRegistry {
/// Create a new custom scalar registry.
pub fn new() -> Self {
Self {
scalars: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Register a custom scalar implementation.
///
/// # Arguments
///
/// * `scalar` - The scalar implementation to register
///
/// # Errors
///
/// Returns an error if a scalar with the same name is already registered.
///
/// # Example
///
/// ```
/// use fraiseql_core::validation::{CustomScalarRegistry, CustomScalar};
/// use fraiseql_core::error::Result;
/// use serde_json::Value;
/// use std::sync::Arc;
///
/// #[derive(Debug)]
/// struct Email;
/// impl CustomScalar for Email {
/// fn name(&self) -> &str { "Email" }
/// fn serialize(&self, v: &Value) -> Result<Value> { Ok(v.clone()) }
/// fn parse_value(&self, v: &Value) -> Result<Value> { Ok(v.clone()) }
/// fn parse_literal(&self, v: &Value) -> Result<Value> { Ok(v.clone()) }
/// }
///
/// let registry = CustomScalarRegistry::new();
/// registry.register(Arc::new(Email)).unwrap();
/// assert!(registry.has_scalar("Email").unwrap());
/// ```
pub fn register(&self, scalar: Arc<dyn CustomScalar>) -> crate::error::Result<()> {
let name = scalar.name().to_string();
let mut scalars = self.scalars.write().map_err(|_| {
crate::error::FraiseQLError::internal("Failed to acquire write lock on scalar registry")
})?;
if scalars.contains_key(&name) {
return Err(crate::error::FraiseQLError::validation(format!(
"Scalar \"{}\" is already registered",
name
)));
}
scalars.insert(name, scalar);
Ok(())
}
/// Get a registered scalar by name.
///
/// Returns `None` if the scalar is not registered.
///
/// # Errors
///
/// Returns `FraiseQLError::Internal` if the read lock cannot be acquired.
pub fn get_scalar(&self, name: &str) -> crate::error::Result<Option<Arc<dyn CustomScalar>>> {
let scalars = self.scalars.read().map_err(|_| {
crate::error::FraiseQLError::internal("Failed to acquire read lock on scalar registry")
})?;
Ok(scalars.get(name).cloned())
}
/// Check if a scalar is registered.
///
/// # Errors
///
/// Returns `FraiseQLError::Internal` if the read lock cannot be acquired.
pub fn has_scalar(&self, name: &str) -> crate::error::Result<bool> {
let scalars = self.scalars.read().map_err(|_| {
crate::error::FraiseQLError::internal("Failed to acquire read lock on scalar registry")
})?;
Ok(scalars.contains_key(name))
}
/// Get all registered scalar names.
///
/// # Errors
///
/// Returns `FraiseQLError::Internal` if the read lock cannot be acquired.
pub fn get_scalar_names(&self) -> crate::error::Result<Vec<String>> {
let scalars = self.scalars.read().map_err(|_| {
crate::error::FraiseQLError::internal("Failed to acquire read lock on scalar registry")
})?;
Ok(scalars.keys().cloned().collect())
}
/// Unregister a scalar by name (useful for testing).
///
/// # Errors
///
/// Returns `FraiseQLError::Internal` if the write lock cannot be acquired.
pub fn unregister(&self, name: &str) -> crate::error::Result<()> {
let mut scalars = self.scalars.write().map_err(|_| {
crate::error::FraiseQLError::internal("Failed to acquire write lock on scalar registry")
})?;
scalars.remove(name);
Ok(())
}
/// Clear all registered scalars (useful for testing).
///
/// # Errors
///
/// Returns `FraiseQLError::Internal` if the write lock cannot be acquired.
pub fn clear(&self) -> crate::error::Result<()> {
let mut scalars = self.scalars.write().map_err(|_| {
crate::error::FraiseQLError::internal("Failed to acquire write lock on scalar registry")
})?;
scalars.clear();
Ok(())
}
}
impl Default for CustomScalarRegistry {
fn default() -> Self {
Self::new()
}
}
impl Clone for CustomScalarRegistry {
fn clone(&self) -> Self {
Self {
scalars: Arc::clone(&self.scalars),
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
use super::*;
#[derive(Debug)]
struct TestScalar;
impl CustomScalar for TestScalar {
#[allow(clippy::unnecessary_literal_bound)] // Reason: trait requires &str return type
fn name(&self) -> &str {
"Test"
}
fn serialize(&self, value: &serde_json::Value) -> crate::error::Result<serde_json::Value> {
Ok(value.clone())
}
fn parse_value(
&self,
value: &serde_json::Value,
) -> crate::error::Result<serde_json::Value> {
Ok(value.clone())
}
fn parse_literal(
&self,
ast: &serde_json::Value,
) -> crate::error::Result<serde_json::Value> {
Ok(ast.clone())
}
}
#[test]
fn test_register_scalar() {
let registry = CustomScalarRegistry::new();
let scalar: Arc<dyn CustomScalar> = Arc::new(TestScalar);
registry
.register(scalar)
.unwrap_or_else(|e| panic!("first registration should succeed: {e}"));
assert!(registry.has_scalar("Test").unwrap());
}
#[test]
fn test_prevent_duplicate_registration() {
let registry = CustomScalarRegistry::new();
let scalar1: Arc<dyn CustomScalar> = Arc::new(TestScalar);
let scalar2: Arc<dyn CustomScalar> = Arc::new(TestScalar);
registry
.register(scalar1)
.unwrap_or_else(|e| panic!("first registration should succeed: {e}"));
assert!(
matches!(
registry.register(scalar2),
Err(crate::error::FraiseQLError::Validation { .. })
),
"duplicate registration should return Validation error"
);
}
#[test]
fn test_get_scalar() {
let registry = CustomScalarRegistry::new();
let scalar: Arc<dyn CustomScalar> = Arc::new(TestScalar);
registry.register(scalar.clone()).unwrap();
assert!(registry.get_scalar("Test").unwrap().is_some());
assert!(registry.get_scalar("NotFound").unwrap().is_none());
}
#[test]
fn test_unregister_scalar() {
let registry = CustomScalarRegistry::new();
let scalar: Arc<dyn CustomScalar> = Arc::new(TestScalar);
registry.register(scalar).unwrap();
assert!(registry.has_scalar("Test").unwrap());
registry.unregister("Test").unwrap();
assert!(!registry.has_scalar("Test").unwrap());
}
#[test]
fn test_clear_scalars() {
let registry = CustomScalarRegistry::new();
let scalar: Arc<dyn CustomScalar> = Arc::new(TestScalar);
registry.register(scalar).unwrap();
registry.clear().unwrap();
assert!(registry.get_scalar_names().unwrap().is_empty());
}
}