whisker-runtime 0.19.0

Host-independent Whisker runtime: reactivity, retained elements, layout, and frames.
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
//! Host-independent native-module dispatch.
//!
//! Core owns the public module API and the listener lifecycle. A Host installs
//! a [`ModuleHost`] while it drives application work. Native Hosts can adapt
//! this interface to FFI, while Rust Hosts can provide ordinary closures.

use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::{Rc, Weak};
use std::sync::{Arc, Mutex};

use whisker_value::WhiskerValue;

/// One-shot completion passed to a Host module invocation.
pub type ModuleResult = Box<dyn FnOnce(WhiskerValue) + Send + 'static>;
type InvokeCallback = dyn Fn(&str, &str, &[WhiskerValue], bool, ModuleResult) -> bool;
type ObserveCallback = dyn Fn(&str, &str, bool);
type EventCallback = Rc<dyn Fn(WhiskerValue)>;

struct Listener {
    module: String,
    event: String,
    callback: EventCallback,
}

/// Host implementation for function-shaped native modules.
///
/// The invocation callback returns whether the Host accepted the call and
/// completes it exactly once through `result`. Synchronous calls must complete
/// before returning. `observe` receives first-listener and last-listener
/// transitions for each `(module, event)` pair.
pub struct ModuleHost {
    invoke: Rc<InvokeCallback>,
    observe: Rc<ObserveCallback>,
    next_listener: Cell<i32>,
    listeners: RefCell<HashMap<i32, Listener>>,
}

impl ModuleHost {
    /// Creates a Host binding from platform-neutral callbacks.
    pub fn new(
        invoke: impl Fn(&str, &str, &[WhiskerValue], bool, ModuleResult) -> bool + 'static,
        observe: impl Fn(&str, &str, bool) + 'static,
    ) -> Rc<Self> {
        Rc::new(Self {
            invoke: Rc::new(invoke),
            observe: Rc::new(observe),
            next_listener: Cell::new(1),
            listeners: RefCell::new(HashMap::new()),
        })
    }

    fn dispatch(
        &self,
        module: &str,
        method: &str,
        args: &[WhiskerValue],
        is_async: bool,
        result: ModuleResult,
    ) -> bool {
        (self.invoke)(module, method, args, is_async, result)
    }

    fn add_listener<F>(
        self: &Rc<Self>,
        module: &str,
        event: &str,
        callback: F,
    ) -> ModuleSubscription
    where
        F: Fn(WhiskerValue) + 'static,
    {
        let id = self.next_listener.get();
        self.next_listener.set(id.saturating_add(1));
        let cleanup = ModuleSubscription {
            id,
            host: Rc::downgrade(self),
            error: None,
        };
        let scoped = crate::lifetime::Scoped::new((callback, cleanup));
        let callback = move |value| {
            scoped.with(|(callback, _)| callback(value));
        };
        let first = {
            let mut listeners = self.listeners.borrow_mut();
            let first = !listeners
                .values()
                .any(|listener| listener.module == module && listener.event == event);
            listeners.insert(
                id,
                Listener {
                    module: module.to_owned(),
                    event: event.to_owned(),
                    callback: Rc::new(callback),
                },
            );
            first
        };
        if first {
            (self.observe)(module, event, true);
        }
        ModuleSubscription {
            id,
            host: Rc::downgrade(self),
            error: None,
        }
    }

    fn remove_listener(&self, id: i32) {
        let removed = self.listeners.borrow_mut().remove(&id);
        let Some(removed) = removed else {
            return;
        };
        let last =
            !self.listeners.borrow().values().any(|listener| {
                listener.module == removed.module && listener.event == removed.event
            });
        if last {
            (self.observe)(&removed.module, &removed.event, false);
        }
        drop(removed);
    }

    /// Delivers a Host event to matching Rust subscriptions.
    pub fn dispatch_event(&self, module: &str, event: &str, payload: WhiskerValue) -> bool {
        let callbacks: Vec<_> = self
            .listeners
            .borrow()
            .iter()
            .filter(|(_, listener)| listener.module == module && listener.event == event)
            .map(|(id, listener)| (*id, Rc::clone(&listener.callback)))
            .collect();
        for (id, callback) in &callbacks {
            if self.listeners.borrow().contains_key(id) {
                callback(payload.clone());
            }
        }
        !callbacks.is_empty()
    }
}

