hxrts-aura-composition 0.2.0

Aura Layer 3: Handler composition and effect system assembly
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
//! Composite Handler for combining multiple effect handlers
//!
//! This module provides a composite handler that can delegate to multiple
//! specialized handlers based on effect type, enabling flexible composition
//! and modular handler architecture.

use async_trait::async_trait;
use std::collections::HashMap;

use crate::registry::{
    EffectRegistry, Handler, HandlerContext, HandlerError, RegisterAllOptions, RegistrableHandler,
    RegistryError,
};
use aura_core::effects::registry as effect_registry;
use aura_core::{DeviceId, EffectType, ExecutionMode};
use aura_mpst::LocalSessionType;

/// A composite handler that delegates to specialized handlers based on effect type
pub struct CompositeHandler {
    /// Effect registry for dispatching operations
    registry: EffectRegistry,
    /// Optional session handler for choreographic execution
    session_handler: Option<Box<dyn Handler>>,
    /// Device ID
    device_id: DeviceId,
}

impl CompositeHandler {
    // Adapter-style composite
    /// Create a new composite handler
    pub fn new(device_id: DeviceId, execution_mode: ExecutionMode) -> Self {
        Self {
            registry: EffectRegistry::new(execution_mode),
            session_handler: None,
            device_id,
        }
    }

    /// Create a composite handler for testing
    pub fn for_testing(device_id: DeviceId) -> Self {
        Self::new(device_id, ExecutionMode::Testing)
    }

    /// Create a composite handler for production
    pub fn for_production(device_id: DeviceId) -> Self {
        Self::new(device_id, ExecutionMode::Production)
    }

    /// Create a composite handler for simulation
    pub fn for_simulation(device_id: DeviceId, seed: u64) -> Self {
        Self::new(device_id, ExecutionMode::Simulation { seed })
    }

    /// Register a handler for a specific effect type
    pub fn register_handler(
        &mut self,
        effect_type: EffectType,
        handler: Box<dyn Handler>,
    ) -> Result<(), CompositeError> {
        if !handler.supports_effect(effect_type) {
            return Err(CompositeError::UnsupportedEffect { effect_type });
        }
        if effect_type == EffectType::Choreographic {
            self.session_handler = Some(handler);
            return Ok(());
        }

        let adapter = Box::new(HandlerRegistrableAdapter::new(handler));
        self.registry
            .register_handler(effect_type, adapter)
            .map_err(|e| CompositeError::HandlerExecutionFailed {
                effect_type,
                source: HandlerError::ExecutionFailed {
                    source: Box::new(e),
                },
            })?;

        Ok(())
    }

    /// Register the default handler bundle.
    ///
    /// Requires explicit opt-in for impure handlers via `RegisterAllOptions`.
    pub fn register_all(&mut self, options: RegisterAllOptions) -> Result<(), RegistryError> {
        self.registry.register_all(options)
    }

    /// Unregister a handler for a specific effect type
    pub fn unregister_handler(
        &mut self,
        effect_type: EffectType,
    ) -> Option<Box<dyn RegistrableHandler>> {
        if effect_type == EffectType::Choreographic {
            self.session_handler.take();
            return None;
        }
        self.registry.unregister_handler(effect_type)
    }

    /// Check if a handler is registered for an effect type
    pub fn has_handler(&self, effect_type: EffectType) -> bool {
        if effect_type == EffectType::Choreographic {
            return self.session_handler.is_some();
        }
        self.registry.is_registered(effect_type)
    }

    /// Get all registered effect types
    pub fn registered_effect_types(&self) -> Vec<EffectType> {
        let mut effects = self.registry.registered_effect_types();
        if self.session_handler.is_some() {
            effects.push(EffectType::Choreographic);
        }
        effects
    }

    /// Get the device ID
    pub fn device_id(&self) -> DeviceId {
        self.device_id
    }
}

