module-registry 0.1.0

Dynamic module/plugin registry with compile-time discovery and runtime instantiation
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# Architecture

## System Overview

Module Registry implements a **type-safe plugin architecture** with compile-time discovery and runtime instantiation using Rust's type system and the `inventory` crate.

```
┌─────────────────────────────────────────────────────────────┐
│                  Compile Time                                │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  Module A                  Module B                Module N  │
│  ┌──────────┐             ┌──────────┐           ┌──────────┐│
│  │impl Trait│             │impl Trait│           │impl Trait││
│  └────┬─────┘             └────┬─────┘           └────┬─────┘│
│       │                        │                       │      │
│       │ register_module!       │ register_module!      │      │
│       └────────┬───────────────┴────────────┬──────────┘      │
│                │                            │                 │
│                ▼                            ▼                 │
│         ┌──────────────────────────────────────┐             │
│         │       inventory::collect!            │             │
│         │  (Compile-Time Registration)         │             │
│         └──────────────────────────────────────┘             │
│                                                               │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│                    Runtime                                   │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌──────────────────────────────────────────────────────┐   │
│  │            ModuleRegistry                             │   │
│  │         (Thread-Safe Storage)                         │   │
│  ├──────────────────────────────────────────────────────┤   │
│  │  RwLock<HashMap<String, (Metadata, Factory)>>        │   │
│  │                                                       │   │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────┐   │   │
│  │  │Module A      │  │Module B      │  │Module N  │   │   │
│  │  ├──────────────┤  ├──────────────┤  ├──────────┤   │   │
│  │  │Metadata      │  │Metadata      │  │Metadata  │   │   │
│  │  │Factory Fn    │  │Factory Fn    │  │Factory Fn│   │   │
│  │  └──────────────┘  └──────────────┘  └──────────┘   │   │
│  └──────────────────────────────────────────────────────┘   │
│                           │                                  │
│                           │ create("module_name")            │
│                           ▼                                  │
│  ┌──────────────────────────────────────────────────────┐   │
│  │  Factory Function Execution                          │   │
│  │  Returns: Box<dyn Any + Send + Sync>                 │   │
│  └──────────────────────────────────────────────────────┘   │
│                           │                                  │
│                           │ downcast                         │
│                           ▼                                  │
│                  Box<dyn YourTrait>                          │
│                                                               │
└─────────────────────────────────────────────────────────────┘
```

## Core Components

### 1. ModuleRegistry

Thread-safe storage and lookup for registered modules.

**Structure:**
```rust
pub struct ModuleRegistry {
    modules: RwLock<HashMap<String, (ModuleMetadata, ModuleFactory)>>,
}
```

**Key Methods:**
```rust
// Global singleton
pub fn global() -> &'static Self

// Registration
pub fn register(&self, name: &str, module_type: &str, factory: ModuleFactory)

// Instantiation
pub fn create_any(&self, name: &str) -> Result<Box<dyn Any + Send + Sync>>
pub fn create<T>(&self, name: &str) -> Result<Box<T>>

// Introspection
pub fn list_modules(&self) -> Vec<String>
pub fn has_module(&self, name: &str) -> bool
pub fn get_metadata(&self, name: &str) -> Option<ModuleMetadata>
```

**Location:** `src/lib.rs`

### 2. Module Trait

Base trait that all modules must implement.

**Definition:**
```rust
pub trait Module: Send + Sync {
    fn name(&self) -> &str;
    fn module_type(&self) -> &str;
}
```

**Purpose:**
- Provide common interface for all modules
- Enable trait object usage
- Ensure thread safety (Send + Sync)

### 3. Factory Pattern

Modules are instantiated through factory functions.

**Factory Type:**
```rust
pub type ModuleFactory = fn() -> Result<Box<dyn Any + Send + Sync>>;
```

**Why `Box<dyn Any>`?**
- Allows factory to return any trait object type
- User downcasts to their specific trait type
- Type-safe with proper error handling

**Example Factory:**
```rust
fn create_my_module() -> Result<Box<dyn Any + Send + Sync>> {
    // Create the concrete module
    let module = MyModule::new()?;
    
    // Box as trait object
    let trait_object = Box::new(module) as Box<dyn MyTrait>;
    
    // Box as Any for storage
    Ok(Box::new(trait_object))
}
```

### 4. ModuleMetadata

Stores information about registered modules.

**Structure:**
```rust
pub struct ModuleMetadata {
    pub name: String,                    // Module identifier
    pub module_type: String,             // Category (processor, provider, etc.)
    pub instantiate_fn_name: String,     // Factory function name
    pub module_path: String,             // Source file path
    pub struct_name: String,             // Struct name
}
```