thread_local! {
    static CURRENT_HOST: RefCell<Option<Rc<ModuleHost>>> = const { RefCell::new(None) };
}

struct BindingGuard(Option<Rc<ModuleHost>>);

impl Drop for BindingGuard {
    fn drop(&mut self) {
        let previous = self.0.take();
        CURRENT_HOST.with(|slot| *slot.borrow_mut() = previous);
    }
}

/// Runs application work with one Host's module binding installed.
pub fn with_module_host<T>(host: &Rc<ModuleHost>, work: impl FnOnce() -> T) -> T {
    let previous = CURRENT_HOST.with(|slot| slot.borrow_mut().replace(Rc::clone(host)));
    let _guard = BindingGuard(previous);
    work()
}

fn current_host() -> Option<Rc<ModuleHost>> {
    CURRENT_HOST.with(|slot| slot.borrow().clone())
}

const UNAVAILABLE: &str = "native module Host binding is not active";

/// Calls one Host module function synchronously.
pub fn invoke(name: &str, method: &str, args: Vec<WhiskerValue>) -> WhiskerValue {
    let Some(host) = current_host() else {
        return WhiskerValue::Error(format!("{UNAVAILABLE}: {name}.{method}"));
    };
    let result = Arc::new(Mutex::new(None));
    let callback_result = Arc::clone(&result);
    let accepted = host.dispatch(
        name,
        method,
        &args,
        false,
        Box::new(move |value| {
            *callback_result
                .lock()
                .unwrap_or_else(|error| error.into_inner()) = Some(value);
        }),
    );
    if !accepted {
        return WhiskerValue::Error(format!("Host refused module call: {name}.{method}"));
    }
    result
        .lock()
        .unwrap_or_else(|error| error.into_inner())
        .take()
        .unwrap_or_else(|| {
            WhiskerValue::Error(format!(
                "Host did not synchronously resolve: {name}.{method}"
            ))
        })
}

/// Calls one Host module function asynchronously.
pub async fn invoke_async(name: &str, method: &str, args: Vec<WhiskerValue>) -> WhiskerValue {
    let Some(host) = current_host() else {
        return WhiskerValue::Error(format!("{UNAVAILABLE}: {name}.{method}"));
    };
    let (sender, receiver) = futures_channel::oneshot::channel();
    let accepted = host.dispatch(
        name,
        method,
        &args,
        true,
        Box::new(move |value| {
            let _ = sender.send(value);
        }),
    );
    if !accepted {
        return WhiskerValue::Error(format!("Host refused async module call: {name}.{method}"));
    }
    receiver
        .await
        .unwrap_or_else(|_| WhiskerValue::Error("async module callback was dropped".into()))
}

/// Name-bound handle for one native module.
#[derive(Debug, Clone)]
pub struct PlatformModule {
    name: String,
}

impl PlatformModule {
    /// Creates a module handle from its package-qualified Host name.
    pub fn named(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }

    /// Returns the package-qualified Host name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Calls a synchronous module function.
    pub fn invoke(&self, function: &str, args: Vec<WhiskerValue>) -> WhiskerValue {
        invoke(&self.name, function, args)
    }

    /// Calls an asynchronous module function.
    pub async fn invoke_async(&self, function: &str, args: Vec<WhiskerValue>) -> WhiskerValue {
        invoke_async(&self.name, function, args).await
    }

    /// Subscribes to one module event.
    pub fn on_event<F>(&self, event: &str, callback: F) -> ModuleSubscription
    where
        F: Fn(WhiskerValue) + 'static,
    {
        let Some(host) = current_host() else {
            return ModuleSubscription::failed(format!("{UNAVAILABLE}: {}.{event}", self.name));
        };
        host.add_listener(&self.name, event, callback)
    }
}

/// Retains an event subscription until this handle drops or its registering Owner is disposed.
pub struct ModuleSubscription {
    id: i32,
    host: Weak<ModuleHost>,
    error: Option<String>,
}

impl ModuleSubscription {
    fn failed(error: String) -> Self {
        Self {
            id: 0,
            host: Weak::new(),
            error: Some(error),
        }
    }

    /// Returns the binding error when no Host was installed.
    pub fn error(&self) -> Option<&str> {
        self.error.as_deref()
    }

    /// Returns the process-local listener identifier.
    pub fn id(&self) -> i32 {
        self.id
    }
}