/// Error type for composite handler operations
#[derive(Debug, thiserror::Error)]
pub enum CompositeError {
    /// Effect type not supported by handler
    #[error("Effect type {effect_type:?} not supported by handler")]
    UnsupportedEffect { effect_type: EffectType },

    /// No handler registered for effect type
    #[error("No handler registered for effect type {effect_type:?}")]
    NoHandlerRegistered { effect_type: EffectType },

    /// Handler execution failed
    #[error("Handler execution failed for effect type {effect_type:?}")]
    HandlerExecutionFailed {
        effect_type: EffectType,
        #[source]
        source: HandlerError,
    },
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl Handler for CompositeHandler {
    // Adapter-style composite
    async fn execute_effect(
        &self,
        effect_type: EffectType,
        operation: &str,
        parameters: &[u8],
        ctx: &HandlerContext,
    ) -> Result<Vec<u8>, HandlerError> {
        self.registry
            .execute_effect(effect_type, operation, parameters, ctx)
            .await
    }

    async fn execute_session(
        &self,
        session: LocalSessionType,
        ctx: &HandlerContext,
    ) -> Result<(), HandlerError> {
        // Sessions are executed exclusively by a registered choreographic handler
        if let Some(handler) = self.session_handler.as_ref() {
            handler.execute_session(session, ctx).await
        } else {
            // Return a session execution error if no choreographic handler is available
            Err(HandlerError::SessionExecution {
                source: "No choreographic handler registered".into(),
            })
        }
    }

    fn supports_effect(&self, effect_type: EffectType) -> bool {
        if effect_type == EffectType::Choreographic {
            return self.session_handler.is_some();
        }
        self.registry.supports_effect(effect_type)
    }

    fn execution_mode(&self) -> ExecutionMode {
        self.registry.execution_mode()
    }
}

/// Builder for creating composite handlers
pub struct CompositeHandlerBuilder {
    device_id: DeviceId,
    execution_mode: ExecutionMode,
    handlers: HashMap<EffectType, Box<dyn Handler>>,
}

impl CompositeHandlerBuilder {
    /// Create a new builder
    pub fn new(device_id: DeviceId) -> Self {
        Self {
            device_id,
            execution_mode: ExecutionMode::Testing,
            handlers: HashMap::new(),
        }
    }

    /// Set execution mode
    pub fn execution_mode(mut self, mode: ExecutionMode) -> Self {
        self.execution_mode = mode;
        self
    }

    /// Add a handler for an effect type
    pub fn with_handler(
        mut self,
        effect_type: EffectType,
        handler: Box<dyn Handler>,
    ) -> Result<Self, CompositeError> {
        if !handler.supports_effect(effect_type) {
            return Err(CompositeError::UnsupportedEffect { effect_type });
        }
        self.handlers.insert(effect_type, handler);
        Ok(self)
    }

    /// Build the composite handler
    pub fn build(self) -> CompositeHandler {
        let mut composite = CompositeHandler::new(self.device_id, self.execution_mode);
        for (effect_type, handler) in self.handlers {
            // We know the handler supports the effect type from the with_handler check
            let _ = composite.register_handler(effect_type, handler);
        }
        composite
    }
}

/// Adapter to make CompositeHandler work as RegistrableHandler
pub struct CompositeHandlerAdapter {
    composite: CompositeHandler,
}

impl CompositeHandlerAdapter {
    /// Create a new adapter
    pub fn new(composite: CompositeHandler) -> Self {
        Self { composite }
    }

    /// Create adapter for testing
    pub fn for_testing(device_id: DeviceId) -> Self {
        Self::new(CompositeHandler::for_testing(device_id))
    }

    /// Create adapter for production
    pub fn for_production(device_id: DeviceId) -> Self {
        Self::new(CompositeHandler::for_production(device_id))
    }

    /// Create adapter for simulation
    pub fn for_simulation(device_id: DeviceId, seed: u64) -> Self {
        Self::new(CompositeHandler::for_simulation(device_id, seed))
    }

