1mod link;
4mod local;
5mod pool;
6mod worker;
7
8pub use link::AgentLink;
9pub(crate) use link::*;
10pub use local::{Context, Job};
11pub(crate) use pool::*;
12pub use pool::{Dispatched, Dispatcher};
13pub use worker::{Private, Public, Threaded};
14
15use crate::callback::Callback;
16use serde::{Deserialize, Serialize};
17use std::fmt;
18use std::ops::{Deref, DerefMut};
19
20pub trait Agent: Sized + 'static {
22 type Reach: Discoverer<Agent = Self>;
24 type Message;
26 type Input;
28 type Output;
30
31 fn create(link: AgentLink<Self>) -> Self;
33
34 fn update(&mut self, msg: Self::Message);
36
37 fn connected(&mut self, _id: HandlerId) {}
39
40 fn handle_input(&mut self, msg: Self::Input, id: HandlerId);
42
43 fn disconnected(&mut self, _id: HandlerId) {}
45
46 fn destroy(&mut self) {}
48
49 fn name_of_resource() -> &'static str {
52 "main.js"
53 }
54
55 fn is_module() -> bool {
58 false
59 }
60}
61
62#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Hash, Clone, Copy)]
64pub struct HandlerId(usize, bool);
65
66impl HandlerId {
67 fn new(id: usize, respondable: bool) -> Self {
68 HandlerId(id, respondable)
69 }
70 fn raw_id(self) -> usize {
71 self.0
72 }
73 pub fn is_respondable(self) -> bool {
75 self.1
76 }
77}
78
79#[doc(hidden)]
81pub trait Discoverer {
82 type Agent: Agent;
83
84 fn spawn_or_join(
86 _callback: Option<Callback<<Self::Agent as Agent>::Output>>,
87 ) -> Box<dyn Bridge<Self::Agent>>;
88}
89
90pub trait Bridge<AGN: Agent> {
92 fn send(&mut self, msg: AGN::Input);
94}
95
96pub trait Bridged: Agent + Sized + 'static {
98 fn bridge(callback: Callback<Self::Output>) -> Box<dyn Bridge<Self>>;
100}
101
102impl<T> Bridged for T
103where
104 T: Agent,
105 <T as Agent>::Reach: Discoverer<Agent = T>,
106{
107 fn bridge(callback: Callback<Self::Output>) -> Box<dyn Bridge<Self>> {
108 Self::Reach::spawn_or_join(Some(callback))
109 }
110}