**Use Cases:**
- Documentation generation
- Debugging and diagnostics
- Runtime introspection
- Dependency tracking

### 5. Inventory Integration

Automatic compile-time registration using `inventory` crate.

**ModuleRegistration Structure:**
```rust
pub struct ModuleRegistration {
    pub name: &'static str,
    pub module_type: &'static str,
    pub instantiate_fn_name: &'static str,
    pub module_path: &'static str,
    pub struct_name: &'static str,
    pub factory: ModuleFactory,
}

inventory::collect!(ModuleRegistration);
```

**How It Works:**
1. `inventory::submit!` at compile time registers modules
2. `inventory::iter` at runtime collects all registrations
3. Global registry is initialized on first access

### 6. register_module! Macro

Convenience macro for module registration.

**Definition:**
```rust
#[macro_export]
macro_rules! register_module {
    ($name:expr, $struct_name:expr, $factory:path) => {
        inventory::submit! {
            $crate::ModuleRegistration {
                name: $name,
                module_type: "module",
                instantiate_fn_name: stringify!($factory),
                module_path: module_path!(),
                struct_name: $struct_name,
                factory: $factory,
            }
        }
    };
}
```

**Usage:**
```rust
register_module!("my_module", "MyModule", create_my_module);
```

## Registration Flow

### Compile-Time Registration

```
Module Source File
    ├─ Define struct: `struct MyModule;`
    ├─ Implement Module trait
    ├─ Implement custom trait
    ├─ Define factory function: `fn create_my_module() -> Result<...>`
    └─ Call macro: `register_module!("my_module", "MyModule", create_my_module);`
    inventory::submit! → Registers in static storage
                         (Compile-time only)
```

### Runtime Initialization

```
First call to ModuleRegistry::global()
    ├─ OnceLock ensures single initialization
    └─> Create new ModuleRegistry
         ├─> Iterate inventory::iter::<ModuleRegistration>
         │    │
         │    └─> For each registration:
         │         ├─ Create ModuleMetadata from registration
         │         └─ Insert into HashMap: (name → (metadata, factory))
         └─> Return initialized registry

(Subsequent calls return cached instance)
```

## Instantiation Flow

### Creating a Module Instance

```
User calls: registry.create_any("my_module")
    ├─ 1. Acquire read lock on HashMap
    ├─ 2. Look up (metadata, factory) by name
    │    └─> Error if not found
    ├─ 3. Call factory function
    │    factory() → Result<Box<dyn Any + Send + Sync>>
    │    └─> May fail with custom error
    └─ 4. Return Box<dyn Any + Send + Sync>

User downcasts to specific type:
    └─> any_module.downcast::<Box<dyn MyTrait>>()?
         ├─ Success: Box<Box<dyn MyTrait>>
         │           └─> Dereference: Box<dyn MyTrait>
         └─ Failure: Type mismatch error
```

## Type System Design

### Why Double Boxing?

```rust
// Module implementation
struct MyModule;

// Step 1: Box as specific trait object
let trait_box: Box<dyn MyTrait> = Box::new(MyModule);

// Step 2: Box as Any for registry storage
let any_box: Box<dyn Any + Send + Sync> = Box::new(trait_box);

// Step 3: Store in registry
registry.insert(name, any_box);

// Step 4: Retrieve and downcast
let any_box = registry.get(name)?;
let trait_box: Box<Box<dyn MyTrait>> = any_box.downcast()?;
let module: Box<dyn MyTrait> = *trait_box;  // Dereference
```

**Rationale:**
- Registry must store different trait types → needs `Any`
- Traits must be `Send + Sync` → registry is thread-safe
- Downcasting validates type at runtime → type safety

### Alternative: Direct Trait Object Storage

**Not possible without specialization:**
```rust
// Cannot do this generically without specialization
fn register<T: MyTrait>(name: &str, instance: T) {
    registry.insert(name, Box::new(instance) as Box<dyn Any>);
    // Problem: How to downcast back to Box<dyn MyTrait>?
}
```

**Solution:** Factory pattern with explicit casting
```rust
fn create_module() -> Result<Box<dyn Any + Send + Sync>> {
    let module = MyModule;
    let trait_obj = Box::new(module) as Box<dyn MyTrait>;
    Ok(Box::new(trait_obj))
}
```

## Thread Safety

### RwLock vs Mutex

**Choice: RwLock**
```rust
modules: RwLock<HashMap<...>>
```

