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        let base = Self::base_name::<T>();
164
165        // Firefox DevTools client requires "/workerTarget" in actor name to recognize workers
166        // <https://searchfox.org/firefox-main/source/devtools/client/fronts/watcher.js#65>
167        if base.contains("WorkerTarget") {
168            format!("/workerTarget{}", suffix)
169        } else {
170            format!("{}{}", base, suffix)
171        }
172    }
173
174    /// Add an actor to the registry of known actors that can receive messages.
175    pub(crate) fn register<T: Actor>(&self, actor: T) {
176        self.actors
177            .0
178            .borrow_mut()
179            .insert(actor.name(), Arc::new(actor));
180    }
181
182    /// Find an actor by registered name
183    pub fn find<T: Actor>(&self, name: &str) -> DowncastableActorArc<T> {
184        let actor = self
185            .actors
186            .0
187            .borrow()
188            .get(name)
189            .expect("Should never look for a nonexistent actor")
190            .clone();
191        DowncastableActorArc {
192            actor,
193            _phantom: PhantomData,
194        }
195    }
196
197    /// Find an actor by registered name and return its serialization
198    pub fn encode<T: ActorEncode<S>, S: Serialize>(&self, name: &str) -> S {
199        self.find::<T>(name).encode(self)
200    }
201
202    /// Attempt to process a message as directed by its `to` property. If the actor is not found, does not support the
203    /// message, or failed to handle the message, send an error reply instead.
204    pub(crate) fn handle_message(
205        &self,
206        msg: &Map<String, Value>,
207        stream: &mut DevtoolsConnection,
208        stream_id: StreamId,
209    ) -> Result<(), ()> {
210        let to = match msg.get("to") {
211            Some(to) => to.as_str().unwrap(),
212            None => {
213                log::warn!("Received unexpected message: {:?}", msg);
214                return Err(());
215            },
216        };
217
218        let actor = {
219            let actors_map = self.actors.0.borrow();
220            actors_map.get(to).cloned()
221        };
222        match actor {
223            None => {
224                // <https://firefox-source-docs.mozilla.org/devtools/backend/protocol.html#packets>
225                let msg = json!({ "from": to, "error": "noSuchActor" });
226                let _ = stream.write_json_packet(&msg);
227            },
228            Some(actor) => {
229                let msg_type = msg.get("type").unwrap().as_str().unwrap();
230                if let Err(error) = ClientRequest::handle(stream.clone(), to, |req| {
231                    actor.handle_message(req, self, msg_type, msg, stream_id)
232                }) {
233                    // <https://firefox-source-docs.mozilla.org/devtools/backend/protocol.html#error-packets>
234                    let error = json!({
235                        "from": actor.name(), "error": error.name()
236                    });
237                    warn!("Sending devtools protocol error: error={error:?} request={msg:?}");
238                    let _ = stream.write_json_packet(&error);
239                }
240            },
241        }
242        Ok(())
243    }
244
245    pub fn remove(&self, name: String) {
246        self.actors.0.borrow_mut().remove(&name);
247    }
248
249    pub fn register_source_actor(&self, pipeline_id: PipelineId, actor_name: &str) {
250        self.source_actor_names
251            .borrow_mut()
252            .entry(pipeline_id)
253            .or_default()
254            .push(actor_name.to_owned());
255    }
256
257    pub fn source_actor_names_for_pipeline(&self, pipeline_id: PipelineId) -> Vec<String> {
258        self.source_actor_names
259            .borrow_mut()
260            .get(&pipeline_id)
261            .cloned()
262            .unwrap_or_default()
263    }
264
265    pub fn set_inline_source_content(&self, pipeline_id: PipelineId, content: String) {
266        assert!(
267            self.inline_source_content
268                .borrow_mut()
269                .insert(pipeline_id, content)
270                .is_none()
271        );
272    }
273
274    pub fn inline_source_content(&self, pipeline_id: PipelineId) -> Option<String> {
275        self.inline_source_content
276            .borrow()
277            .get(&pipeline_id)
278            .cloned()
279    }
280}