tairitsu 0.5.18

Core WASM Component Model runtime — Container, Registry, WIT binding, RON/Binary interop
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
//! Container - Generic WASM component container
//!
//! This module provides a generic container implementation that can run any WASM component.
//! Users need to implement WIT interface bindings and initialization themselves.

use anyhow::{Context as AnyhowContext, Result};

use wasmtime::{
    component::{Component, Linker},
    error::Context,
    Store,
};
use wasmtime_wasi::{ResourceTable, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};

#[cfg(feature = "dynamic")]
use crate::dynamic::host_imports::HostImportRegistry;
use crate::Image;

/// Base trait for host state
///
/// Users need to implement this trait to provide their own host functionality
pub trait HostStateImpl: WasiView + Send + 'static {
    /// Get user-defined state
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}

/// Default host state implementation
///
/// Provides basic WASI support, users can extend through inheritance or composition
pub struct HostState {
    wasi: WasiCtx,
    table: ResourceTable,
}

impl HostState {
    /// Create a new host state with no inherited capabilities
    ///
    /// The returned state has no stdio, network, or filesystem access by default.
    /// Use [`HostState::with_wasi`] or [`HostState::default`] if you need
    /// to customise WASI capabilities explicitly.
    pub fn new() -> Result<Self> {
        let wasi = WasiCtxBuilder::new().build();

        let table = ResourceTable::new();

        Ok(Self { wasi, table })
    }

    /// Create host state with custom WASI configuration
    pub fn with_wasi<F>(f: F) -> Result<Self>
    where
        F: FnOnce(&mut WasiCtxBuilder) -> &mut WasiCtxBuilder,
    {
        let mut builder = WasiCtxBuilder::new();
        f(&mut builder);
        let wasi = builder.build();

        let table = ResourceTable::new();

        Ok(Self { wasi, table })
    }
}

impl Default for HostState {
    fn default() -> Self {
        let wasi = WasiCtxBuilder::new().build();
        let table = ResourceTable::new();
        Self { wasi, table }
    }
}

impl WasiView for HostState {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

impl HostStateImpl for HostState {
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// Handle to a guest instance
///
/// This type wraps the instance type generated by WIT bindings.
/// Users need to interact with it through `GuestHandlerContext`.
pub struct GuestInstance {
    // The actual WIT binding instance is provided by the user when building Container
    // Box is used here to store any type
    inner: Box<dyn std::any::Any + Send + Sync>,

    // Dynamic instance reference (optional, controlled by cfg feature)
    #[cfg(feature = "dynamic")]
    dynamic_instance: Option<wasmtime::component::Instance>,
}

impl GuestInstance {
    /// Create a new guest instance
    ///
    /// # Arguments
    /// * `instance` - Instance type generated by WIT bindgen
    pub fn new<T: 'static + Send + Sync>(instance: T) -> Self {
        Self {
            inner: Box::new(instance),
            #[cfg(feature = "dynamic")]
            dynamic_instance: None,
        }
    }

    /// Create a new guest instance with a dynamic invocation handle.
    ///
    /// When the guest instance is a raw [`wasmtime::component::Instance`]
    /// (as opposed to a WIT-bindgen-generated wrapper), pass it as both
    /// arguments so that [`Container::call_guest_raw_desc`] and friends work
    /// without a typed WIT binding layer.
    #[cfg(feature = "dynamic")]
    pub fn new_dynamic(instance: wasmtime::component::Instance) -> Self {
        Self {
            inner: Box::new(instance),
            dynamic_instance: Some(instance),
        }
    }

    /// Get the underlying instance
    ///
    /// # Type Parameters
    /// * `T` - Instance type generated by WIT bindgen
    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
        self.inner.downcast_ref::<T>()
    }

    /// Get mutable reference to the underlying instance
    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.inner.downcast_mut::<T>()
    }

    /// Get export function for dynamic invocation (requires `dynamic` feature)
    #[cfg(feature = "dynamic")]
    pub fn get_export_func<T: HostStateImpl>(
        &self,
        _store: &mut Store<T>,
        _func_name: &str,
    ) -> Result<Option<wasmtime::component::Func>> {
        if let Some(ref instance) = self.dynamic_instance {
            Ok(instance.get_func(_store, _func_name))
        } else {
            Ok(None)
        }
    }

    /// Get the dynamic instance reference (for internal use during Container build)
    #[cfg(feature = "dynamic")]
    pub(crate) fn get_dynamic_instance_ref(&self) -> Option<&wasmtime::component::Instance> {
        self.dynamic_instance.as_ref()
    }
}

