1use std::any::Any;
6use std::cell::{Cell, RefCell};
7use std::collections::HashMap;
8use std::mem;
9use std::net::TcpStream;
10use std::sync::{Arc, Mutex};
11
12use base::cross_process_instant::CrossProcessInstant;
13use base::id::PipelineId;
14use log::{debug, warn};
15use serde_json::{Map, Value, json};
16
17use crate::StreamId;
18use crate::protocol::{ClientRequest, JsonPacketStream};
19
20#[derive(Debug)]
24pub enum ActorError {
25 MissingParameter,
26 BadParameterType,
27 UnrecognizedPacketType,
28 Internal,
31}
32
33impl ActorError {
34 pub fn name(&self) -> &'static str {
35 match self {
36 ActorError::MissingParameter => "missingParameter",
37 ActorError::BadParameterType => "badParameterType",
38 ActorError::UnrecognizedPacketType => "unrecognizedPacketType",
39 ActorError::Internal => "",
44 }
45 }
46}
47
48pub(crate) trait Actor: Any + ActorAsAny {
52 fn handle_message(
53 &self,
54 request: ClientRequest,
55 registry: &ActorRegistry,
56 msg_type: &str,
57 msg: &Map<String, Value>,
58 stream_id: StreamId,
59 ) -> Result<(), ActorError>;
60 fn name(&self) -> String;
61 fn cleanup(&self, _id: StreamId) {}
62}
63
64pub(crate) trait ActorAsAny {
65 fn actor_as_any(&self) -> &dyn Any;
66 fn actor_as_any_mut(&mut self) -> &mut dyn Any;
67}
68
69impl<T: Actor> ActorAsAny for T {
70 fn actor_as_any(&self) -> &dyn Any {
71 self
72 }
73 fn actor_as_any_mut(&mut self) -> &mut dyn Any {
74 self
75 }
76}
77
78pub struct ActorRegistry {
80 actors: HashMap<String, Box<dyn Actor + Send>>,
81 new_actors: RefCell<Vec<Box<dyn Actor + Send>>>,
82 old_actors: RefCell<Vec<String>>,
83 script_actors: RefCell<HashMap<String, String>>,
84
85 source_actor_names: RefCell<HashMap<PipelineId, Vec<String>>>,
87 inline_source_content: RefCell<HashMap<PipelineId, String>>,
89
90 shareable: Option<Arc<Mutex<ActorRegistry>>>,
91 next: Cell<u32>,
92 start_stamp: CrossProcessInstant,
93}
94
95impl ActorRegistry {
96 pub fn new() -> ActorRegistry {
98 ActorRegistry {
99 actors: HashMap::new(),
100 new_actors: RefCell::new(vec![]),
101 old_actors: RefCell::new(vec![]),
102 script_actors: RefCell::new(HashMap::new()),
103 source_actor_names: RefCell::new(HashMap::new()),
104 inline_source_content: RefCell::new(HashMap::new()),
105 shareable: None,
106 next: Cell::new(0),
107 start_stamp: CrossProcessInstant::now(),
108 }
109 }
110
111 pub(crate) fn cleanup(&self, stream_id: StreamId) {
112 for actor in self.actors.values() {
113 actor.cleanup(stream_id);
114 }
115 }
116
117 pub fn create_shareable(self) -> Arc<Mutex<ActorRegistry>> {
119 if let Some(shareable) = self.shareable {
120 return shareable;
121 }
122
123 let shareable = Arc::new(Mutex::new(self));
124 {
125 let mut lock = shareable.lock();
126 let registry = lock.as_mut().unwrap();
127 registry.shareable = Some(shareable.clone());
128 }
129 shareable
130 }
131
132 pub fn shareable(&self) -> Arc<Mutex<ActorRegistry>> {
134 self.shareable.as_ref().unwrap().clone()
135 }
136
137 pub fn start_stamp(&self) -> CrossProcessInstant {
139 self.start_stamp
140 }
141
142 pub fn register_script_actor(&self, script_id: String, actor: String) {
143 debug!("registering {} ({})", actor, script_id);
144 let mut script_actors = self.script_actors.borrow_mut();
145 script_actors.insert(script_id, actor);
146 }
147
148 pub fn script_to_actor(&self, script_id: String) -> String {
149 if script_id.is_empty() {
150 return "".to_owned();
151 }
152 self.script_actors.borrow().get(&script_id).unwrap().clone()
153 }
154
155 pub fn script_actor_registered(&self, script_id: String) -> bool {
156 self.script_actors.borrow().contains_key(&script_id)
157 }
158
159 pub fn actor_to_script(&self, actor: String) -> String {
160 for (key, value) in &*self.script_actors.borrow() {
161 debug!("checking {}", value);
162 if *value == actor {
163 return key.to_owned();
164 }
165 }
166 panic!("couldn't find actor named {}", actor)
167 }
168
169 pub fn new_name(&self, prefix: &str) -> String {
171 let suffix = self.next.get();
172 self.next.set(suffix + 1);
173 format!("{}{}", prefix, suffix)
174 }
175
176 pub(crate) fn register(&mut self, actor: Box<dyn Actor + Send>) {
178 self.actors.insert(actor.name(), actor);
179 }
180
181 pub(crate) fn register_later(&self, actor: Box<dyn Actor + Send>) {
182 let mut actors = self.new_actors.borrow_mut();
183 actors.push(actor);
184 }
185
186 pub fn find<'a, T: Any>(&'a self, name: &str) -> &'a T {
188 let actor = self.actors.get(name).unwrap();
189 actor.actor_as_any().downcast_ref::<T>().unwrap()
190 }
191
192 pub fn find_mut<'a, T: Any>(&'a mut self, name: &str) -> &'a mut T {
194 let actor = self.actors.get_mut(name).unwrap();
195 actor.actor_as_any_mut().downcast_mut::<T>().unwrap()
196 }
197
198 pub(crate) fn handle_message(
201 &mut self,
202 msg: &Map<String, Value>,
203 stream: &mut TcpStream,
204 stream_id: StreamId,
205 ) -> Result<(), ()> {
206 let to = match msg.get("to") {
207 Some(to) => to.as_str().unwrap(),
208 None => {
209 log::warn!("Received unexpected message: {:?}", msg);
210 return Err(());
211 },
212 };
213
214 match self.actors.get(to) {
215 None => {
216 let msg = json!({ "from": to, "error": "noSuchActor" });
218 let _ = stream.write_json_packet(&msg);
219 },
220 Some(actor) => {
221 let msg_type = msg.get("type").unwrap().as_str().unwrap();
222 if let Err(error) = ClientRequest::handle(stream, to, |req| {
223 actor.handle_message(req, self, msg_type, msg, stream_id)
224 }) {
225 let error = json!({
227 "from": actor.name(), "error": error.name()
228 });
229 warn!("Sending devtools protocol error: error={error:?} request={msg:?}");
230 let _ = stream.write_json_packet(&error);
231 }
232 },
233 }
234 let new_actors = mem::take(&mut *self.new_actors.borrow_mut());
235 for actor in new_actors.into_iter() {
236 self.actors.insert(actor.name().to_owned(), actor);
237 }
238
239 let old_actors = mem::take(&mut *self.old_actors.borrow_mut());
240 for name in old_actors {
241 self.drop_actor(name);
242 }
243 Ok(())
244 }
245
246 pub fn drop_actor(&mut self, name: String) {
247 self.actors.remove(&name);
248 }
249
250 pub fn drop_actor_later(&self, name: String) {
251 let mut actors = self.old_actors.borrow_mut();
252 actors.push(name);
253 }
254
255 pub fn register_source_actor(&self, pipeline_id: PipelineId, actor_name: &str) {
256 self.source_actor_names
257 .borrow_mut()
258 .entry(pipeline_id)
259 .or_default()
260 .push(actor_name.to_owned());
261 }
262
263 pub fn source_actor_names_for_pipeline(&mut self, pipeline_id: PipelineId) -> Vec<String> {
264 if let Some(source_actor_names) = self.source_actor_names.borrow_mut().get(&pipeline_id) {
265 return source_actor_names.clone();
266 }
267
268 vec![]
269 }
270
271 pub fn set_inline_source_content(&mut self, pipeline_id: PipelineId, content: String) {
272 assert!(
273 self.inline_source_content
274 .borrow_mut()
275 .insert(pipeline_id, content)
276 .is_none()
277 );
278 }
279
280 pub fn inline_source_content(&mut self, pipeline_id: PipelineId) -> Option<String> {
281 self.inline_source_content
282 .borrow()
283 .get(&pipeline_id)
284 .cloned()
285 }
286}