Skip to main content

whisker_runtime/
module.rs

1//! Host-independent native-module dispatch.
2//!
3//! Core owns the public module API and the listener lifecycle. A Host installs
4//! a [`ModuleHost`] while it drives application work. Native Hosts can adapt
5//! this interface to FFI, while Rust Hosts can provide ordinary closures.
6
7use std::cell::Cell;
8use std::cell::RefCell;
9use std::collections::HashMap;
10use std::rc::{Rc, Weak};
11use std::sync::{Arc, Mutex};
12
13use whisker_value::WhiskerValue;
14
15/// One-shot completion passed to a Host module invocation.
16pub type ModuleResult = Box<dyn FnOnce(WhiskerValue) + Send + 'static>;
17type InvokeCallback = dyn Fn(&str, &str, &[WhiskerValue], bool, ModuleResult) -> bool;
18type ObserveCallback = dyn Fn(&str, &str, bool);
19type EventCallback = Rc<dyn Fn(WhiskerValue)>;
20
21struct Listener {
22    module: String,
23    event: String,
24    callback: EventCallback,
25}
26
27/// Host implementation for function-shaped native modules.
28///
29/// The invocation callback returns whether the Host accepted the call and
30/// completes it exactly once through `result`. Synchronous calls must complete
31/// before returning. `observe` receives first-listener and last-listener
32/// transitions for each `(module, event)` pair.
33pub struct ModuleHost {
34    invoke: Rc<InvokeCallback>,
35    observe: Rc<ObserveCallback>,
36    next_listener: Cell<i32>,
37    listeners: RefCell<HashMap<i32, Listener>>,
38}
39
40impl ModuleHost {
41    /// Creates a Host binding from platform-neutral callbacks.
42    pub fn new(
43        invoke: impl Fn(&str, &str, &[WhiskerValue], bool, ModuleResult) -> bool + 'static,
44        observe: impl Fn(&str, &str, bool) + 'static,
45    ) -> Rc<Self> {
46        Rc::new(Self {
47            invoke: Rc::new(invoke),
48            observe: Rc::new(observe),
49            next_listener: Cell::new(1),
50            listeners: RefCell::new(HashMap::new()),
51        })
52    }
53
54    fn dispatch(
55        &self,
56        module: &str,
57        method: &str,
58        args: &[WhiskerValue],
59        is_async: bool,
60        result: ModuleResult,
61    ) -> bool {
62        (self.invoke)(module, method, args, is_async, result)
63    }
64
65    fn add_listener<F>(
66        self: &Rc<Self>,
67        module: &str,
68        event: &str,
69        callback: F,
70    ) -> ModuleSubscription
71    where
72        F: Fn(WhiskerValue) + 'static,
73    {
74        let id = self.next_listener.get();
75        self.next_listener.set(id.saturating_add(1));
76        let cleanup = ModuleSubscription {
77            id,
78            host: Rc::downgrade(self),
79            error: None,
80        };
81        let scoped = crate::lifetime::Scoped::new((callback, cleanup));
82        let callback = move |value| {
83            scoped.with(|(callback, _)| callback(value));
84        };
85        let first = {
86            let mut listeners = self.listeners.borrow_mut();
87            let first = !listeners
88                .values()
89                .any(|listener| listener.module == module && listener.event == event);
90            listeners.insert(
91                id,
92                Listener {
93                    module: module.to_owned(),
94                    event: event.to_owned(),
95                    callback: Rc::new(callback),
96                },
97            );
98            first
99        };
100        if first {
101            (self.observe)(module, event, true);
102        }
103        ModuleSubscription {
104            id,
105            host: Rc::downgrade(self),
106            error: None,
107        }
108    }
109
110    fn remove_listener(&self, id: i32) {
111        let removed = self.listeners.borrow_mut().remove(&id);
112        let Some(removed) = removed else {
113            return;
114        };
115        let last =
116            !self.listeners.borrow().values().any(|listener| {
117                listener.module == removed.module && listener.event == removed.event
118            });
119        if last {
120            (self.observe)(&removed.module, &removed.event, false);
121        }
122        drop(removed);
123    }
124
125    /// Delivers a Host event to matching Rust subscriptions.
126    pub fn dispatch_event(&self, module: &str, event: &str, payload: WhiskerValue) -> bool {
127        let callbacks: Vec<_> = self
128            .listeners
129            .borrow()
130            .iter()
131            .filter(|(_, listener)| listener.module == module && listener.event == event)
132            .map(|(id, listener)| (*id, Rc::clone(&listener.callback)))
133            .collect();
134        for (id, callback) in &callbacks {
135            if self.listeners.borrow().contains_key(id) {
136                callback(payload.clone());
137            }
138        }
139        !callbacks.is_empty()
140    }
141}
142
143thread_local! {
144    static CURRENT_HOST: RefCell<Option<Rc<ModuleHost>>> = const { RefCell::new(None) };
145}
146
147struct BindingGuard(Option<Rc<ModuleHost>>);
148
149impl Drop for BindingGuard {
150    fn drop(&mut self) {
151        let previous = self.0.take();
152        CURRENT_HOST.with(|slot| *slot.borrow_mut() = previous);
153    }
154}
155
156/// Runs application work with one Host's module binding installed.
157pub fn with_module_host<T>(host: &Rc<ModuleHost>, work: impl FnOnce() -> T) -> T {
158    let previous = CURRENT_HOST.with(|slot| slot.borrow_mut().replace(Rc::clone(host)));
159    let _guard = BindingGuard(previous);
160    work()
161}
162
163fn current_host() -> Option<Rc<ModuleHost>> {
164    CURRENT_HOST.with(|slot| slot.borrow().clone())
165}
166
167const UNAVAILABLE: &str = "native module Host binding is not active";
168
169/// Calls one Host module function synchronously.
170pub fn invoke(name: &str, method: &str, args: Vec<WhiskerValue>) -> WhiskerValue {
171    let Some(host) = current_host() else {
172        return WhiskerValue::Error(format!("{UNAVAILABLE}: {name}.{method}"));
173    };
174    let result = Arc::new(Mutex::new(None));
175    let callback_result = Arc::clone(&result);
176    let accepted = host.dispatch(
177        name,
178        method,
179        &args,
180        false,
181        Box::new(move |value| {
182            *callback_result
183                .lock()
184                .unwrap_or_else(|error| error.into_inner()) = Some(value);
185        }),
186    );
187    if !accepted {
188        return WhiskerValue::Error(format!("Host refused module call: {name}.{method}"));
189    }
190    result
191        .lock()
192        .unwrap_or_else(|error| error.into_inner())
193        .take()
194        .unwrap_or_else(|| {
195            WhiskerValue::Error(format!(
196                "Host did not synchronously resolve: {name}.{method}"
197            ))
198        })
199}
200
201/// Calls one Host module function asynchronously.
202pub async fn invoke_async(name: &str, method: &str, args: Vec<WhiskerValue>) -> WhiskerValue {
203    let Some(host) = current_host() else {
204        return WhiskerValue::Error(format!("{UNAVAILABLE}: {name}.{method}"));
205    };
206    let (sender, receiver) = futures_channel::oneshot::channel();
207    let accepted = host.dispatch(
208        name,
209        method,
210        &args,
211        true,
212        Box::new(move |value| {
213            let _ = sender.send(value);
214        }),
215    );
216    if !accepted {
217        return WhiskerValue::Error(format!("Host refused async module call: {name}.{method}"));
218    }
219    receiver
220        .await
221        .unwrap_or_else(|_| WhiskerValue::Error("async module callback was dropped".into()))
222}
223
224/// Name-bound handle for one native module.
225#[derive(Debug, Clone)]
226pub struct PlatformModule {
227    name: String,
228}
229
230impl PlatformModule {
231    /// Creates a module handle from its package-qualified Host name.
232    pub fn named(name: impl Into<String>) -> Self {
233        Self { name: name.into() }
234    }
235
236    /// Returns the package-qualified Host name.
237    pub fn name(&self) -> &str {
238        &self.name
239    }
240
241    /// Calls a synchronous module function.
242    pub fn invoke(&self, function: &str, args: Vec<WhiskerValue>) -> WhiskerValue {
243        invoke(&self.name, function, args)
244    }
245
246    /// Calls an asynchronous module function.
247    pub async fn invoke_async(&self, function: &str, args: Vec<WhiskerValue>) -> WhiskerValue {
248        invoke_async(&self.name, function, args).await
249    }
250
251    /// Subscribes to one module event.
252    pub fn on_event<F>(&self, event: &str, callback: F) -> ModuleSubscription
253    where
254        F: Fn(WhiskerValue) + 'static,
255    {
256        let Some(host) = current_host() else {
257            return ModuleSubscription::failed(format!("{UNAVAILABLE}: {}.{event}", self.name));
258        };
259        host.add_listener(&self.name, event, callback)
260    }
261}
262
263/// Retains an event subscription until this handle drops or its registering Owner is disposed.
264pub struct ModuleSubscription {
265    id: i32,
266    host: Weak<ModuleHost>,
267    error: Option<String>,
268}
269
270impl ModuleSubscription {
271    fn failed(error: String) -> Self {
272        Self {
273            id: 0,
274            host: Weak::new(),
275            error: Some(error),
276        }
277    }
278
279    /// Returns the binding error when no Host was installed.
280    pub fn error(&self) -> Option<&str> {
281        self.error.as_deref()
282    }
283
284    /// Returns the process-local listener identifier.
285    pub fn id(&self) -> i32 {
286        self.id
287    }
288}
289
290impl Drop for ModuleSubscription {
291    fn drop(&mut self) {
292        if let Some(host) = self.host.upgrade() {
293            host.remove_listener(self.id);
294        }
295    }
296}
297
298/// Promise handed to a Rust Host `AsyncFunction` implementation.
299///
300/// The first settlement wins. Dropping an unsettled promise completes the
301/// invocation with an error so the Rust caller cannot wait forever.
302pub struct ModulePromise {
303    result: Option<ModuleResult>,
304}
305
306impl ModulePromise {
307    fn new(result: ModuleResult) -> Self {
308        Self {
309            result: Some(result),
310        }
311    }
312
313    /// Completes the invocation with one transferable value.
314    pub fn resolve(mut self, value: WhiskerValue) {
315        if let Some(result) = self.result.take() {
316            result(value);
317        }
318    }
319
320    /// Completes the invocation with a Host error.
321    pub fn reject(self, message: impl Into<String>) {
322        self.resolve(WhiskerValue::Error(message.into()));
323    }
324}
325
326impl Drop for ModulePromise {
327    fn drop(&mut self) {
328        if let Some(result) = self.result.take() {
329            result(WhiskerValue::Error(
330                "Host AsyncFunction dropped its promise without settling".into(),
331            ));
332        }
333    }
334}
335
336/// Event channel available to Rust Host module handlers.
337type ModuleEventSink = Rc<dyn Fn(&str, &str, WhiskerValue) -> bool>;
338
339#[derive(Clone)]
340pub struct ModuleEventEmitter {
341    module: String,
342    emit: ModuleEventSink,
343}
344
345impl ModuleEventEmitter {
346    /// Enqueues one declared service event for delivery on the next runtime
347    /// drive. Returns `false` when the event was not declared by the module.
348    pub fn emit(&self, event: &str, payload: WhiskerValue) -> bool {
349        if !payload.is_data() {
350            return false;
351        }
352        (self.emit)(&self.module, event, payload)
353    }
354}
355
356type HostFunction = Rc<dyn Fn(&[WhiskerValue], &ModuleEventEmitter) -> WhiskerValue>;
357type HostAsyncFunction = Rc<dyn Fn(&[WhiskerValue], ModulePromise, &ModuleEventEmitter)>;
358type ObserverHook = Rc<dyn Fn(&ModuleEventEmitter)>;
359
360/// Service portion shared by the Desktop and Web `ModuleDefinition` APIs.
361///
362/// Element factories stay in their target crates. This value contains only
363/// the portable `Name`, `Function`, `AsyncFunction`, event, and observer
364/// declarations used by Rust Hosts.
365#[derive(Clone, Default)]
366pub struct RustModuleDefinition {
367    name: Option<String>,
368    functions: HashMap<String, HostFunction>,
369    async_functions: HashMap<String, HostAsyncFunction>,
370    events: std::collections::HashSet<String>,
371    on_start: HashMap<String, ObserverHook>,
372    on_stop: HashMap<String, ObserverHook>,
373}
374
375impl std::fmt::Debug for RustModuleDefinition {
376    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377        formatter
378            .debug_struct("RustModuleDefinition")
379            .field("name", &self.name)
380            .field("functions", &self.functions.keys())
381            .field("async_functions", &self.async_functions.keys())
382            .field("events", &self.events)
383            .finish_non_exhaustive()
384    }
385}
386
387impl RustModuleDefinition {
388    /// Declares the package-qualified service module name.
389    pub fn name(mut self, name: impl Into<String>) -> Self {
390        let name = name.into();
391        assert!(self.name.replace(name).is_none(), "duplicate module Name");
392        self
393    }
394
395    /// Declares one synchronous service function.
396    pub fn function(
397        mut self,
398        name: impl Into<String>,
399        handler: impl Fn(&[WhiskerValue], &ModuleEventEmitter) -> WhiskerValue + 'static,
400    ) -> Self {
401        let name = name.into();
402        assert!(!name.trim().is_empty(), "module Function name is empty");
403        assert!(
404            self.functions
405                .insert(name.clone(), Rc::new(handler))
406                .is_none(),
407            "duplicate module Function {name}"
408        );
409        self
410    }
411
412    /// Declares one deferred service function.
413    pub fn async_function(
414        mut self,
415        name: impl Into<String>,
416        handler: impl Fn(&[WhiskerValue], ModulePromise, &ModuleEventEmitter) + 'static,
417    ) -> Self {
418        let name = name.into();
419        assert!(
420            !name.trim().is_empty(),
421            "module AsyncFunction name is empty"
422        );
423        assert!(
424            self.async_functions
425                .insert(name.clone(), Rc::new(handler))
426                .is_none(),
427            "duplicate module AsyncFunction {name}"
428        );
429        self
430    }
431
432    /// Declares one service-scoped event.
433    pub fn event(mut self, name: impl Into<String>) -> Self {
434        let name = name.into();
435        assert!(!name.trim().is_empty(), "module Event name is empty");
436        assert!(
437            self.events.insert(name.clone()),
438            "duplicate module Event {name}"
439        );
440        self
441    }
442
443    /// Declares the first-subscriber hook for one event.
444    pub fn on_start_observing(
445        mut self,
446        event: impl Into<String>,
447        hook: impl Fn(&ModuleEventEmitter) + 'static,
448    ) -> Self {
449        let event = event.into();
450        assert!(
451            self.on_start.insert(event.clone(), Rc::new(hook)).is_none(),
452            "duplicate OnStartObserving for {event}"
453        );
454        self
455    }
456
457    /// Declares the last-subscriber hook for one event.
458    pub fn on_stop_observing(
459        mut self,
460        event: impl Into<String>,
461        hook: impl Fn(&ModuleEventEmitter) + 'static,
462    ) -> Self {
463        let event = event.into();
464        assert!(
465            self.on_stop.insert(event.clone(), Rc::new(hook)).is_none(),
466            "duplicate OnStopObserving for {event}"
467        );
468        self
469    }
470
471    /// Returns the required module identity.
472    pub fn module_name(&self) -> Option<&str> {
473        self.name.as_deref()
474    }
475
476    fn validate(&self) -> Result<(), String> {
477        let name = self
478            .name
479            .as_deref()
480            .ok_or_else(|| "ModuleDefinition requires exactly one Name".to_string())?;
481        if name.trim().is_empty() {
482            return Err("ModuleDefinition Name is empty".into());
483        }
484        if let Some(duplicate) = self
485            .functions
486            .keys()
487            .find(|function| self.async_functions.contains_key(*function))
488        {
489            return Err(format!(
490                "Function and AsyncFunction both declare `{duplicate}` on `{name}`"
491            ));
492        }
493        for event in self.on_start.keys().chain(self.on_stop.keys()) {
494            if !self.events.contains(event) {
495                return Err(format!(
496                    "observer hook references undeclared event `{event}` on `{name}`"
497                ));
498            }
499        }
500        Ok(())
501    }
502}
503
504thread_local! {
505    static LINKED_RUST_MODULES: RefCell<Vec<RustModuleDefinition>> = const { RefCell::new(Vec::new()) };
506}
507
508/// Installs Rust service modules for native Hosts created later on this thread.
509pub fn link_rust_modules(definitions: impl IntoIterator<Item = RustModuleDefinition>) {
510    LINKED_RUST_MODULES.with(|linked| linked.borrow_mut().extend(definitions));
511}
512
513/// Rust service modules installed with [`link_rust_modules`] on this thread.
514pub fn linked_rust_modules() -> Vec<RustModuleDefinition> {
515    LINKED_RUST_MODULES.with(|linked| linked.borrow().clone())
516}
517
518#[derive(Clone)]
519struct PendingModuleEvent {
520    module: String,
521    event: String,
522    payload: WhiskerValue,
523}
524
525struct RustModuleRuntimeInner {
526    definitions: HashMap<String, RustModuleDefinition>,
527    pending: RefCell<Vec<PendingModuleEvent>>,
528    wake: Rc<dyn Fn()>,
529}
530
531/// Bound service-module registry used by direct Rust Hosts.
532pub struct RustModuleRuntime {
533    inner: Rc<RustModuleRuntimeInner>,
534    host: Rc<ModuleHost>,
535}
536
537impl RustModuleRuntime {
538    /// Validates module declarations and creates the runtime binding.
539    pub fn new(
540        definitions: impl IntoIterator<Item = RustModuleDefinition>,
541        wake: impl Fn() + 'static,
542    ) -> Result<Self, String> {
543        Self::build(definitions, wake, None)
544    }
545
546    /// Like [`Self::new`], but forwards modules it does not define to `fallback`.
547    pub fn with_fallback(
548        definitions: impl IntoIterator<Item = RustModuleDefinition>,
549        wake: impl Fn() + 'static,
550        fallback: Rc<ModuleHost>,
551    ) -> Result<Self, String> {
552        Self::build(definitions, wake, Some(fallback))
553    }
554
555    fn build(
556        definitions: impl IntoIterator<Item = RustModuleDefinition>,
557        wake: impl Fn() + 'static,
558        fallback: Option<Rc<ModuleHost>>,
559    ) -> Result<Self, String> {
560        let mut by_name = HashMap::new();
561        for definition in definitions {
562            definition.validate()?;
563            let name = definition
564                .module_name()
565                .expect("validated module has a Name")
566                .to_owned();
567            if by_name.insert(name.clone(), definition).is_some() {
568                return Err(format!("duplicate Host module `{name}`"));
569            }
570        }
571        let inner = Rc::new(RustModuleRuntimeInner {
572            definitions: by_name,
573            pending: RefCell::new(Vec::new()),
574            wake: Rc::new(wake),
575        });
576        let invoke_inner = Rc::downgrade(&inner);
577        let observe_inner = Rc::downgrade(&inner);
578        let invoke_fallback = fallback.clone();
579        let host = ModuleHost::new(
580            move |module, method, args, is_async, result| {
581                let Some(inner) = invoke_inner.upgrade() else {
582                    return false;
583                };
584                let Some(definition) = inner.definitions.get(module) else {
585                    return invoke_fallback
586                        .as_ref()
587                        .is_some_and(|host| host.dispatch(module, method, args, is_async, result));
588                };
589                let emitter = inner.emitter(module);
590                if is_async {
591                    let Some(function) = definition.async_functions.get(method) else {
592                        return false;
593                    };
594                    function(args, ModulePromise::new(result), &emitter);
595                    true
596                } else {
597                    let Some(function) = definition.functions.get(method) else {
598                        return false;
599                    };
600                    result(function(args, &emitter));
601                    true
602                }
603            },
604            move |module, event, observing| {
605                let Some(inner) = observe_inner.upgrade() else {
606                    return;
607                };
608                let Some(definition) = inner.definitions.get(module) else {
609                    if let Some(host) = &fallback {
610                        (host.observe)(module, event, observing);
611                    }
612                    return;
613                };
614                let hook = if observing {
615                    definition.on_start.get(event)
616                } else {
617                    definition.on_stop.get(event)
618                };
619                if let Some(hook) = hook {
620                    hook(&inner.emitter(module));
621                }
622            },
623        );
624        Ok(Self { inner, host })
625    }
626
627    /// Runs application/runtime work with this registry installed.
628    pub fn with_host<T>(&self, work: impl FnOnce() -> T) -> T {
629        with_module_host(&self.host, work)
630    }
631
632    /// Host binding that answers this registry's modules.
633    pub fn host(&self) -> &Rc<ModuleHost> {
634        &self.host
635    }
636
637    /// Delivers queued Host events through the owning runtime's ordinary event
638    /// transaction rather than re-entering application code from the
639    /// originating Host callback.
640    pub fn dispatch_pending_events(
641        &self,
642        runtime: &crate::RuntimeInstance,
643    ) -> Result<usize, crate::RuntimeEventError> {
644        let pending = std::mem::take(&mut *self.inner.pending.borrow_mut());
645        let count = pending.len();
646        for event in pending {
647            runtime.dispatch_module_event(
648                &self.host,
649                &event.module,
650                &event.event,
651                event.payload,
652            )?;
653        }
654        Ok(count)
655    }
656}
657
658impl RustModuleRuntimeInner {
659    fn emitter(self: &Rc<Self>, module: &str) -> ModuleEventEmitter {
660        let weak = Rc::downgrade(self);
661        ModuleEventEmitter {
662            module: module.to_owned(),
663            emit: Rc::new(move |module, event, payload| {
664                let Some(inner) = weak.upgrade() else {
665                    return false;
666                };
667                let declared = inner
668                    .definitions
669                    .get(module)
670                    .is_some_and(|definition| definition.events.contains(event));
671                if declared {
672                    inner.pending.borrow_mut().push(PendingModuleEvent {
673                        module: module.to_owned(),
674                        event: event.to_owned(),
675                        payload,
676                    });
677                    (inner.wake)();
678                }
679                declared
680            }),
681        }
682    }
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688
689    #[test]
690    fn direct_rust_host_drives_the_same_module_api() {
691        let calls = Rc::new(Cell::new(0));
692        let calls_for_host = Rc::clone(&calls);
693        let host = ModuleHost::new(
694            move |module, method, args, _, result| {
695                assert_eq!((module, method), ("demo", "echo"));
696                calls_for_host.set(calls_for_host.get() + 1);
697                result(args[0].clone());
698                true
699            },
700            |_, _, _| {},
701        );
702        let value = with_module_host(&host, || {
703            PlatformModule::named("demo").invoke("echo", vec![WhiskerValue::Int(7)])
704        });
705        assert_eq!(value, WhiskerValue::Int(7));
706        assert_eq!(calls.get(), 1);
707    }
708
709    #[test]
710    fn unknown_modules_reach_the_fallback_host() {
711        let observed = Rc::new(RefCell::new(Vec::new()));
712        let fallback = ModuleHost::new(
713            |module, _, _, _, result| {
714                result(WhiskerValue::String(module.into()));
715                true
716            },
717            {
718                let observed = Rc::clone(&observed);
719                move |module, event, observing| {
720                    observed
721                        .borrow_mut()
722                        .push((module.to_owned(), event.to_owned(), observing));
723                }
724            },
725        );
726        let rust = RustModuleDefinition::default()
727            .name("demo:Rust")
728            .function("ping", |_, _| WhiskerValue::Bool(true));
729        let runtime = RustModuleRuntime::with_fallback([rust], || {}, fallback).unwrap();
730        runtime.with_host(|| {
731            assert_eq!(
732                PlatformModule::named("demo:Rust").invoke("ping", vec![]),
733                WhiskerValue::Bool(true)
734            );
735            assert_eq!(
736                PlatformModule::named("demo:Native").invoke("ping", vec![]),
737                WhiskerValue::String("demo:Native".into())
738            );
739            drop(PlatformModule::named("demo:Native").on_event("ready", |_| {}));
740        });
741        assert_eq!(
742            *observed.borrow(),
743            [
744                ("demo:Native".to_owned(), "ready".to_owned(), true),
745                ("demo:Native".to_owned(), "ready".to_owned(), false),
746            ]
747        );
748    }
749
750    #[test]
751    fn rust_host_definition_supports_functions_events_and_observer_lifecycle() {
752        let starts = Rc::new(Cell::new(0));
753        let stops = Rc::new(Cell::new(0));
754        let wakes = Rc::new(Cell::new(0));
755        let definition = RustModuleDefinition::default()
756            .name("demo:Echo")
757            .function("echo", |args, _| args[0].clone())
758            .async_function("echoAsync", |args, promise, _| {
759                promise.resolve(args[0].clone());
760            })
761            .event("ready")
762            .on_start_observing("ready", {
763                let starts = Rc::clone(&starts);
764                move |events| {
765                    starts.set(starts.get() + 1);
766                    assert!(events.emit("ready", WhiskerValue::String("now".into())));
767                }
768            })
769            .on_stop_observing("ready", {
770                let stops = Rc::clone(&stops);
771                move |_| stops.set(stops.get() + 1)
772            });
773        let runtime = RustModuleRuntime::new([definition], {
774            let wakes = Rc::clone(&wakes);
775            move || wakes.set(wakes.get() + 1)
776        })
777        .unwrap();
778
779        runtime.with_host(|| {
780            assert_eq!(
781                PlatformModule::named("demo:Echo").invoke("echo", vec![WhiskerValue::Int(9)]),
782                WhiskerValue::Int(9)
783            );
784        });
785
786        let payload = Rc::new(RefCell::new(None));
787        let subscription = Rc::new(RefCell::new(None));
788        let surface = crate::SurfaceRuntime::new(
789            whisker_protocol::SurfaceId::new(1).unwrap(),
790            whisker_style::StyleEnvironment::new(100.0, 100.0, 1.0, 14.0),
791        );
792        let mut instance =
793            crate::RuntimeInstance::new(surface, crate::RuntimeWakeHandle::new(|| {}));
794        runtime.with_host(|| {
795            instance
796                .mount({
797                    let payload = Rc::clone(&payload);
798                    let subscription = Rc::clone(&subscription);
799                    move || {
800                        *subscription.borrow_mut() = Some(
801                            PlatformModule::named("demo:Echo").on_event("ready", move |value| {
802                                *payload.borrow_mut() = Some(value);
803                            }),
804                        );
805                        crate::view::create_element(crate::ElementTag::View)
806                    }
807                })
808                .unwrap();
809        });
810        assert_eq!(starts.get(), 1);
811        assert_eq!(wakes.get(), 1);
812        assert_eq!(runtime.dispatch_pending_events(&instance).unwrap(), 1);
813        assert_eq!(*payload.borrow(), Some(WhiskerValue::String("now".into())));
814        drop(subscription.borrow_mut().take());
815        assert_eq!(stops.get(), 1);
816        runtime.with_host(|| instance.unmount().unwrap());
817    }
818
819    #[test]
820    fn rust_host_definition_requires_name_and_declared_observer_events() {
821        assert!(
822            RustModuleRuntime::new([RustModuleDefinition::default()], || {})
823                .err()
824                .expect("definition without Name must fail")
825                .contains("Name")
826        );
827        let undeclared = RustModuleDefinition::default()
828            .name("demo:Bad")
829            .on_start_observing("missing", |_| {});
830        assert!(
831            RustModuleRuntime::new([undeclared], || {})
832                .err()
833                .expect("observer for undeclared event must fail")
834                .contains("undeclared event")
835        );
836
837        let duplicate_function = RustModuleDefinition::default()
838            .name("demo:Bad")
839            .function("load", |_, _| WhiskerValue::Null)
840            .async_function("load", |_, promise, _| promise.resolve(WhiskerValue::Null));
841        assert!(
842            RustModuleRuntime::new([duplicate_function], || {})
843                .err()
844                .expect("sync and async members must share one namespace")
845                .contains("both declare")
846        );
847    }
848}