/// Context for building guest instances
///
/// Provides Linker, Store, and Component, allowing users to register their own WIT interfaces
pub struct GuestHandlerContext<'a, T: HostStateImpl> {
    pub linker: &'a mut Linker<T>,
    pub store: &'a mut Store<T>,
    pub component: &'a Component,
}

impl<'a, T: HostStateImpl> GuestHandlerContext<'a, T> {
    /// Create new context
    pub fn new(
        linker: &'a mut Linker<T>,
        store: &'a mut Store<T>,
        component: &'a Component,
    ) -> Self {
        Self {
            linker,
            store,
            component,
        }
    }
}

/// Container builder
///
/// Used to configure and create a WASM container instance.
///
/// # Multi-World Pattern
///
/// When multiple WIT worlds share the same WASM component (e.g. `webhook-handler`
/// and `bot-handler`), create separate `Container` instances from the same `Image`.
/// Each container's [`with_guest_initializer`](ContainerBuilder::with_guest_initializer)
/// closure binds whichever WIT world is needed:
///
/// ```ignore
/// // Same image, different WIT worlds
/// let webhook = Container::builder(image.clone())
///     .with_guest_initializer(|ctx| {
///         WebhookHandler::add_to_linker(ctx.linker, |s| &mut s.data)?;
///         let inst = WebhookHandler::instantiate(ctx.store, ctx.component, ctx.linker)?;
///         Ok(GuestInstance::new(inst))
///     })
///     .build()?;
///
/// let bot = Container::builder(image)
///     .with_guest_initializer(|ctx| {
///         BotHandler::add_to_linker(ctx.linker, |s| &mut s.data)?;
///         let inst = BotHandler::instantiate(ctx.store, ctx.component, ctx.linker)?;
///         Ok(GuestInstance::new(inst))
///     })
///     .build()?;
/// ```
pub struct ContainerBuilder<T: HostStateImpl> {
    image: Image,
    host_state: T,
    fuel_limit: Option<u64>,
    epoch_deadline: Option<u64>,
    #[allow(clippy::type_complexity)]
    host_linker_init: Option<Box<dyn FnOnce(&mut Linker<T>) -> Result<(), anyhow::Error> + Send>>,
    #[allow(clippy::type_complexity)]
    guest_initializer: Option<
        Box<
            dyn for<'a> FnOnce(GuestHandlerContext<'a, T>) -> Result<GuestInstance, anyhow::Error>
                + Send,
        >,
    >,
}

impl<T: HostStateImpl> ContainerBuilder<T>
where
    T: Default,
{
    /// Create builder from Image
    pub fn new(image: Image) -> Self {
        Self {
            image,
            host_state: T::default(),
            fuel_limit: None,
            epoch_deadline: None,
            host_linker_init: None,
            guest_initializer: None,
        }
    }
}

impl<T: HostStateImpl> ContainerBuilder<T> {
    /// Use custom host state
    pub fn with_host_state(mut self, state: T) -> Self {
        self.host_state = state;
        self
    }

    /// Set fuel limit for the container's WASM store.
    ///
    /// Requires that the [`Image`](crate::Image) was created with
    /// [`Config::consume_fuel(true)`](wasmtime::Config::consume_fuel) via
    /// [`Image::new_with_config`].
    ///
    /// Each consumed unit roughly corresponds to one WASM instruction.
    /// When fuel runs out the guest invocation traps.
    pub fn with_fuel_limit(mut self, limit: u64) -> Self {
        self.fuel_limit = Some(limit);
        self
    }

