lunatic_process/
state.rs

1use std::{collections::HashMap, sync::Arc};
2
3use anyhow::Result;
4use hash_map_id::HashMapId;
5use tokio::sync::{
6    mpsc::{UnboundedReceiver, UnboundedSender},
7    Mutex, RwLock,
8};
9use wasmtime::Linker;
10
11use crate::{
12    config::ProcessConfig,
13    mailbox::MessageMailbox,
14    runtimes::wasmtime::{WasmtimeCompiledModule, WasmtimeRuntime},
15    Signal,
16};
17
18pub type ConfigResources<T> = HashMapId<T>;
19pub type SignalSender = UnboundedSender<Signal>;
20pub type SignalReceiver = Arc<Mutex<UnboundedReceiver<Signal>>>;
21
22/// The internal state of a process.
23///
24/// The `ProcessState` has two main roles:
25/// - It holds onto all vm resources (file descriptors, tcp streams, channels, ...)
26/// - Registers all host functions working on those resources to the `Linker`
27pub trait ProcessState: Sized {
28    type Config: ProcessConfig + Default + Send + Sync;
29
30    // Create a new `ProcessState` using the parent's state (self) to inherit environment and
31    // other parts of the state.
32    // This is used in the guest function `spawn` which uses this trait and not the concrete state.
33    fn new_state(
34        &self,
35        module: Arc<WasmtimeCompiledModule<Self>>,
36        config: Arc<Self::Config>,
37    ) -> Result<Self>;
38
39    /// Register all host functions to the linker.
40    fn register(linker: &mut Linker<Self>) -> Result<()>;
41    /// Marks a wasm instance as initialized
42    fn initialize(&mut self);
43    /// Returns true if the instance was initialized
44    fn is_initialized(&self) -> bool;
45
46    /// Returns the WebAssembly runtime
47    fn runtime(&self) -> &WasmtimeRuntime;
48    // Returns the WebAssembly module
49    fn module(&self) -> &Arc<WasmtimeCompiledModule<Self>>;
50    /// Returns the process configuration
51    fn config(&self) -> &Arc<Self::Config>;
52
53    // Returns process ID
54    fn id(&self) -> u64;
55    // Returns signal mailbox
56    fn signal_mailbox(&self) -> &(SignalSender, SignalReceiver);
57    // Returns message mailbox
58    fn message_mailbox(&self) -> &MessageMailbox;
59
60    // Config resources
61    fn config_resources(&self) -> &ConfigResources<Self::Config>;
62    fn config_resources_mut(&mut self) -> &mut ConfigResources<Self::Config>;
63
64    // Registry
65    fn registry(&self) -> &Arc<RwLock<HashMap<String, (u64, u64)>>>;
66}