impl Drop for ModuleSubscription {
    fn drop(&mut self) {
        if let Some(host) = self.host.upgrade() {
            host.remove_listener(self.id);
        }
    }
}

/// Promise handed to a Rust Host `AsyncFunction` implementation.
///
/// The first settlement wins. Dropping an unsettled promise completes the
/// invocation with an error so the Rust caller cannot wait forever.
pub struct ModulePromise {
    result: Option<ModuleResult>,
}

impl ModulePromise {
    fn new(result: ModuleResult) -> Self {
        Self {
            result: Some(result),
        }
    }

    /// Completes the invocation with one transferable value.
    pub fn resolve(mut self, value: WhiskerValue) {
        if let Some(result) = self.result.take() {
            result(value);
        }
    }

    /// Completes the invocation with a Host error.
    pub fn reject(self, message: impl Into<String>) {
        self.resolve(WhiskerValue::Error(message.into()));
    }
}

impl Drop for ModulePromise {
    fn drop(&mut self) {
        if let Some(result) = self.result.take() {
            result(WhiskerValue::Error(
                "Host AsyncFunction dropped its promise without settling".into(),
            ));
        }
    }
}

/// Event channel available to Rust Host module handlers.
type ModuleEventSink = Rc<dyn Fn(&str, &str, WhiskerValue) -> bool>;

#[derive(Clone)]
pub struct ModuleEventEmitter {
    module: String,
    emit: ModuleEventSink,
}

impl ModuleEventEmitter {
    /// Enqueues one declared service event for delivery on the next runtime
    /// drive. Returns `false` when the event was not declared by the module.
    pub fn emit(&self, event: &str, payload: WhiskerValue) -> bool {
        if !payload.is_data() {
            return false;
        }
        (self.emit)(&self.module, event, payload)
    }
}

type HostFunction = Rc<dyn Fn(&[WhiskerValue], &ModuleEventEmitter) -> WhiskerValue>;
type HostAsyncFunction = Rc<dyn Fn(&[WhiskerValue], ModulePromise, &ModuleEventEmitter)>;
type ObserverHook = Rc<dyn Fn(&ModuleEventEmitter)>;

/// Service portion shared by the Desktop and Web `ModuleDefinition` APIs.
///
/// Element factories stay in their target crates. This value contains only
/// the portable `Name`, `Function`, `AsyncFunction`, event, and observer
/// declarations used by Rust Hosts.
#[derive(Clone, Default)]
pub struct RustModuleDefinition {
    name: Option<String>,
    functions: HashMap<String, HostFunction>,
    async_functions: HashMap<String, HostAsyncFunction>,
    events: std::collections::HashSet<String>,
    on_start: HashMap<String, ObserverHook>,
    on_stop: HashMap<String, ObserverHook>,
}

impl std::fmt::Debug for RustModuleDefinition {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("RustModuleDefinition")
            .field("name", &self.name)
            .field("functions", &self.functions.keys())
            .field("async_functions", &self.async_functions.keys())
            .field("events", &self.events)
            .finish_non_exhaustive()
    }
}