    /// Set epoch deadline for cooperative interruption of the guest.
    ///
    /// Requires that the [`Image`](crate::Image) was created with
    /// [`Config::epoch_interruption(true)`](wasmtime::Config::epoch_interruption)
    /// via [`Image::new_with_config`].
    ///
    /// The deadline counts down each time [`Engine::increment_epoch`] is called.
    /// When it reaches zero the guest traps, allowing the host to implement
    /// time-based timeouts.
    pub fn with_epoch_deadline(mut self, deadline: u64) -> Self {
        self.epoch_deadline = Some(deadline);
        self
    }

    /// Register additional host imports with the linker before guest instantiation.
    ///
    /// This is called after WASI is added to the linker but before the guest
    /// initializer runs, allowing host imports to be available when the component
    /// is instantiated.
    ///
    /// # Example
    /// ```ignore
    /// let container = Container::builder(image)
    ///     .with_host_linker(|linker| {
    ///         MyHostImpl::add_to_linker(linker, |state| &mut state.my_data)
    ///     })
    ///     .with_guest_initializer(|ctx| { ... })
    ///     .build();
    /// ```
    pub fn with_host_linker<F>(mut self, func: F) -> Self
    where
        F: FnOnce(&mut Linker<T>) -> Result<(), anyhow::Error> + Send + 'static,
    {
        self.host_linker_init = Some(Box::new(func));
        self
    }

    /// Set guest instance initializer
    ///
    /// # Arguments
    /// * `f` - A closure that receives `GuestHandlerContext` and returns WIT-bound instance
    ///
    /// # Example
    /// ```ignore
    /// let container = Container::builder(image)?
    ///     .with_guest_initializer(|ctx| {
    ///         // Register your WIT interface to linker
    ///         MyWit::add_to_linker(ctx.linker, |state| &mut state.my_state)?;
    ///
    ///         // Instantiate component
    ///         let instance = MyWit::instantiate(ctx.store, ctx.component, ctx.linker)?;
    ///
    ///         Ok(GuestInstance::new(instance))
    ///     })?
    ///     .build();
    /// ```
    pub fn with_guest_initializer<F>(mut self, f: F) -> Self
    where
        F: for<'a> FnOnce(GuestHandlerContext<'a, T>) -> Result<GuestInstance, anyhow::Error>
            + Send
            + 'static,
    {
        self.guest_initializer = Some(Box::new(f));
        self
    }

    /// Build container
    pub fn build(self) -> Result<Container<T>> {
        let mut store = Store::new(self.image.engine(), self.host_state);

        if let Some(fuel) = self.fuel_limit {
            store
                .set_fuel(fuel)
                .context("Failed to set fuel limit (ensure Image was created with consume_fuel(true) in Config)")?;
        }
        if let Some(deadline) = self.epoch_deadline {
            store.set_epoch_deadline(deadline);
        }

        let mut linker = Linker::new(self.image.engine());
        wasmtime_wasi::p2::add_to_linker_sync(&mut linker)
            .context("Failed to add WASI to linker")?;

        // Apply custom host linker configuration (e.g. registering host imports).
        if let Some(linker_init) = self.host_linker_init {
            linker_init(&mut linker).context("Failed to configure host linker")?;
        }

        // Clone the component for type introspection
        // Component is reference-counted internally, so this is cheap
        let component = self.image.component().clone();

        let guest_instance = if let Some(initializer) = self.guest_initializer {
            let ctx = GuestHandlerContext::new(&mut linker, &mut store, &component);
            initializer(ctx)?
        } else {
            return Err(anyhow::anyhow!(
                "Guest initializer is required. Use with_guest_initializer() to set it."
            ));
        };

        // Extract dynamic instance from guest_instance if available
        #[cfg(feature = "dynamic")]
        let dynamic_instance = guest_instance.get_dynamic_instance_ref().cloned();

        Ok(Container {
            store,
            guest: guest_instance,
            state: ContainerState::Created,
            #[cfg(feature = "dynamic")]
            dynamic_instance,
            #[cfg(feature = "dynamic")]
            host_imports: None,
        })
    }
}

/// Lifecycle state of a [`Container`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContainerState {
    /// Container has been built but no guest call has been made yet.
    Created,
    /// Container is operational — at least one guest call has succeeded.
    Running,
    /// Container was explicitly stopped via [`Container::stop`].
    Stopped,
    /// An unrecoverable error occurred. Contains the error message.
    Error(String),
}

