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
mod secret;
pub use secret::Secret;
// TODO: There are a number of instances of `#[allow(unused)]` that allow
// certain portions of the factories to be unused without warning. These should
// be removed once all factories are populated and utilized.
/*-- Generic Factory Infrastructure ------------------------------------------*/
/// Core trait that all factory-managed types must implement.
/// Provides construction from a configuration object.
pub trait ConfigConstructable {
/// Construct with a config instance
fn new(cfg: &serde_json::Value) -> Self
where
Self: Sized;
}
/// Macro to define a complete factory infrastructure for a trait hierarchy.
///
/// This macro generates:
/// - An internal metadata trait for type erasure
/// - A HasMetadata trait that implementations must provide
/// - A MetaOf wrapper for connecting implementations to metadata
/// - A Factory struct with registration and construction capabilities
///
/// # Arguments
///
/// * `$trait` - The trait being factored (e.g., Provider, Capability)
/// * `$config` - The config type used for construction
/// * `$metadata` - The metadata type returned by describe()
/// * `$factory` - Name for the Factory struct
///
/// # Example
///
/// ```ignore
/// trait MyTrait: ConfigConstructable {
/// fn do_something(&self);
/// }
/// struct MyMetadata { value: i32 }
///
/// define_factory!(
/// MyTrait,
/// MyMetadata,
/// MyTraitFactory
/// );
///
/// struct MySomething { value: i32 }
/// impl MyTrait for MySomething {
/// fn do_something(&self) { println!("My value: {}", self.value); }
/// }
/// impl HasMyTraitMetadata for MySomething {
/// fn metadata() -> String { "I belong to you".to_string() }
/// }
/// ```
#[macro_export]
macro_rules! define_factory {
($trait:ident, $metadata:ty, $factory:ident) => {
/// Wrapper type that connects an implementation to its metadata.
/// Uses PhantomData to maintain type information without storing instances.
struct MetaOf<T>(std::marker::PhantomData<T>);
impl<T> MetaOf<T> {
#[allow(unused)]
const fn new() -> Self {
Self(std::marker::PhantomData)
}
}
$crate::paste::paste! {
/// Internal trait for metadata provision and construction.
/// This trait enables type erasure while maintaining type safety.
pub(crate) trait [<$trait Metadata_>]: Send + Sync {
/// Get metadata describing this implementation
fn describe(&self) -> $metadata;
/// Construct an instance with the given config
#[allow(unused)]
fn construct(&self, cfg: &serde_json::Value) -> Box<dyn $trait>;
/// JSON schema of the config this implementation expects
#[allow(unused)]
fn config_schema(&self) -> schemars::Schema;
/// Default config value for this implementation
#[allow(unused)]
fn default_config(&self) -> serde_json::Value;
}
/// Trait that implementations must provide to supply metadata.
/// This is the public interface for implementations to describe themselves.
pub trait [<Has $trait Metadata>] {
/// Return metadata describing this implementation
fn metadata() -> $metadata;
/// Return the JSON schema of the config this implementation's
/// `ConfigConstructable::new` expects. Implementations with a
/// real config struct should override this with
/// `schemars::schema_for!(TheirConfigType)`; the default is an
/// opaque schema for implementations with no structured config
/// worth exposing (e.g. test doubles).
fn config_schema() -> schemars::Schema {
schemars::schema_for!(serde_json::Value)
}
/// Return the default config value for this implementation.
/// Implementations with a real config struct should override
/// this with their struct's own `Default` impl, serialized;
/// the default is an empty object for implementations with no
/// structured config worth exposing (e.g. test doubles).
fn default_config() -> serde_json::Value {
serde_json::Value::Object(serde_json::Map::new())
}
}
/// Implementation of the internal metadata trait for any type T
/// that implements the required traits.
impl<T> [<$trait Metadata_>] for MetaOf<T>
where
T: $trait + [<Has $trait Metadata>] + Send + Sync + 'static,
{
fn describe(&self) -> $metadata {
T::metadata()
}
fn construct(&self, cfg: &serde_json::Value) -> Box<dyn $trait> {
Box::new(T::new(cfg))
}
fn config_schema(&self) -> schemars::Schema {
T::config_schema()
}
fn default_config(&self) -> serde_json::Value {
T::default_config()
}
}
/// Factory for creating and managing instances of the trait.
///
/// The factory maintains a registry of implementations and provides
/// methods to:
/// - Register new implementations
/// - Construct instances by name
/// - Query metadata
/// - List all registered implementations
pub struct $factory {
registry: std::collections::HashMap<&'static str, Box<dyn [<$trait Metadata_>]>>,
}
impl $factory {
/// Create a new empty factory
pub(crate) fn new() -> Self {
Self {
registry: std::collections::HashMap::new(),
}
}
/// Register an implementation with the given name.
///
/// # Type Parameters
///
/// * `T` - The implementation type to register
///
/// # Arguments
///
/// * `name` - Static string identifier for this implementation
#[allow(unused)]
pub(crate) fn register<T>(&mut self, name: &'static str)
where
T: $trait + [<Has $trait Metadata>] + Send + Sync + 'static,
{
self.registry.insert(name, Box::new(MetaOf::<T>::new()));
}
/// Construct an instance by name with the given configuration.
///
/// # Arguments
///
/// * `name` - The name of the implementation to construct
/// * `cfg` - Configuration to pass to the constructor
///
/// # Returns
///
/// * `Ok(Box<dyn Trait>)` - Successfully constructed instance
/// * `Err(String)` - Error message if name not found
#[allow(unused)]
pub(crate) fn construct(
&self,
name: &str,
cfg: &serde_json::Value,
) -> Result<Box<dyn $trait>, String> {
self.registry
.get(name)
.map(|x| x.construct(cfg))
.ok_or_else(|| format!("Unknown instance type: {}", name))
}
/// Get metadata for a specific implementation by name.
///
/// # Arguments
///
/// * `name` - The name of the implementation
///
/// # Returns
///
/// * `Some(metadata)` - Metadata if found
/// * `None` - If name not registered
#[allow(unused)]
pub(crate) fn get(&self, name: &str) -> Option<$metadata> {
self.registry.get(name).map(|x| x.describe())
}
/// Get all registered implementations with their metadata.
///
/// # Returns
///
/// HashMap mapping names to metadata for all registered implementations
#[allow(unused)]
pub(crate) fn entries(&self) -> std::collections::HashMap<&str, $metadata> {
self.registry
.iter()
.map(|(k, v)| (*k, v.describe()))
.collect()
}
/// Get the config JSON schema for a specific implementation by name.
///
/// # Arguments
///
/// * `name` - The name of the implementation
///
/// # Returns
///
/// * `Some(schema)` - Schema of the config `construct` expects, if found
/// * `None` - If name not registered
#[allow(unused)]
pub(crate) fn config_schema(&self, name: &str) -> Option<schemars::Schema> {
self.registry.get(name).map(|x| x.config_schema())
}
/// Get the default config value for a specific implementation by name.
///
/// # Arguments
///
/// * `name` - The name of the implementation
///
/// # Returns
///
/// * `Some(value)` - Default config value, if found
/// * `None` - If name not registered
#[allow(unused)]
pub(crate) fn default_config(&self, name: &str) -> Option<serde_json::Value> {
self.registry.get(name).map(|x| x.default_config())
}
}
}
impl Default for $factory {
fn default() -> Self {
Self::new()
}
}
impl $crate::dependency::Catalogued for dyn $trait {
type Metadata = $metadata;
}
};
}
/*-- tests -------------------------------------------------------------------*/
#[cfg(test)]
mod tests {
use super::*;
// Hoist paste macro for use in the macro-expanded traits
extern crate paste;
// Test trait and types
pub(crate) trait TestTrait: ConfigConstructable {
fn get_value(&self) -> i32;
}
// Define factory for test trait (3 params: trait, metadata type, factory name)
define_factory!(TestTrait, String, TestTraitFactory);
// Test implementation 1
struct TestImpl1 {
value: i32,
}
impl ConfigConstructable for TestImpl1 {
fn new(cfg: &serde_json::Value) -> Self {
let value = cfg.get("value").and_then(|v| v.as_i64()).unwrap_or(0) as i32;
Self { value }
}
}
impl TestTrait for TestImpl1 {
fn get_value(&self) -> i32 {
self.value
}
}
impl HasTestTraitMetadata for TestImpl1 {
fn metadata() -> String {
"TestImpl1: A test implementation".to_string()
}
}
// Test implementation 2
struct TestImpl2 {
value: i32,
}
impl ConfigConstructable for TestImpl2 {
fn new(cfg: &serde_json::Value) -> Self {
let value = cfg.get("value").and_then(|v| v.as_i64()).unwrap_or(0) as i32;
Self { value: value * 2 }
}
}
impl TestTrait for TestImpl2 {
fn get_value(&self) -> i32 {
self.value
}
}
#[derive(schemars::JsonSchema)]
struct TestImpl2Config {
#[allow(unused)] // Used for schema inspection
value: i32,
}
impl HasTestTraitMetadata for TestImpl2 {
fn metadata() -> String {
"TestImpl2: Another test implementation".to_string()
}
fn config_schema() -> schemars::Schema {
schemars::schema_for!(TestImpl2Config)
}
fn default_config() -> serde_json::Value {
serde_json::json!({ "value": 7 })
}
}
#[test]
fn test_factory_registration() {
let mut factory = TestTraitFactory::new();
factory.register::<TestImpl1>("impl1");
factory.register::<TestImpl2>("impl2");
assert!(factory.get("impl1").is_some());
assert!(factory.get("impl2").is_some());
assert!(factory.get("impl3").is_none());
}
#[test]
fn test_factory_metadata() {
let mut factory = TestTraitFactory::new();
factory.register::<TestImpl1>("impl1");
factory.register::<TestImpl2>("impl2");
let meta1 = factory.get("impl1").unwrap();
assert!(meta1.contains("TestImpl1"));
let meta2 = factory.get("impl2").unwrap();
assert!(meta2.contains("TestImpl2"));
}
#[test]
fn test_factory_construction() {
let mut factory = TestTraitFactory::new();
factory.register::<TestImpl1>("impl1");
factory.register::<TestImpl2>("impl2");
let cfg = serde_json::json!({ "value": 42 });
let inst1 = factory.construct("impl1", &cfg).unwrap();
assert_eq!(inst1.get_value(), 42);
let inst2 = factory.construct("impl2", &cfg).unwrap();
assert_eq!(inst2.get_value(), 84); // TestImpl2 doubles the value
}
#[test]
fn test_factory_construct_unknown() {
let factory = TestTraitFactory::new();
let cfg = serde_json::json!({ "value": 42 });
let result = factory.construct("unknown", &cfg);
assert!(result.is_err());
assert!(result.err().unwrap().contains("Unknown instance type"));
}
#[test]
fn test_factory_entries() {
let mut factory = TestTraitFactory::new();
factory.register::<TestImpl1>("impl1");
factory.register::<TestImpl2>("impl2");
let entries = factory.entries();
assert_eq!(entries.len(), 2);
let metadata_strs: Vec<String> = entries.into_values().collect();
assert!(metadata_strs.iter().any(|s| s.contains("TestImpl1")));
assert!(metadata_strs.iter().any(|s| s.contains("TestImpl2")));
}
#[test]
fn test_factory_default() {
let factory = TestTraitFactory::default();
assert_eq!(factory.entries().len(), 0);
}
#[test]
fn test_config_schema_default_is_opaque() {
let mut factory = TestTraitFactory::new();
factory.register::<TestImpl1>("impl1");
// TestImpl1 never overrides config_schema, so it gets the default
// opaque `serde_json::Value` schema rather than failing to compile.
let schema = factory.config_schema("impl1").unwrap();
assert_eq!(schema, schemars::schema_for!(serde_json::Value));
}
#[test]
fn test_config_schema_uses_override() {
let mut factory = TestTraitFactory::new();
factory.register::<TestImpl2>("impl2");
let schema = factory.config_schema("impl2").unwrap();
let properties = schema
.get("properties")
.and_then(|p| p.as_object())
.expect("object schema with properties");
assert!(properties.contains_key("value"));
}
#[test]
fn test_config_schema_unknown() {
let factory = TestTraitFactory::new();
assert!(factory.config_schema("unknown").is_none());
}
#[test]
fn test_default_config_default_is_empty_object() {
let mut factory = TestTraitFactory::new();
factory.register::<TestImpl1>("impl1");
// TestImpl1 never overrides default_config, so it gets the default
// empty object rather than failing to compile.
let value = factory.default_config("impl1").unwrap();
assert_eq!(value, serde_json::json!({}));
}
#[test]
fn test_default_config_uses_override() {
let mut factory = TestTraitFactory::new();
factory.register::<TestImpl2>("impl2");
let value = factory.default_config("impl2").unwrap();
assert_eq!(value, serde_json::json!({ "value": 7 }));
}
#[test]
fn test_default_config_unknown() {
let factory = TestTraitFactory::new();
assert!(factory.default_config("unknown").is_none());
}
}