impl RustModuleDefinition {
    /// Declares the package-qualified service module name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        let name = name.into();
        assert!(self.name.replace(name).is_none(), "duplicate module Name");
        self
    }

    /// Declares one synchronous service function.
    pub fn function(
        mut self,
        name: impl Into<String>,
        handler: impl Fn(&[WhiskerValue], &ModuleEventEmitter) -> WhiskerValue + 'static,
    ) -> Self {
        let name = name.into();
        assert!(!name.trim().is_empty(), "module Function name is empty");
        assert!(
            self.functions
                .insert(name.clone(), Rc::new(handler))
                .is_none(),
            "duplicate module Function {name}"
        );
        self
    }

    /// Declares one deferred service function.
    pub fn async_function(
        mut self,
        name: impl Into<String>,
        handler: impl Fn(&[WhiskerValue], ModulePromise, &ModuleEventEmitter) + 'static,
    ) -> Self {
        let name = name.into();
        assert!(
            !name.trim().is_empty(),
            "module AsyncFunction name is empty"
        );
        assert!(
            self.async_functions
                .insert(name.clone(), Rc::new(handler))
                .is_none(),
            "duplicate module AsyncFunction {name}"
        );
        self
    }

    /// Declares one service-scoped event.
    pub fn event(mut self, name: impl Into<String>) -> Self {
        let name = name.into();
        assert!(!name.trim().is_empty(), "module Event name is empty");
        assert!(
            self.events.insert(name.clone()),
            "duplicate module Event {name}"
        );
        self
    }

    /// Declares the first-subscriber hook for one event.
    pub fn on_start_observing(
        mut self,
        event: impl Into<String>,
        hook: impl Fn(&ModuleEventEmitter) + 'static,
    ) -> Self {
        let event = event.into();
        assert!(
            self.on_start.insert(event.clone(), Rc::new(hook)).is_none(),
            "duplicate OnStartObserving for {event}"
        );
        self
    }

    /// Declares the last-subscriber hook for one event.
    pub fn on_stop_observing(
        mut self,
        event: impl Into<String>,
        hook: impl Fn(&ModuleEventEmitter) + 'static,
    ) -> Self {
        let event = event.into();
        assert!(
            self.on_stop.insert(event.clone(), Rc::new(hook)).is_none(),
            "duplicate OnStopObserving for {event}"
        );
        self
    }

    /// Returns the required module identity.
    pub fn module_name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    fn validate(&self) -> Result<(), String> {
        let name = self
            .name
            .as_deref()
            .ok_or_else(|| "ModuleDefinition requires exactly one Name".to_string())?;
        if name.trim().is_empty() {
            return Err("ModuleDefinition Name is empty".into());
        }
        if let Some(duplicate) = self
            .functions
            .keys()
            .find(|function| self.async_functions.contains_key(*function))
        {
            return Err(format!(
                "Function and AsyncFunction both declare `{duplicate}` on `{name}`"
            ));
        }
        for event in self.on_start.keys().chain(self.on_stop.keys()) {
            if !self.events.contains(event) {
                return Err(format!(
                    "observer hook references undeclared event `{event}` on `{name}`"
                ));
            }
        }
        Ok(())
    }
}

thread_local! {
    static LINKED_RUST_MODULES: RefCell<Vec<RustModuleDefinition>> = const { RefCell::new(Vec::new()) };
}

/// Installs Rust service modules for native Hosts created later on this thread.
pub fn link_rust_modules(definitions: impl IntoIterator<Item = RustModuleDefinition>) {
    LINKED_RUST_MODULES.with(|linked| linked.borrow_mut().extend(definitions));
}

/// Rust service modules installed with [`link_rust_modules`] on this thread.
pub fn linked_rust_modules() -> Vec<RustModuleDefinition> {
    LINKED_RUST_MODULES.with(|linked| linked.borrow().clone())
}

#[derive(Clone)]
struct PendingModuleEvent {
    module: String,
    event: String,
    payload: WhiskerValue,
}

struct RustModuleRuntimeInner {
    definitions: HashMap<String, RustModuleDefinition>,
    pending: RefCell<Vec<PendingModuleEvent>>,
    wake: Rc<dyn Fn()>,
}

/// Bound service-module registry used by direct Rust Hosts.
pub struct RustModuleRuntime {
    inner: Rc<RustModuleRuntimeInner>,
    host: Rc<ModuleHost>,
}

impl RustModuleRuntime {
    /// Validates module declarations and creates the runtime binding.
    pub fn new(
        definitions: impl IntoIterator<Item = RustModuleDefinition>,
        wake: impl Fn() + 'static,
    ) -> Result<Self, String> {
        Self::build(definitions, wake, None)
    }

    /// Like [`Self::new`], but forwards modules it does not define to `fallback`.
    pub fn with_fallback(
        definitions: impl IntoIterator<Item = RustModuleDefinition>,
        wake: impl Fn() + 'static,
        fallback: Rc<ModuleHost>,
    ) -> Result<Self, String> {
        Self::build(definitions, wake, Some(fallback))
    }