/// A Container represents a running instance of an Image
///
/// Similar to Docker containers, it maintains runtime state and can be started/stopped.
///
/// # Async usage
///
/// All guest-call methods are synchronous. To call them from an async context
/// (e.g. a tokio web-handler), wrap the container in `Arc<Mutex<…>>` and use
/// [`tokio::task::spawn_blocking`]:
///
/// ```ignore
/// use std::sync::{Arc, Mutex};
/// use tairitsu::Container;
///
/// let container = Arc::new(Mutex::new(container));
/// let c = container.clone();
/// let result = tokio::task::spawn_blocking(move || {
///     c.lock().unwrap().call_guest_raw_desc("handle", payload)
/// }).await??;
/// ```
///
/// `Container<T>` is `Send` when `T: Send` (the default [`HostState`] satisfies
/// this). It is **not** `Sync`, so always guard with a `Mutex`.
pub struct Container<T: HostStateImpl = HostState> {
    store: Store<T>,
    guest: GuestInstance,
    state: ContainerState,

    /// Dynamic instance for runtime function invocation (duplicated from guest for easier access)
    #[cfg(feature = "dynamic")]
    dynamic_instance: Option<wasmtime::component::Instance>,

    /// Host import registry for dynamic host function invocation
    #[cfg(feature = "dynamic")]
    host_imports: Option<HostImportRegistry>,
}

impl Container {
    /// Create container builder from Image
    pub fn builder(image: Image) -> ContainerBuilder<HostState> {
        ContainerBuilder::new(image)
    }
}

impl<T: HostStateImpl> Container<T> {
    /// Get mutable reference to Store
    pub fn store_mut(&mut self) -> &mut Store<T> {
        &mut self.store
    }

    /// Get immutable reference to Store
    pub fn store(&self) -> &Store<T> {
        &self.store
    }

    /// Get reference to guest instance
    pub fn guest(&self) -> &GuestInstance {
        &self.guest
    }

    /// Get mutable reference to guest instance
    pub fn guest_mut(&mut self) -> &mut GuestInstance {
        &mut self.guest
    }

    /// Get mutable reference to host state
    pub fn host_state_mut(&mut self) -> &mut T {
        self.store.data_mut()
    }

    /// Get immutable reference to host state
    pub fn host_state(&self) -> &T {
        self.store.data()
    }

    /// Return the current lifecycle state of the container.
    pub fn state(&self) -> &ContainerState {
        &self.state
    }

    /// Stop the container.
    ///
    /// After stopping, subsequent guest calls will return an error.
    /// This transitions the state to [`ContainerState::Stopped`].
    pub fn stop(&mut self) {
        self.state = ContainerState::Stopped;
    }

