gloo_worker/actor/
traits.rs

1use super::handler_id::HandlerId;
2use super::registrar::WorkerRegistrar;
3use super::scope::{WorkerDestroyHandle, WorkerScope};
4use super::spawner::WorkerSpawner;
5use crate::traits::{Registrable, Spawnable};
6
7/// Declares the behaviour of a worker.
8pub trait Worker: Sized {
9    /// Update message type.
10    type Message;
11    /// Incoming message type.
12    type Input;
13    /// Outgoing message type.
14    type Output;
15
16    /// Creates an instance of a worker.
17    fn create(scope: &WorkerScope<Self>) -> Self;
18
19    /// Receives an update.
20    ///
21    /// This method is called when the worker send messages to itself via [`WorkerScope::send_message`].
22    fn update(&mut self, scope: &WorkerScope<Self>, msg: Self::Message);
23
24    /// New bridge created.
25    ///
26    /// When a new bridge is created by [`WorkerSpawner::spawn`](crate::spawner::WorkerSpawner)
27    /// or [`WorkerBridge::fork`](crate::WorkerBridge::fork),
28    /// the worker will be notified the [`HandlerId`] of the created bridge via this method.
29    fn connected(&mut self, scope: &WorkerScope<Self>, id: HandlerId) {
30        let _scope = scope;
31        let _id = id;
32    }
33
34    /// Receives an input from a connected bridge.
35    ///
36    /// When a bridge sends an input via [`WorkerBridge::send`](crate::WorkerBridge::send), the worker will receive the
37    /// input via this method.
38    fn received(&mut self, scope: &WorkerScope<Self>, msg: Self::Input, id: HandlerId);
39
40    /// Existing bridge destroyed.
41    ///
42    /// When a bridge is dropped, the worker will be notified with this method.
43    fn disconnected(&mut self, scope: &WorkerScope<Self>, id: HandlerId) {
44        let _scope = scope;
45        let _id = id;
46    }
47
48    /// Destroys the current worker.
49    ///
50    /// When all bridges are dropped, the method will be invoked.
51    ///
52    /// This method is provided a destroy handle where when it is dropped, the worker is closed.
53    /// If the worker is closed immediately, then it can ignore the destroy handle.
54    /// Otherwise hold the destroy handle until the clean up task is finished.
55    ///
56    /// # Note
57    ///
58    /// This method will only be called after all bridges are disconnected.
59    /// Attempting to send messages after this method is called will have no effect.
60    fn destroy(&mut self, scope: &WorkerScope<Self>, destruct: WorkerDestroyHandle<Self>) {
61        let _scope = scope;
62        let _destruct = destruct;
63    }
64}
65
66impl<W> Spawnable for W
67where
68    W: Worker + 'static,
69{
70    type Spawner = WorkerSpawner<Self>;
71
72    fn spawner() -> WorkerSpawner<Self> {
73        WorkerSpawner::new()
74    }
75}
76
77impl<W> Registrable for W
78where
79    W: Worker + 'static,
80{
81    type Registrar = WorkerRegistrar<Self>;
82
83    fn registrar() -> WorkerRegistrar<Self> {
84        WorkerRegistrar::new()
85    }
86}