    fn build(
        definitions: impl IntoIterator<Item = RustModuleDefinition>,
        wake: impl Fn() + 'static,
        fallback: Option<Rc<ModuleHost>>,
    ) -> Result<Self, String> {
        let mut by_name = HashMap::new();
        for definition in definitions {
            definition.validate()?;
            let name = definition
                .module_name()
                .expect("validated module has a Name")
                .to_owned();
            if by_name.insert(name.clone(), definition).is_some() {
                return Err(format!("duplicate Host module `{name}`"));
            }
        }
        let inner = Rc::new(RustModuleRuntimeInner {
            definitions: by_name,
            pending: RefCell::new(Vec::new()),
            wake: Rc::new(wake),
        });
        let invoke_inner = Rc::downgrade(&inner);
        let observe_inner = Rc::downgrade(&inner);
        let invoke_fallback = fallback.clone();
        let host = ModuleHost::new(
            move |module, method, args, is_async, result| {
                let Some(inner) = invoke_inner.upgrade() else {
                    return false;
                };
                let Some(definition) = inner.definitions.get(module) else {
                    return invoke_fallback
                        .as_ref()
                        .is_some_and(|host| host.dispatch(module, method, args, is_async, result));
                };
                let emitter = inner.emitter(module);
                if is_async {
                    let Some(function) = definition.async_functions.get(method) else {
                        return false;
                    };
                    function(args, ModulePromise::new(result), &emitter);
                    true
                } else {
                    let Some(function) = definition.functions.get(method) else {
                        return false;
                    };
                    result(function(args, &emitter));
                    true
                }
            },
            move |module, event, observing| {
                let Some(inner) = observe_inner.upgrade() else {
                    return;
                };
                let Some(definition) = inner.definitions.get(module) else {
                    if let Some(host) = &fallback {
                        (host.observe)(module, event, observing);
                    }
                    return;
                };
                let hook = if observing {
                    definition.on_start.get(event)
                } else {
                    definition.on_stop.get(event)
                };
                if let Some(hook) = hook {
                    hook(&inner.emitter(module));
                }
            },
        );
        Ok(Self { inner, host })
    }

    /// Runs application/runtime work with this registry installed.
    pub fn with_host<T>(&self, work: impl FnOnce() -> T) -> T {
        with_module_host(&self.host, work)
    }

    /// Host binding that answers this registry's modules.
    pub fn host(&self) -> &Rc<ModuleHost> {
        &self.host
    }

    /// Delivers queued Host events through the owning runtime's ordinary event
    /// transaction rather than re-entering application code from the
    /// originating Host callback.
    pub fn dispatch_pending_events(
        &self,
        runtime: &crate::RuntimeInstance,
    ) -> Result<usize, crate::RuntimeEventError> {
        let pending = std::mem::take(&mut *self.inner.pending.borrow_mut());
        let count = pending.len();
        for event in pending {
            runtime.dispatch_module_event(
                &self.host,
                &event.module,
                &event.event,
                event.payload,
            )?;
        }
        Ok(count)
    }
}