    /// Call a guest function by name with JSON payload
    ///
    /// This is a convenience method for dynamic invocation.
    /// Requires that the guest instance implements the appropriate interface.
    ///
    /// # Arguments
    /// * `function_name` - Name of the function to call
    /// * `json_payload` - JSON string containing function arguments
    ///
    /// # Returns
    /// JSON string containing the result
    ///
    /// # Example
    /// ```ignore
    /// let result = container.call_guest_json("process", r#"{"input":"hello"}"#)?;
    /// ```
    #[deprecated(
        since = "0.6.0",
        note = "use call_guest_raw_desc() with RON format instead"
    )]
    pub fn call_guest_json(&mut self, function_name: &str, _json_payload: &str) -> Result<String> {
        anyhow::bail!(
            "JSON invocation is not supported. Use call_guest_raw_desc() instead with RON format for better Rust type compatibility. Function: {}",
            function_name,
        )
    }

    /// Call a guest function by name with raw descriptor payload
    ///
    /// This is the preferred method for dynamic invocation using type descriptors at runtime.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// Uses RON format for serialization which provides better Rust type compatibility than JSON.
    ///
    /// # Arguments
    /// * `function_name` - Name of the function to call
    /// * `raw_desc_payload` - RON string containing function arguments (using type descriptors)
    ///
    /// # Returns
    /// RON string containing the result
    ///
    /// # Example
    /// ```ignore
    /// let result = container.call_guest_raw_desc("process", r#"Request { input: "hello", count: 42 }"#)?;
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn call_guest_raw_desc(
        &mut self,
        function_name: &str,
        raw_desc_payload: &str,
    ) -> Result<String> {
        match &self.state {
            ContainerState::Stopped => {
                anyhow::bail!("Container is stopped");
            }
            ContainerState::Error(e) => {
                anyhow::bail!("Container is in error state: {}", e);
            }
            _ => {}
        }

        let result = self.call_guest_raw_desc_inner(function_name, raw_desc_payload);
        match &result {
            Ok(_) => self.state = ContainerState::Running,
            Err(e) => {
                let is_wasm_fatal = e.downcast_ref::<wasmtime::Trap>().is_some();
                if is_wasm_fatal {
                    self.state = ContainerState::Error(e.to_string());
                }
            }
        }
        result
    }

    #[cfg(feature = "dynamic")]
    fn call_guest_raw_desc_inner(
        &mut self,
        function_name: &str,
        raw_desc_payload: &str,
    ) -> Result<String> {
        use wasmtime::component::Val;

        use crate::dynamic::{ron_to_val, val_to_ron};

        // Get the function (direct field access avoids borrow checker issues)
        let instance = self
            .dynamic_instance
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Dynamic instance not available"))?;

        let func = instance
            .get_func(&mut self.store, function_name)
            .ok_or_else(|| anyhow::anyhow!("Export function not found: {}", function_name))?;

        // Get function type info
        let func_ty = func.ty(&self.store);
        let param_types: Vec<_> = func_ty.params().collect();
        let result_types: Vec<_> = func_ty.results().collect();

        // Convert raw descriptor → Val
        let mut args = Vec::new();

        if param_types.len() == 1 {
            // Single parameter - direct parsing
            // Extract just the type from the (name, type) tuple
            let param_type = &param_types[0].1;
            args.push(ron_to_val(raw_desc_payload, param_type)?);
        } else {
            // Multiple parameters - parse as sequence/array
            let ron_array = if raw_desc_payload.trim().starts_with('[') {
                raw_desc_payload.to_string()
            } else if raw_desc_payload.trim().starts_with('(') {
                // RON treats tuples differently, convert to array syntax
                raw_desc_payload.to_string()
            } else {
                format!("[{}]", raw_desc_payload)
            };

            use ron::Value as RonValue;
            let ron_value: RonValue = ron::from_str(&ron_array)?;

            if let RonValue::Seq(items) = ron_value {
                if items.len() != param_types.len() {
                    anyhow::bail!(
                        "Parameter count mismatch: expected {}, got {}",
                        param_types.len(),
                        items.len()
                    );
                }
                for (ron_val, (_param_name, param_type)) in
                    items.into_iter().zip(param_types.iter())
                {
                    args.push(ron_value_to_val(ron_val, param_type)?);
                }
            } else {
                anyhow::bail!(
                    "Invalid raw descriptor payload for function with multiple parameters"
                );
            }
        }

        // Call the function
        let mut results = vec![Val::Bool(false); result_types.len()];
        func.call(&mut self.store, &args, &mut results)
            .context("Function call failed")?;

        // Convert Val → raw descriptor (RON)
        let output_ron: Result<Vec<_>> = results.iter().map(val_to_ron).collect();
        let output_ron = output_ron.context("Failed to convert result to RON")?;

        // Format output based on return value count
        let output = match output_ron.len() {
            0 => "()".to_string(),
            1 => output_ron[0].clone(),
            _ => format!("({})", output_ron.join(", ")),
        };

        Ok(output)
    }

    /// Call a guest function by name with binary payload
    ///
    /// This is the high-performance path using canonical ABI directly.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// # Arguments
    /// * `function_name` - Name of the function to call
    /// * `args` - Arguments as Val types
    ///
    /// # Returns
    /// Results as Val types
    ///
    /// # Example
    /// ```ignore
    /// use wasmtime::component::Val;
    /// let args = vec![Val::String("hello".to_string()), Val::U32(42)];
    /// let results = container.call_guest_binary("process", &args)?;
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn call_guest_binary(
        &mut self,
        function_name: &str,
        args: &[wasmtime::component::Val],
    ) -> Result<Vec<wasmtime::component::Val>> {
        match &self.state {
            ContainerState::Stopped => {
                anyhow::bail!("Container is stopped");
            }
            ContainerState::Error(e) => {
                anyhow::bail!("Container is in error state: {}", e);
            }
            _ => {}
        }

        let result = self.call_guest_binary_inner(function_name, args);
        match &result {
            Ok(_) => self.state = ContainerState::Running,
            Err(e) => {
                let msg = e.to_string();
                let is_wasm_fatal = msg.contains("trap")
                    || msg.contains("out of memory")
                    || msg.contains("fuel")
                    || e.downcast_ref::<wasmtime::Error>().is_some()
                    || e.downcast_ref::<wasmtime::Trap>().is_some();
                if is_wasm_fatal {
                    self.state = ContainerState::Error(msg);
                }
            }
        }
        result
    }

    #[cfg(feature = "dynamic")]
    fn call_guest_binary_inner(
        &mut self,
        function_name: &str,
        args: &[wasmtime::component::Val],
    ) -> Result<Vec<wasmtime::component::Val>> {
        use wasmtime::component::Val;

        // Get the function (direct field access avoids borrow checker issues)
        let instance = self
            .dynamic_instance
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Dynamic instance not available"))?;

        let func = instance
            .get_func(&mut self.store, function_name)
            .ok_or_else(|| anyhow::anyhow!("Export function not found: {}", function_name))?;

        // Get function type info
        let func_ty = func.ty(&self.store);
        let num_results = func_ty.results().count();

        // Call the function
        let mut results = vec![Val::Bool(false); num_results];
        func.call(&mut self.store, args, &mut results)
            .context("Function call failed")?;

        Ok(results)
    }

    /// Set the host import registry
    ///
    /// # Arguments
    /// * `registry` - Host import registry to use
    #[cfg(feature = "dynamic")]
    pub fn with_host_import_registry(&mut self, registry: HostImportRegistry) {
        self.host_imports = Some(registry);
    }

    /// Get mutable reference to host import registry
    #[cfg(feature = "dynamic")]
    pub fn host_imports_mut(&mut self) -> Option<&mut HostImportRegistry> {
        self.host_imports.as_mut()
    }

    /// Call a host import function by name with raw descriptor payload
    ///
    /// This allows dynamically calling host functions that the WASM component imports.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// # Arguments
    /// * `function_name` - Name of the host import function to call
    /// * `raw_desc_payload` - RON string containing function arguments
    ///
    /// # Returns
    /// RON string containing the result
    ///
    /// # Example
    /// ```ignore
    /// let result = container.call_host_import_raw_desc("log", r#"LogMessage { level: "info", msg: "hello" }"#)?;
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn call_host_import_raw_desc(
        &mut self,
        function_name: &str,
        raw_desc_payload: &str,
    ) -> Result<String> {
        use crate::dynamic::{ron_to_val, val_to_ron};

        let registry = self
            .host_imports
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Host import registry not initialized"))?;

        // Get function signature
        let (params, _results) = registry
            .get_signature(function_name)
            .ok_or_else(|| anyhow::anyhow!("Host import not found: {}", function_name))?;

        // Convert raw descriptor → Val
        let mut args = Vec::new();
        if params.len() == 1 {
            args.push(ron_to_val(raw_desc_payload, &params[0])?);
        } else {
            // Multiple parameters - parse as sequence/array
            let payload = raw_desc_payload.trim();
            let ron_array = if payload.starts_with('[') || payload.starts_with('(') {
                raw_desc_payload.to_string()
            } else {
                format!("[{}]", raw_desc_payload)
            };

            use ron::Value as RonValue;
            let ron_value: RonValue = ron::from_str(&ron_array)?;

            if let RonValue::Seq(items) = ron_value {
                if items.len() != params.len() {
                    anyhow::bail!(
                        "Parameter count mismatch: expected {}, got {}",
                        params.len(),
                        items.len()
                    );
                }
                for (ron_val, param_type) in items.into_iter().zip(params.iter()) {
                    args.push(ron_value_to_val(ron_val, param_type)?);
                }
            } else {
                anyhow::bail!(
                    "Invalid raw descriptor payload for function with multiple parameters"
                );
            }
        }

        // Call the function
        let result_vals = registry.call(function_name, &args)?;

        // Convert Val → raw descriptor (RON)
        let output_ron: Result<Vec<_>> = result_vals.iter().map(val_to_ron).collect();
        let output_ron = output_ron.context("Failed to convert result to RON")?;
        let output = match output_ron.len() {
            0 => "()".to_string(),
            1 => output_ron[0].clone(),
            _ => format!("({})", output_ron.join(", ")),
        };

        Ok(output)
    }

    /// List all guest export functions
    ///
    /// Returns information about all functions exported by the WASM component.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// # Returns
    /// Vector of export information including function names and types
    ///
    /// # Example
    /// ```ignore
    /// let exports = container.list_guest_exports()?;
    /// for export in exports {
    ///     println!("Function: {}", export.name);
    ///     println!("  Params: {:?}", export.params);
    ///     println!("  Results: {:?}", export.results);
    /// }
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn list_guest_exports(&mut self) -> Result<Vec<ExportInfo>> {
        if let Some(instance) = &self.dynamic_instance {
            let mut exports = Vec::new();

            // Try to get common export function names
            // This is a pragmatic approach since we can't easily iterate all exports
            // without knowing their names beforehand
            let potential_exports = vec![
                "init",
                "process",
                "getname",
                "getversion",
                "getfeatures",
                "shutdown",
                "notify",
                "add",
                "sub",
                "mul",
                "div",
                "to-upper",
                "to-lower",
                "reverse",
                "length",
                "process-numbers",
                "transform",
            ];

            for export_name in potential_exports {
                // Try to get the function
                if let Some(func) = instance.get_func(&mut self.store, export_name) {
                    // Get function type information
                    let func_ty = func.ty(&self.store);
                    let mut params = Vec::new();
                    let mut results = Vec::new();

                    // Extract parameter types (they come as (name, type) tuples)
                    for (param_name, param_type) in func_ty.params() {
                        params.push((param_name.to_string(), param_type.clone()));
                    }

                    // Extract result types
                    for result_type in func_ty.results() {
                        results.push(result_type.clone());
                    }

                    exports.push(ExportInfo {
                        name: export_name.to_string(),
                        params,
                        results,
                    });
                }
            }

            Ok(exports)
        } else {
            // No dynamic instance available, return empty list
            Ok(Vec::new())
        }
    }

    /// List all host import functions
    ///
    /// Returns information about all registered host import functions.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// # Returns
    /// Vector of import information including function names and types
    ///
    /// # Example
    /// ```ignore
    /// if let Some(imports) = container.list_host_imports()? {
    ///     for import in imports {
    ///         println!("Function: {}", import.name);
    ///     }
    /// }
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn list_host_imports(&self) -> Result<Vec<ImportInfo>> {
        if let Some(ref registry) = self.host_imports {
            let imports = registry.list_imports();
            imports
                .into_iter()
                .map(|name| {
                    let (params, results) =
                        AnyhowContext::with_context(registry.get_signature(name), || {
                            format!("missing signature for import: {name}")
                        })?;
                    Ok(ImportInfo {
                        name: name.to_string(),
                        params,
                        results,
                    })
                })
                .collect()
        } else {
            Ok(Vec::new())
        }
    }
}

