sdforge 0.3.0

Multi-protocol SDK framework with unified macro configuration
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! Unified registration system for eliminating code duplication across protocols
//!
//! This module provides a trait-based abstraction for protocol registration,
//! allowing HTTP, MCP, WebSocket, and gRPC to share a common registration pattern.
//!
//! # Design Goals
//!
//! - Eliminate ~200+ lines of duplicate registration code
//! - Provide type-safe abstraction through traits
//! - Support future protocol extensions
//! - Maintain backward compatibility
//!
//! # Usage
//!
//! ```rust,ignore
//! use sdforge::core::registration::{Registration, define_registration};
//!
//! // Use the macro to define a registration type
//! define_registration!(RouteRegistration, HttpRoute, ApiMetadata);
//! ```

/// Core trait for all protocol registrations
///
/// This trait abstracts the common pattern used by HTTP routes, MCP tools,
/// WebSocket handlers, and gRPC services. Each protocol implements this trait
/// with their specific instance and metadata types.
///
/// # Type Parameters
///
/// - `Instance`: The concrete type created by this registration (e.g., `HttpRoute`, `Arc<dyn Tool>`)
/// - `Metadata`: Metadata associated with the registration (typically `ApiMetadata`)
///
/// # Examples
///
/// ```rust,ignore
/// impl Registration for RouteRegistration {
///     type Instance = HttpRoute;
///     type Metadata = ApiMetadata;
///
///     fn name(&self) -> &str { self.name }
///     fn version(&self) -> &str { self.version }
///     fn create(&self) -> Self::Instance { (self.create_fn)() }
///     fn metadata(&self) -> Self::Metadata { (self.metadata_fn)() }
/// }
/// ```
pub trait Registration: 'static + Send + Sync {
    /// The concrete instance type created by this registration
    type Instance;

    /// The metadata type associated with this registration
    type Metadata;

    /// Get the API name
    fn name(&self) -> &str;

    /// Get the API version
    fn version(&self) -> &str;

    /// Create a new instance
    fn create(&self) -> Self::Instance;

    /// Get the metadata
    fn metadata(&self) -> Self::Metadata;
}