impl RustModuleRuntimeInner {
    fn emitter(self: &Rc<Self>, module: &str) -> ModuleEventEmitter {
        let weak = Rc::downgrade(self);
        ModuleEventEmitter {
            module: module.to_owned(),
            emit: Rc::new(move |module, event, payload| {
                let Some(inner) = weak.upgrade() else {
                    return false;
                };
                let declared = inner
                    .definitions
                    .get(module)
                    .is_some_and(|definition| definition.events.contains(event));
                if declared {
                    inner.pending.borrow_mut().push(PendingModuleEvent {
                        module: module.to_owned(),
                        event: event.to_owned(),
                        payload,
                    });
                    (inner.wake)();
                }
                declared
            }),
        }
    }
}

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

    #[test]
    fn direct_rust_host_drives_the_same_module_api() {
        let calls = Rc::new(Cell::new(0));
        let calls_for_host = Rc::clone(&calls);
        let host = ModuleHost::new(
            move |module, method, args, _, result| {
                assert_eq!((module, method), ("demo", "echo"));
                calls_for_host.set(calls_for_host.get() + 1);
                result(args[0].clone());
                true
            },
            |_, _, _| {},
        );
        let value = with_module_host(&host, || {
            PlatformModule::named("demo").invoke("echo", vec![WhiskerValue::Int(7)])
        });
        assert_eq!(value, WhiskerValue::Int(7));
        assert_eq!(calls.get(), 1);
    }

    #[test]
    fn unknown_modules_reach_the_fallback_host() {
        let observed = Rc::new(RefCell::new(Vec::new()));
        let fallback = ModuleHost::new(
            |module, _, _, _, result| {
                result(WhiskerValue::String(module.into()));
                true
            },
            {
                let observed = Rc::clone(&observed);
                move |module, event, observing| {
                    observed
                        .borrow_mut()
                        .push((module.to_owned(), event.to_owned(), observing));
                }
            },
        );
        let rust = RustModuleDefinition::default()
            .name("demo:Rust")
            .function("ping", |_, _| WhiskerValue::Bool(true));
        let runtime = RustModuleRuntime::with_fallback([rust], || {}, fallback).unwrap();
        runtime.with_host(|| {
            assert_eq!(
                PlatformModule::named("demo:Rust").invoke("ping", vec![]),
                WhiskerValue::Bool(true)
            );
            assert_eq!(
                PlatformModule::named("demo:Native").invoke("ping", vec![]),
                WhiskerValue::String("demo:Native".into())
            );
            drop(PlatformModule::named("demo:Native").on_event("ready", |_| {}));
        });
        assert_eq!(
            *observed.borrow(),
            [
                ("demo:Native".to_owned(), "ready".to_owned(), true),
                ("demo:Native".to_owned(), "ready".to_owned(), false),
            ]
        );
    }

    #[test]
    fn rust_host_definition_supports_functions_events_and_observer_lifecycle() {
        let starts = Rc::new(Cell::new(0));
        let stops = Rc::new(Cell::new(0));
        let wakes = Rc::new(Cell::new(0));
        let definition = RustModuleDefinition::default()
            .name("demo:Echo")
            .function("echo", |args, _| args[0].clone())
            .async_function("echoAsync", |args, promise, _| {
                promise.resolve(args[0].clone());
            })
            .event("ready")
            .on_start_observing("ready", {
                let starts = Rc::clone(&starts);
                move |events| {
                    starts.set(starts.get() + 1);
                    assert!(events.emit("ready", WhiskerValue::String("now".into())));
                }
            })
            .on_stop_observing("ready", {
                let stops = Rc::clone(&stops);
                move |_| stops.set(stops.get() + 1)
            });
        let runtime = RustModuleRuntime::new([definition], {
            let wakes = Rc::clone(&wakes);
            move || wakes.set(wakes.get() + 1)
        })
        .unwrap();

        runtime.with_host(|| {
            assert_eq!(
                PlatformModule::named("demo:Echo").invoke("echo", vec![WhiskerValue::Int(9)]),
                WhiskerValue::Int(9)
            );
        });

        let payload = Rc::new(RefCell::new(None));
        let subscription = Rc::new(RefCell::new(None));
        let surface = crate::SurfaceRuntime::new(
            whisker_protocol::SurfaceId::new(1).unwrap(),
            whisker_style::StyleEnvironment::new(100.0, 100.0, 1.0, 14.0),
        );
        let mut instance =
            crate::RuntimeInstance::new(surface, crate::RuntimeWakeHandle::new(|| {}));
        runtime.with_host(|| {
            instance
                .mount({
                    let payload = Rc::clone(&payload);
                    let subscription = Rc::clone(&subscription);
                    move || {
                        *subscription.borrow_mut() = Some(
                            PlatformModule::named("demo:Echo").on_event("ready", move |value| {
                                *payload.borrow_mut() = Some(value);
                            }),
                        );
                        crate::view::create_element(crate::ElementTag::View)
                    }
                })
                .unwrap();
        });
        assert_eq!(starts.get(), 1);
        assert_eq!(wakes.get(), 1);
        assert_eq!(runtime.dispatch_pending_events(&instance).unwrap(), 1);
        assert_eq!(*payload.borrow(), Some(WhiskerValue::String("now".into())));
        drop(subscription.borrow_mut().take());
        assert_eq!(stops.get(), 1);
        runtime.with_host(|| instance.unmount().unwrap());
    }

    #[test]
    fn rust_host_definition_requires_name_and_declared_observer_events() {
        assert!(
            RustModuleRuntime::new([RustModuleDefinition::default()], || {})
                .err()
                .expect("definition without Name must fail")
                .contains("Name")
        );
        let undeclared = RustModuleDefinition::default()
            .name("demo:Bad")
            .on_start_observing("missing", |_| {});
        assert!(
            RustModuleRuntime::new([undeclared], || {})
                .err()
                .expect("observer for undeclared event must fail")
                .contains("undeclared event")
        );

        let duplicate_function = RustModuleDefinition::default()
            .name("demo:Bad")
            .function("load", |_, _| WhiskerValue::Null)
            .async_function("load", |_, promise, _| promise.resolve(WhiskerValue::Null));
        assert!(
            RustModuleRuntime::new([duplicate_function], || {})
                .err()
                .expect("sync and async members must share one namespace")
                .contains("both declare")
        );
    }
}