/// Export function information
#[derive(Debug, Clone)]
pub struct ExportInfo {
    pub name: String,
    pub params: Vec<(String, wasmtime::component::Type)>,
    pub results: Vec<wasmtime::component::Type>,
}

/// Import function information
#[derive(Debug, Clone)]
pub struct ImportInfo {
    pub name: String,
    pub params: Vec<wasmtime::component::Type>,
    pub results: Vec<wasmtime::component::Type>,
}

/// Helper: RON Value to Val (for use in Container)
#[cfg(feature = "dynamic")]
fn ron_value_to_val(
    ron_value: ron::Value,
    target_type: &wasmtime::component::Type,
) -> Result<wasmtime::component::Val> {
    use crate::dynamic::ron_to_val;
    // Convert ron::Value to RON string, then use ron_to_val
    let ron_str = ron::to_string(&ron_value)?;
    ron_to_val(&ron_str, target_type)
}

impl<T: HostStateImpl> std::fmt::Debug for Container<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Container")
            .field("state", &self.state)
            .finish()
    }
}

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

    #[test]
    fn test_host_state_new_succeeds() {
        let state = HostState::new();
        assert!(state.is_ok(), "HostState::new() should succeed");
    }

    #[test]
    fn test_host_state_new_does_not_inherit_stdio_or_network() {
        let state = HostState::new().expect("should succeed");
        let _ = state;
    }

    #[test]
    fn test_host_state_default_does_not_panic() {
        let state = HostState::default();
        let _ = state;
    }

    #[test]
    fn test_host_state_new_equals_default() {
        let new_state = HostState::new().expect("new should succeed");
        let default_state = HostState::default();
        let _ = (new_state, default_state);
    }

    #[test]
    fn test_guest_instance_new_and_downcast_ref() {
        let instance: GuestInstance = GuestInstance::new(42i32);
        let val = instance.downcast_ref::<i32>();
        assert!(val.is_some());
        assert_eq!(*val.unwrap(), 42);

        let wrong = instance.downcast_ref::<String>();
        assert!(wrong.is_none());
    }

    #[test]
    fn test_guest_instance_downcast_mut() {
        let mut instance: GuestInstance = GuestInstance::new(vec![1, 2, 3]);
        {
            let v = instance.downcast_mut::<Vec<i32>>();
            assert!(v.is_some());
            v.unwrap().push(4);
        }
        let v = instance.downcast_ref::<Vec<i32>>();
        assert_eq!(v.unwrap(), &vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_guest_instance_with_string_type() {
        let instance: GuestInstance = GuestInstance::new(String::from("hello"));
        let val = instance.downcast_ref::<String>();
        assert_eq!(val.unwrap(), "hello");

        let mut instance = instance;
        instance
            .downcast_mut::<String>()
            .unwrap()
            .push_str(" world");
        assert_eq!(instance.downcast_ref::<String>().unwrap(), "hello world");
    }

    #[test]
    fn test_host_state_with_wasi_custom() {
        let state = HostState::with_wasi(|builder| {
            builder.arg("test").env("KEY", "VALUE");
            builder
        });
        assert!(state.is_ok());
    }

    #[test]
    fn test_container_state_transitions() {
        let created = ContainerState::Created;
        let running = ContainerState::Running;
        let stopped = ContainerState::Stopped;
        let error = ContainerState::Error("trap".to_string());

        assert_eq!(created, ContainerState::Created);
        assert_eq!(running, ContainerState::Running);
        assert_eq!(stopped, ContainerState::Stopped);
        assert!(matches!(error, ContainerState::Error(msg) if msg == "trap"));
    }

    #[test]
    fn test_container_state_equality() {
        assert_eq!(ContainerState::Created, ContainerState::Created);
        assert_ne!(ContainerState::Created, ContainerState::Running);
        assert_ne!(ContainerState::Running, ContainerState::Stopped);
        assert_ne!(
            ContainerState::Error("a".into()),
            ContainerState::Error("b".into())
        );
    }

    #[test]
    fn test_container_state_clone_debug() {
        let state = ContainerState::Error("oom".to_string());
        let cloned = state.clone();
        assert_eq!(state, cloned);
        let debug = format!("{:?}", state);
        assert!(debug.contains("oom"));
    }

    #[test]
    #[cfg(feature = "dynamic")]
    fn test_call_guest_raw_desc_rejects_invalid_payload() {
        use crate::Image;
        let wasm = bytes::Bytes::from_static(b"\x00asm\x01\x00\x00\x00");
        let img = match Image::new(wasm) {
            Ok(img) => img,
            Err(_) => return,
        };
        let mut container = Container::builder(img)
            .with_guest_initializer(|_ctx| Ok(GuestInstance::new(())))
            .build()
            .expect("build should succeed");

        let sensitive = r#"("SECRET_API_KEY_12345",)"#;
        let result = container.call_guest_raw_desc("test_fn", sensitive);
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            !err_msg.contains("SECRET_API_KEY_12345"),
            "Error message should not contain the payload, but got: {}",
            err_msg
        );
    }
}