Skip to main content

wasm_actor_bridge/
actor.rs

1//! Worker-side actor trait.
2
3use serde::Serialize;
4use serde::de::DeserializeOwned;
5use std::future::Future;
6
7use crate::cancel::CancellationToken;
8use crate::context::Context;
9
10/// Trait for a worker-side actor that processes typed commands.
11///
12/// # Lifecycle
13///
14/// 1. The worker starts and calls `run_actor_loop(MyActor::default())`
15/// 2. The main thread sends an `Init` payload via `WorkerHandle::send_init()`
16/// 3. The actor's `init()` method is called with the payload
17/// 4. The command loop begins — all subsequent messages are `Cmd`
18///
19/// # Type Parameters
20///
21/// - `Init`: one-time initialization payload. Use `()` for no init.
22/// - `Cmd`: The command type posted from Main → Worker.
23/// - `Evt`: The event type posted from Worker → Main.
24pub trait WorkerActor: 'static {
25    /// One-time initialisation payload. The first message from the main thread
26    /// is always deserialized as this type before the command loop begins.
27    ///
28    /// Use `()` for workers that need no initialisation.
29    type Init: DeserializeOwned + 'static;
30
31    /// Command type (Main → Worker).
32    type Cmd: DeserializeOwned + 'static;
33    /// Event type (Worker → Main).
34    type Evt: Serialize + 'static;
35
36    /// Called exactly once with the first message, before the command loop.
37    ///
38    /// Default implementation: no-op.
39    fn init(&mut self, _init: Self::Init) {}
40
41    /// Handle a single command.
42    ///
43    /// Use `ctx` to send responses and access the binary payload.
44    /// Use `token` to check for cancellation at async yield points.
45    /// `ctx` is `Clone + 'static` — safe to move into spawned tasks.
46    fn handle(
47        &mut self,
48        cmd: Self::Cmd,
49        ctx: Context<Self::Evt>,
50        token: CancellationToken,
51    ) -> impl Future<Output = ()> + '_;
52}