    /// Register a handler
    pub fn register_handler(
        &mut self,
        effect_type: EffectType,
        handler: Box<dyn Handler>,
    ) -> Result<(), CompositeError> {
        self.composite.register_handler(effect_type, handler)
    }

    /// Get the underlying composite handler
    pub fn into_composite(self) -> CompositeHandler {
        self.composite
    }

    /// Get a reference to the composite handler
    pub fn composite(&self) -> &CompositeHandler {
        &self.composite
    }

    /// Get a mutable reference to the composite handler
    pub fn composite_mut(&mut self) -> &mut CompositeHandler {
        &mut self.composite
    }
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl Handler for CompositeHandlerAdapter {
    async fn execute_effect(
        &self,
        effect_type: EffectType,
        operation: &str,
        parameters: &[u8],
        ctx: &HandlerContext,
    ) -> Result<Vec<u8>, HandlerError> {
        self.composite
            .execute_effect(effect_type, operation, parameters, ctx)
            .await
    }

    async fn execute_session(
        &self,
        session: LocalSessionType,
        ctx: &HandlerContext,
    ) -> Result<(), HandlerError> {
        self.composite.execute_session(session, ctx).await
    }

    fn supports_effect(&self, effect_type: EffectType) -> bool {
        self.composite.supports_effect(effect_type)
    }

    fn execution_mode(&self) -> ExecutionMode {
        self.composite.execution_mode()
    }
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl RegistrableHandler for CompositeHandlerAdapter {
    async fn execute_operation_bytes(
        &self,
        effect_type: EffectType,
        operation: &str,
        parameters: &[u8],
        ctx: &HandlerContext,
    ) -> Result<Vec<u8>, HandlerError> {
        self.execute_effect(effect_type, operation, parameters, ctx)
            .await
    }

    fn supported_operations(&self, effect_type: EffectType) -> Vec<String> {
        effect_registry::operations_for(effect_type)
            .iter()
            .map(|op| (*op).to_string())
            .collect()
    }

    fn supports_effect(&self, effect_type: EffectType) -> bool {
        self.composite.supports_effect(effect_type)
    }

    fn execution_mode(&self) -> ExecutionMode {
        self.composite.execution_mode()
    }
}

/// Adapter to expose a `Handler` as a `RegistrableHandler` for registry dispatch.
struct HandlerRegistrableAdapter {
    handler: Box<dyn Handler>,
}

impl HandlerRegistrableAdapter {
    fn new(handler: Box<dyn Handler>) -> Self {
        Self { handler }
    }
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl RegistrableHandler for HandlerRegistrableAdapter {
    async fn execute_operation_bytes(
        &self,
        effect_type: EffectType,
        operation: &str,
        parameters: &[u8],
        ctx: &HandlerContext,
    ) -> Result<Vec<u8>, HandlerError> {
        self.handler
            .execute_effect(effect_type, operation, parameters, ctx)
            .await
    }

    fn supported_operations(&self, effect_type: EffectType) -> Vec<String> {
        effect_registry::operations_for(effect_type)
            .iter()
            .map(|op| (*op).to_string())
            .collect()
    }

    fn supports_effect(&self, effect_type: EffectType) -> bool {
        self.handler.supports_effect(effect_type)
    }

    fn execution_mode(&self) -> ExecutionMode {
        self.handler.execution_mode()
    }
}

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

    /// Minimal handler used for registration tests
    struct TestConsoleHandler;

    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl Handler for TestConsoleHandler {
        async fn execute_effect(
            &self,
            _effect_type: EffectType,
            operation: &str,
            _parameters: &[u8],
            _ctx: &HandlerContext,
        ) -> Result<Vec<u8>, HandlerError> {
            match operation {
                "log_info" | "log_warn" | "log_error" => Ok(vec![]),
                _ => Err(HandlerError::UnknownOperation {
                    effect_type: EffectType::Console,
                    operation: operation.to_string(),
                }),
            }
        }

        async fn execute_session(
            &self,
            _session: LocalSessionType,
            _ctx: &HandlerContext,
        ) -> Result<(), HandlerError> {
            Err(HandlerError::SessionExecution {
                source: "Console handler does not execute sessions".into(),
            })
        }

        fn supports_effect(&self, effect_type: EffectType) -> bool {
            effect_type == EffectType::Console
        }

        fn execution_mode(&self) -> ExecutionMode {
            ExecutionMode::Testing
        }
    }

    /// All three execution modes (Testing, Production, Simulation) produce
    /// handlers with the correct mode and device identity.
    #[test]
    fn test_composite_handler_creation() {
        let device_id = DeviceId::new_from_entropy([1u8; 32]);

        let handler = CompositeHandler::for_testing(device_id);
        assert_eq!(handler.execution_mode(), ExecutionMode::Testing);
        assert_eq!(handler.device_id(), device_id);

        let handler = CompositeHandler::for_production(device_id);
        assert_eq!(handler.execution_mode(), ExecutionMode::Production);

        let handler = CompositeHandler::for_simulation(device_id, 42);
        assert_eq!(
            handler.execution_mode(),
            ExecutionMode::Simulation { seed: 42 }
        );
    }

    /// Builder sets execution mode and preserves device identity through build.
    #[test]
    fn test_composite_handler_builder() {
        let device_id = DeviceId::new_from_entropy([2u8; 32]);

        let builder =
            CompositeHandlerBuilder::new(device_id).execution_mode(ExecutionMode::Production);

        // Note: We can't easily test handler registration here without mock handlers
        // In a real test, we would create mock handlers and register them

        let composite = builder.build();
        assert_eq!(composite.execution_mode(), ExecutionMode::Production);
        assert_eq!(composite.device_id(), device_id);
    }

    /// Adapter factories produce the correct execution mode for each variant.
    #[test]
    fn test_composite_handler_adapter() {
        let device_id = DeviceId::new_from_entropy([3u8; 32]);

        let adapter = CompositeHandlerAdapter::for_testing(device_id);
        assert_eq!(Handler::execution_mode(&adapter), ExecutionMode::Testing);

        let adapter = CompositeHandlerAdapter::for_production(device_id);
        assert_eq!(Handler::execution_mode(&adapter), ExecutionMode::Production);

        let adapter = CompositeHandlerAdapter::for_simulation(device_id, 42);
        assert_eq!(
            Handler::execution_mode(&adapter),
            ExecutionMode::Simulation { seed: 42 }
        );
    }

    /// Registering a handler updates `has_handler` and `registered_effect_types`.
    #[test]
    fn test_handler_registration() {
        let device_id = DeviceId::new_from_entropy([4u8; 32]);
        let mut composite = CompositeHandler::for_testing(device_id);

        // Initially no handlers registered
        assert!(!composite.has_handler(EffectType::Console));
        assert!(composite.registered_effect_types().is_empty());

        // Register a minimal console handler and validate registration bookkeeping
        let handler = Box::new(TestConsoleHandler);
        composite
            .register_handler(EffectType::Console, handler)
            .unwrap();

        assert!(composite.has_handler(EffectType::Console));
        assert_eq!(
            composite.registered_effect_types(),
            vec![EffectType::Console]
        );
    }

    /// Operation mapping returns known operations for registered types and
    /// empty for unsupported types.
    #[test]
    fn test_supported_operations() {
        let device_id = DeviceId::new_from_entropy([5u8; 32]);
        let adapter = CompositeHandlerAdapter::for_testing(device_id);

        // Test that the operation mapping exists (even without registered handlers)
        let console_ops = adapter.supported_operations(EffectType::Console);
        assert!(console_ops.contains(&"log_info".to_string()));

        let random_ops = adapter.supported_operations(EffectType::Random);
        assert!(random_ops.contains(&"random_bytes".to_string()));

        // Unsupported effect type should return empty list
        let unknown_ops = adapter.supported_operations(EffectType::PropertyChecking);
        assert!(unknown_ops.is_empty());
    }
}