devtools/
actor.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::any::{Any, type_name};
6use std::collections::HashMap;
7use std::marker::PhantomData;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicU32, Ordering};
10
11use atomic_refcell::AtomicRefCell;
12use log::{debug, warn};
13use malloc_size_of::MallocSizeOf;
14use malloc_size_of_derive::MallocSizeOf;
15use serde::Serialize;
16use serde_json::{Map, Value, json};
17use servo_base::id::PipelineId;
18
19use crate::StreamId;
20use crate::protocol::{ClientRequest, DevtoolsConnection, JsonPacketStream};
21
22/// Error replies.
23///
24/// <https://firefox-source-docs.mozilla.org/devtools/backend/protocol.html#error-packets>
25#[derive(Debug)]
26pub enum ActorError {
27    MissingParameter,
28    BadParameterType,
29    UnrecognizedPacketType,
30    /// Custom errors, not defined in the protocol docs.
31    /// This includes send errors, and errors that prevent Servo from sending a reply.
32    Internal,
33}
34
35impl ActorError {
36    pub fn name(&self) -> &'static str {
37        match self {
38            ActorError::MissingParameter => "missingParameter",
39            ActorError::BadParameterType => "badParameterType",
40            ActorError::UnrecognizedPacketType => "unrecognizedPacketType",
41            // The devtools frontend always checks for specific protocol errors by catching a JS exception `e` whose
42            // message contains the error name, and checking `e.message.includes("someErrorName")`. As a result, the
43            // only error name we can safely use for custom errors is the empty string, because any other error name we
44            // use may be a substring of some upstream error name.
45            ActorError::Internal => "",
46        }
47    }
48}
49
50/// A common trait for all devtools actors that encompasses an immutable name
51/// and the ability to process messages that are directed to particular actors.
52pub(crate) trait Actor: Any + ActorAsAny + Send + Sync + MallocSizeOf {
53    fn handle_message(
54        &self,
55        request: ClientRequest,
56        registry: &ActorRegistry,
57        msg_type: &str,
58        msg: &Map<String, Value>,
59        stream_id: StreamId,
60    ) -> Result<(), ActorError> {
61        let _ = (request, registry, msg_type, msg, stream_id);
62        Err(ActorError::UnrecognizedPacketType)
63    }
64    fn name(&self) -> String;
65    fn cleanup(&self, _id: StreamId) {}
66}
67
68pub(crate) trait ActorAsAny {
69    fn actor_as_any(&self) -> &dyn Any;
70}
71
72impl<T: Actor> ActorAsAny for T {
73    fn actor_as_any(&self) -> &dyn Any {
74        self
75    }
76}
77
78pub(crate) trait ActorEncode<T: Serialize>: Actor {
79    fn encode(&self, registry: &ActorRegistry) -> T;
80}
81
82/// Return value of `ActorRegistry::find` that allows seamless downcasting
83/// from `dyn Actor` to the concrete actor type.
84pub(crate) struct DowncastableActorArc<T> {
85    actor: Arc<dyn Actor>,
86    _phantom: PhantomData<T>,
87}
88
89impl<T: 'static> std::ops::Deref for DowncastableActorArc<T> {
90    type Target = T;
91    fn deref(&self) -> &Self::Target {
92        self.actor.actor_as_any().downcast_ref::<T>().unwrap()
93    }
94}
95
96#[derive(Default)]
97struct ActorRegistryType(AtomicRefCell<HashMap<String, Arc<dyn Actor>>>);
98
99impl MallocSizeOf for ActorRegistryType {
100    fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
101        self.0.borrow().iter().map(|actor| actor.size_of(ops)).sum()
102    }
103}
104
105/// A list of known, owned actors.
106#[derive(Default, MallocSizeOf)]
107pub(crate) struct ActorRegistry {
108    actors: ActorRegistryType,
109    script_actors: AtomicRefCell<HashMap<String, String>>,
110    /// Lookup table for SourceActor names associated with a given PipelineId.
111    source_actor_names: AtomicRefCell<HashMap<PipelineId, Vec<String>>>,
112    /// Lookup table for inline source content associated with a given PipelineId.
113    inline_source_content: AtomicRefCell<HashMap<PipelineId, String>>,
114    next: AtomicU32,
115}
116
117impl ActorRegistry {
118    pub(crate) fn cleanup(&self, stream_id: StreamId) {
119        for actor in self.actors.0.borrow().values() {
120            actor.cleanup(stream_id);
121        }
122    }
123
124    pub fn register_script_actor(&self, script_id: String, actor: String) {
125        debug!("registering {} ({})", actor, script_id);
126        let mut script_actors = self.script_actors.borrow_mut();
127        script_actors.insert(script_id, actor);
128    }
129
130    pub fn script_to_actor(&self, script_id: String) -> String {
131        if script_id.is_empty() {
132            return "".to_owned();
133        }
134        self.script_actors.borrow().get(&script_id).unwrap().clone()
135    }
136
137    pub fn script_actor_registered(&self, script_id: String) -> bool {
138        self.script_actors.borrow().contains_key(&script_id)
139    }
140
141    pub fn actor_to_script(&self, actor: String) -> String {
142        for (key, value) in &*self.script_actors.borrow() {
143            if *value == actor {
144                return key.to_owned();
145            }
146        }
147        panic!("couldn't find actor named {}", actor)
148    }
149
150    /// Create a name prefix for each actor type.
151    /// While not needed for unique ids as each actor already has a different
152    /// suffix, it can be used to visually identify actors in the logs.
153    pub fn base_name<T: Actor>() -> &'static str {
154        let prefix = type_name::<T>();
155        prefix.split("::").last().unwrap_or(prefix)
156    }
157
158    /// Create a unique name based on a monotonically increasing suffix
159    /// TODO: Merge this with `register` and don't allow to
160    /// create new names without registering an actor.
161    pub fn new_name<T: Actor>(&self) -> String {
162        let suffix = self.next.fetch_add(1, Ordering::Relaxed);
163        format!("{}{}", Self::base_name::<T>(), suffix)
164    }
165
166    /// Add an actor to the registry of known actors that can receive messages.
167    pub(crate) fn register<T: Actor>(&self, actor: T) {
168        self.actors
169            .0
170            .borrow_mut()
171            .insert(actor.name(), Arc::new(actor));
172    }
173
174    /// Find an actor by registered name
175    pub fn find<T: Actor>(&self, name: &str) -> DowncastableActorArc<T> {
176        let actor = self
177            .actors
178            .0
179            .borrow()
180            .get(name)
181            .expect("Should never look for a nonexistent actor")
182            .clone();
183        DowncastableActorArc {
184            actor,
185            _phantom: PhantomData,
186        }
187    }
188
189    /// Find an actor by registered name and return its serialization
190    pub fn encode<T: ActorEncode<S>, S: Serialize>(&self, name: &str) -> S {
191        self.find::<T>(name).encode(self)
192    }
193
194    /// Attempt to process a message as directed by its `to` property. If the actor is not found, does not support the
195    /// message, or failed to handle the message, send an error reply instead.
196    pub(crate) fn handle_message(
197        &self,
198        msg: &Map<String, Value>,
199        stream: &mut DevtoolsConnection,
200        stream_id: StreamId,
201    ) -> Result<(), ()> {
202        let to = match msg.get("to") {
203            Some(to) => to.as_str().unwrap(),
204            None => {
205                log::warn!("Received unexpected message: {:?}", msg);
206                return Err(());
207            },
208        };
209
210        let actor = {
211            let actors_map = self.actors.0.borrow();
212            actors_map.get(to).cloned()
213        };
214        match actor {
215            None => {
216                // <https://firefox-source-docs.mozilla.org/devtools/backend/protocol.html#packets>
217                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.clone(), to, |req| {
223                    actor.handle_message(req, self, msg_type, msg, stream_id)
224                }) {
225                    // <https://firefox-source-docs.mozilla.org/devtools/backend/protocol.html#error-packets>
226                    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        Ok(())
235    }
236
237    pub fn remove(&self, name: String) {
238        self.actors.0.borrow_mut().remove(&name);
239    }
240
241    pub fn register_source_actor(&self, pipeline_id: PipelineId, actor_name: &str) {
242        self.source_actor_names
243            .borrow_mut()
244            .entry(pipeline_id)
245            .or_default()
246            .push(actor_name.to_owned());
247    }
248
249    pub fn source_actor_names_for_pipeline(&self, pipeline_id: PipelineId) -> Vec<String> {
250        self.source_actor_names
251            .borrow_mut()
252            .get(&pipeline_id)
253            .cloned()
254            .unwrap_or_default()
255    }
256
257    pub fn set_inline_source_content(&self, pipeline_id: PipelineId, content: String) {
258        assert!(
259            self.inline_source_content
260                .borrow_mut()
261                .insert(pipeline_id, content)
262                .is_none()
263        );
264    }
265
266    pub fn inline_source_content(&self, pipeline_id: PipelineId) -> Option<String> {
267        self.inline_source_content
268            .borrow()
269            .get(&pipeline_id)
270            .cloned()
271    }
272}