/// Macro for defining registration types
///
/// This macro generates the boilerplate code for implementing the `Registration` trait.
/// It creates a struct with the necessary fields and implements the trait automatically.
///
/// # Syntax
///
/// ```rust,ignore
/// define_registration!(RegistrationTypeName, InstanceType, MetadataType);
/// ```
///
/// # Arguments
///
/// - `$name`: Name of the registration struct to create
/// - `$instance`: The instance type (e.g., `HttpRoute`, `Arc<dyn Tool>`)
/// - `$metadata`: The metadata type (e.g., `ApiMetadata`)
///
/// # Generated Code
///
/// The macro generates:
/// - A struct with `name`, `version`, `create_fn`, and `metadata_fn` fields
/// - Implementation of the `Registration` trait
/// - `inventory::collect!` call for automatic registration
///
/// # Examples
///
/// ```rust,ignore
/// // Define HTTP route registration
/// define_registration!(RouteRegistration, HttpRoute, ApiMetadata);
///
/// // Define MCP tool registration
/// define_registration!(McpToolRegistration, Arc<dyn Tool>, ApiMetadata);
///
/// // Define WebSocket route registration
/// define_registration!(WebSocketRouteRegistration, WebSocketHandler, ApiMetadata);
///
/// // Define gRPC service registration
/// define_registration!(GrpcServiceRegistration, GrpcService, ApiMetadata);
/// ```
#[macro_export]
macro_rules! define_registration {
    ($name:ident, $instance:ty, $metadata:ty) => {
        #[derive(Debug, Clone, Copy)]
        /// Registration entry for protocol-specific APIs
        ///
        /// This struct is generated by the `define_registration!` macro and contains
        /// metadata and factory functions for a specific API registration.
        pub struct $name {
            /// API name
            pub name: &'static str,
            /// API version
            pub version: &'static str,
            /// Function that creates the instance at runtime
            pub create_fn: fn() -> $instance,
            /// Function that creates the metadata at runtime
            pub metadata_fn: fn() -> $metadata,
        }

        impl $name {
            /// Create a new registration instance
            ///
            /// # Arguments
            ///
            /// * `name` - API name
            /// * `version` - API version
            /// * `create_fn` - Function to create the instance
            /// * `metadata_fn` - Function to create the metadata
            #[allow(dead_code)]
            pub const fn new(
                name: &'static str,
                version: &'static str,
                create_fn: fn() -> $instance,
                metadata_fn: fn() -> $metadata,
            ) -> Self {
                Self {
                    name,
                    version,
                    create_fn,
                    metadata_fn,
                }
            }
        }

        impl $crate::core::registration::Registration for $name {
            type Instance = $instance;
            type Metadata = $metadata;

            fn name(&self) -> &str {
                self.name
            }
            fn version(&self) -> &str {
                self.version
            }
            fn create(&self) -> Self::Instance {
                (self.create_fn)()
            }
            fn metadata(&self) -> Self::Metadata {
                (self.metadata_fn)()
            }
        }

        // Register with inventory for automatic collection
        inventory::collect!($name);
    };
}

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

    // Mock types for testing
    pub struct MockInstance {
        pub _data: String,
    }

    pub struct MockMetadata {
        pub _name: String,
    }

    // Additional test types
    #[derive(Debug, Clone)]
    pub struct InstanceTypeA {
        pub value: i32,
    }
    #[derive(Debug, Clone)]
    pub struct InstanceTypeB {
        pub text: String,
    }
    #[derive(Debug, Clone)]
    pub struct MetadataTypeA {
        pub id: u64,
    }
    #[derive(Debug, Clone)]
    pub struct MetadataTypeB {
        pub tags: Vec<String>,
    }

    // Test the macro-generated code
    define_registration!(TestRegistration, MockInstance, MockMetadata);

    /// Test that Registration trait methods work correctly
    #[test]
    fn test_registration_trait_methods() {
        let reg = TestRegistration::new(
            "test_api",
            "v1",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        assert_eq!(reg.name(), "test_api");
        assert_eq!(reg.version(), "v1");

        let instance = reg.create();
        assert!(instance._data == "test");

        let metadata = reg.metadata();
        assert!(metadata._name == "test");
    }

    /// Test that Registration trait bounds are satisfied
    #[test]
    fn test_registration_trait_bounds() {
        fn requires_send_sync<T: Send + Sync>() {}
        fn requires_static<T: 'static>() {}

        // Should compile without errors
        requires_send_sync::<TestRegistration>();
        requires_static::<TestRegistration>();
    }

    /// Test multiple registration instances
    #[test]
    fn test_multiple_registrations() {
        define_registration!(TestReg1, MockInstance, MockMetadata);
        define_registration!(TestReg2, MockInstance, MockMetadata);

        let reg1 = TestReg1::new(
            "api1",
            "v1",
            || MockInstance {
                _data: "1".to_string(),
            },
            || MockMetadata {
                _name: "1".to_string(),
            },
        );

        let reg2 = TestReg2::new(
            "api2",
            "v2",
            || MockInstance {
                _data: "2".to_string(),
            },
            || MockMetadata {
                _name: "2".to_string(),
            },
        );

        assert_eq!(reg1.name(), "api1");
        assert_eq!(reg2.name(), "api2");
        assert_ne!(reg1.name(), reg2.name());

        // Exercise closures to cover their bodies
        let i1 = reg1.create();
        assert_eq!(i1._data, "1");
        let m1 = reg1.metadata();
        assert_eq!(m1._name, "1");
        let i2 = reg2.create();
        assert_eq!(i2._data, "2");
        let m2 = reg2.metadata();
        assert_eq!(m2._name, "2");
    }

    /// Test that macro-generated struct has correct fields
    #[test]
    fn test_define_registration_macro_generates_struct() {
        let reg = TestRegistration::new(
            "test_api",
            "v1",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        // Verify struct fields exist and are accessible
        assert_eq!(reg.name, "test_api");
        assert_eq!(reg.version, "v1");
        assert!(std::mem::size_of_val(&reg.create_fn) > 0);
        assert!(std::mem::size_of_val(&reg.metadata_fn) > 0);

        // Exercise closures to cover their bodies
        let inst = reg.create();
        assert_eq!(inst._data, "test");
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    /// Test that new() is a const fn
    #[test]
    fn test_define_registration_macro_new_const_fn() {
        const REG: TestRegistration = TestRegistration::new(
            "const_api",
            "v2",
            || MockInstance {
                _data: "const".to_string(),
            },
            || MockMetadata {
                _name: "const".to_string(),
            },
        );

        assert_eq!(REG.name, "const_api");
        assert_eq!(REG.version, "v2");

        // Exercise closures to cover their bodies
        let inst = REG.create();
        assert_eq!(inst._data, "const");
        let meta = REG.metadata();
        assert_eq!(meta._name, "const");
    }

    /// Test Registration trait name() method
    #[test]
    fn test_registration_trait_name_method() {
        let reg = TestRegistration::new(
            "api_name_test",
            "v1",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        let name = reg.name();
        assert_eq!(name, "api_name_test");
        assert!(!name.is_empty());

        // Exercise closures to cover their bodies
        let inst = reg.create();
        assert_eq!(inst._data, "test");
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    /// Test Registration trait version() method
    #[test]
    fn test_registration_trait_version_method() {
        let reg = TestRegistration::new(
            "test_api",
            "v2.0.0",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        let version = reg.version();
        assert_eq!(version, "v2.0.0");

        // Exercise closures to cover their bodies
        let inst = reg.create();
        assert_eq!(inst._data, "test");
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    /// Test Registration trait create() method
    #[test]
    fn test_registration_trait_create_method() {
        let reg = TestRegistration::new(
            "test_api",
            "v1",
            || MockInstance {
                _data: "created_instance".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        let instance = reg.create();
        assert_eq!(instance._data, "created_instance");

        // Also exercise metadata closure
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    /// Test Registration trait metadata() method
    #[test]
    fn test_registration_trait_metadata_method() {
        let reg = TestRegistration::new(
            "test_api",
            "v1",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "metadata_value".to_string(),
            },
        );

        let metadata = reg.metadata();
        assert_eq!(metadata._name, "metadata_value");

        // Also exercise create closure
        let inst = reg.create();
        assert_eq!(inst._data, "test");
    }

    /// Test Send + Sync + 'static bounds
    #[test]
    fn test_registration_send_sync_static_bounds() {
        fn requires_send_sync<T: Send + Sync>() {}
        fn requires_static<T: 'static>() {}

        requires_send_sync::<TestRegistration>();
        requires_static::<TestRegistration>();

        // Also test the trait object
        fn requires_registration<T: Registration>() {}
        requires_registration::<TestRegistration>();
    }

    /// Test Clone and Copy trait
    #[test]
    fn test_registration_clone_copy_traits() {
        let reg = TestRegistration::new(
            "test_api",
            "v1",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        // Test Copy
        let reg_copy = reg;
        assert_eq!(reg_copy.name(), "test_api");

        // Test Clone
        let reg_cloned = reg;
        assert_eq!(reg_cloned.name(), "test_api");
        assert_eq!(reg_cloned.version(), "v1");

        // Original should still be valid after clone
        assert_eq!(reg.name(), "test_api");

        // Exercise closures to cover their bodies
        let inst = reg.create();
        assert_eq!(inst._data, "test");
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    /// Test Debug trait output
    #[test]
    fn test_registration_debug_trait() {
        let reg = TestRegistration::new(
            "debug_api",
            "v1",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        let debug_output = format!("{:?}", reg);
        assert!(debug_output.contains("debug_api"));
        assert!(debug_output.contains("v1"));

        // Exercise closures to cover their bodies
        let inst = reg.create();
        assert_eq!(inst._data, "test");
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    /// Test empty name and version boundary cases
    #[test]
    fn test_registration_empty_name_and_version() {
        let reg = TestRegistration::new(
            "",
            "",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        assert_eq!(reg.name(), "");
        assert_eq!(reg.version(), "");
        assert_eq!(reg.name, "");
        assert_eq!(reg.version, "");

        // Exercise closures to cover their bodies
        let inst = reg.create();
        assert_eq!(inst._data, "test");
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    /// Test special characters in name/version
    #[test]
    fn test_registration_special_characters_name() {
        let reg = TestRegistration::new(
            "api-with-dashes_and_underscores",
            "v1.0.0-alpha+build.123",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        assert_eq!(reg.name(), "api-with-dashes_and_underscores");
        assert_eq!(reg.version(), "v1.0.0-alpha+build.123");

        // Exercise closures to cover their bodies
        let inst = reg.create();
        assert_eq!(inst._data, "test");
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    /// Test multiple define_registration! in same scope
    #[test]
    fn test_multiple_define_registration_same_scope() {
        define_registration!(RegA, MockInstance, MockMetadata);
        define_registration!(RegB, MockInstance, MockMetadata);
        define_registration!(RegC, MockInstance, MockMetadata);

        let a = RegA::new(
            "a",
            "v1",
            || MockInstance { _data: "a".into() },
            || MockMetadata { _name: "a".into() },
        );
        let b = RegB::new(
            "b",
            "v1",
            || MockInstance { _data: "b".into() },
            || MockMetadata { _name: "b".into() },
        );
        let c = RegC::new(
            "c",
            "v1",
            || MockInstance { _data: "c".into() },
            || MockMetadata { _name: "c".into() },
        );

        assert_eq!(a.name(), "a");
        assert_eq!(b.name(), "b");
        assert_eq!(c.name(), "c");

        // Exercise closures to cover their bodies
        let ia = a.create();
        assert_eq!(ia._data, "a");
        let ma = a.metadata();
        assert_eq!(ma._name, "a");
        let ib = b.create();
        assert_eq!(ib._data, "b");
        let mb = b.metadata();
        assert_eq!(mb._name, "b");
        let ic = c.create();
        assert_eq!(ic._data, "c");
        let mc = c.metadata();
        assert_eq!(mc._name, "c");
    }

    /// Test inventory collect macro registration mechanism
    #[test]
    fn test_registration_inventory_collect_macro() {
        // inventory::collect! should register the type
        // We verify this by checking the type is collectible
        use std::any::TypeId;

        let reg = TestRegistration::new(
            "inventory_test",
            "v1",
            || MockInstance {
                _data: "test".to_string(),
            },
            || MockMetadata {
                _name: "test".to_string(),
            },
        );

        // TypeId should be available
        let _type_id = TypeId::of::<TestRegistration>();

        // Registration should implement the trait
        let _registration: &dyn Registration<Instance = MockInstance, Metadata = MockMetadata> =
            &reg;

        // Exercise closures to cover their bodies
        let inst = reg.create();
        assert_eq!(inst._data, "test");
        let meta = reg.metadata();
        assert_eq!(meta._name, "test");
    }

    #[test]
    fn test_registration_different_instance_types() {
        define_registration!(RegWithInstanceA, InstanceTypeA, MockMetadata);
        define_registration!(RegWithInstanceB, InstanceTypeB, MockMetadata);

        let reg_a = RegWithInstanceA::new(
            "instance_a",
            "v1",
            || InstanceTypeA { value: 42 },
            || MockMetadata {
                _name: "a".to_string(),
            },
        );

        let reg_b = RegWithInstanceB::new(
            "instance_b",
            "v1",
            || InstanceTypeB {
                text: "hello".to_string(),
            },
            || MockMetadata {
                _name: "b".to_string(),
            },
        );

        let instance_a = reg_a.create();
        let instance_b = reg_b.create();

        assert_eq!(instance_a.value, 42);
        assert_eq!(instance_b.text, "hello");

        // Also exercise metadata closures
        let meta_a = reg_a.metadata();
        assert_eq!(meta_a._name, "a");
        let meta_b = reg_b.metadata();
        assert_eq!(meta_b._name, "b");
    }

    #[test]
    fn test_registration_different_metadata_types() {
        define_registration!(RegWithMetadataA, MockInstance, MetadataTypeA);
        define_registration!(RegWithMetadataB, MockInstance, MetadataTypeB);

        let reg_a = RegWithMetadataA::new(
            "metadata_a",
            "v1",
            || MockInstance {
                _data: "a".to_string(),
            },
            || MetadataTypeA { id: 100 },
        );

        let reg_b = RegWithMetadataB::new(
            "metadata_b",
            "v1",
            || MockInstance {
                _data: "b".to_string(),
            },
            || MetadataTypeB {
                tags: vec!["tag1".to_string(), "tag2".to_string()],
            },
        );

        let metadata_a = reg_a.metadata();
        let metadata_b = reg_b.metadata();

        assert_eq!(metadata_a.id, 100);
        assert_eq!(metadata_b.tags.len(), 2);

        // Also exercise create closures
        let inst_a = reg_a.create();
        assert_eq!(inst_a._data, "a");
        let inst_b = reg_b.create();
        assert_eq!(inst_b._data, "b");
    }
}