**Rationale:**
- **Many readers, few writers**
- Registration: write-once at initialization
- Queries: read-many during runtime
- Module creation: read-only (no lock contention)

**Performance:**
- Concurrent reads: ✅ No blocking
- Concurrent writes: ❌ Serialized (rare)

### Send + Sync Requirements

**Why required?**
```rust
Box<dyn Any + Send + Sync>
```

- **Send**: Module can be transferred between threads
- **Sync**: Module can be accessed from multiple threads

**Implications:**
- All modules must be thread-safe
- Interior mutability requires `Arc<Mutex<T>>` or similar
- Prevents data races at compile time

## Performance Characteristics

### Registration
- **Time**: O(1) per module
- **Memory**: ~100 bytes per module (metadata + pointer)
- **When**: Compile-time submission, runtime initialization

### Lookup
- **Time**: O(1) average (HashMap)
- **Memory**: No allocation (read lock)
- **Concurrency**: Unlimited parallel reads

### Instantiation
- **Time**: O(factory) - depends on module
- **Memory**: O(module size)
- **Concurrency**: Parallel instantiation possible

### Global Registry
- **Lazy initialization**: First access only
- **Thread-safe**: OnceLock guarantees single init
- **No runtime overhead**: After initialization

## Use Case Patterns

### 1. Plugin System

```
Application
    ├─ Define plugin trait
    ├─ Load plugins from registry
    └─ Execute plugins dynamically

Plugins (compiled with app)
    ├─ Plugin A: register_module!(...)
    ├─ Plugin B: register_module!(...)
    └─ Plugin N: register_module!(...)
```

### 2. Service Locator

```
Services
    ├─ DatabaseService: register_module!("database", ...)
    ├─ CacheService: register_module!("cache", ...)
    └─ LoggingService: register_module!("logging", ...)

Application
    └─> Locate services by name at runtime
```

### 3. Provider Pattern

```
Providers (same interface, different implementations)
    ├─ PostgresProvider: register_module!("postgres", ...)
    ├─ MySQLProvider: register_module!("mysql", ...)
    └─ SQLiteProvider: register_module!("sqlite", ...)

Application
    └─> Select provider from config: registry.create(config.db_provider)
```

### 4. Feature Flags

```
Features (conditionally compiled)
    ├─ #[cfg(feature = "premium")] register_module!("premium_feature", ...)
    ├─ register_module!("free_feature", ...)
    └─ #[cfg(feature = "experimental")] register_module!("experimental", ...)

Application
    └─> Query available features: registry.list_modules()
```

## Limitations

### 1. Static Linking Only

**Limitation:**
- Modules must be compiled into the binary
- No runtime loading of external `.so`/`.dll`

**Workaround:**
- Use Rust's dynamic library support separately
- Consider `libloading` crate for dynamic loading

### 2. Type Erasure

**Limitation:**
- Registry stores `Box<dyn Any>`
- User must know the correct trait type to downcast

**Workaround:**
- Store type information in metadata
- Provide typed wrappers

### 3. No Dependency Resolution

**Limitation:**
- No automatic dependency injection
- No lifecycle management

**Workaround:**
- Implement in factory functions
- Use external DI framework

## Error Handling

### Registration Errors

- **Duplicate names**: Overrides previous registration
- **Invalid metadata**: Caught at compile time
- **Factory panics**: Propagates to caller

### Instantiation Errors

```rust
pub enum RegistryError {
    ModuleNotFound(String),
    FactoryFailed(String),
    TypeMismatch(String),
}
```

**Error Flow:**
```
registry.create("module")?
    ├─ Not found → Error::ModuleNotFound
    ├─ Factory fails → Error::FactoryFailed (with context)
    └─ Downcast fails → Error::TypeMismatch
```

## Testing Strategy

### Unit Tests

```rust
#[cfg(test)]
mod tests {
    // Test registry operations
    - test_registry_creation()
    - test_module_registration()
    - test_module_creation()
    - test_list_modules()
    - test_has_module()
    - test_get_metadata()
    - test_module_not_found()
    - test_clear_registry()
}
```

### Integration Tests

```rust
// tests/integration_test.rs
- Test multiple modules
- Test global registry
- Test inventory integration
- Test concurrent access
```

## Future Enhancements

### v0.2
- Dependency resolution
- Lifecycle hooks (init, shutdown)
- Module versioning

### v0.3
- Dynamic library loading
- Hot module replacement
- Module isolation (sandboxing)

### v0.4
- Typed registry (avoid downcasting)
- Async module initialization
- Module health checks