Skip to main content

devtools/actors/
console.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
5//! Liberally derived from the [Firefox JS implementation](https://searchfox.org/firefox-main/source/devtools/server/actors/webconsole.js).
6//! Mediates interaction between the remote web console and equivalent functionality (object
7//! inspection, JS evaluation, autocompletion) in Servo.
8
9use std::collections::HashMap;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12
13use atomic_refcell::AtomicRefCell;
14use devtools_traits::{
15    ConsoleMessage, ConsoleMessageFields, DebuggerValue, DevtoolScriptControlMsg,
16    GetEnvironmentRequest, PageError, StackFrame, get_time_stamp,
17};
18use embedder_traits::ConsoleLogLevel;
19use malloc_size_of_derive::MallocSizeOf;
20use serde::Serialize;
21use serde_json::{self, Map, Value};
22use servo_base::generic_channel::{self, GenericSender, channel};
23use servo_base::id::{PipelineId, TEST_PIPELINE_ID};
24use uuid::Uuid;
25
26use crate::actor::{Actor, ActorError, ActorRegistry};
27use crate::actors::browsing_context::BrowsingContextActor;
28use crate::actors::environment::EnvironmentActor;
29use crate::actors::worker::WorkerTargetActor;
30use crate::protocol::{ClientRequest, DevtoolsConnection, JsonPacketStream};
31use crate::resource::{ResourceArrayType, ResourceAvailable};
32use crate::{EmptyReplyMsg, StreamId, UniqueId, console_table_items, debugger_value_to_json};
33
34/// Port of the `message.level === "table"` branch of Firefox's
35/// `prepareConsoleMessageForRemote`:
36/// <https://searchfox.org/firefox-main/source/devtools/server/actors/resources/console-messages.js>
37///
38/// - `arguments[0].ownProperties` holds the table rows (with one level of sub-properties),
39/// - `arguments[0].preview` is set to null,
40/// - only the first two arguments (data, columns) are sent.
41fn console_table_arguments(registry: &ActorRegistry, arguments: Vec<DebuggerValue>) -> Vec<Value> {
42    let table_items = arguments
43        .first()
44        .and_then(|data| console_table_items(registry, data, true));
45
46    // "Only return the 2 first params."
47    let mut grips: Vec<Value> = arguments
48        .into_iter()
49        .take(2)
50        .map(|argument| debugger_value_to_json(registry, argument))
51        .collect();
52
53    if let (Some(items), Some(grip)) = (
54        table_items,
55        grips.first_mut().and_then(Value::as_object_mut),
56    ) {
57        grip.insert("ownProperties".to_owned(), Value::Object(items));
58        grip.insert("preview".to_owned(), Value::Null);
59    }
60
61    grips
62}
63
64#[derive(Clone, Serialize, MallocSizeOf)]
65#[serde(rename_all = "camelCase")]
66pub(crate) struct DevtoolsConsoleMessage {
67    #[serde(flatten)]
68    fields: ConsoleMessageFields,
69    #[ignore_malloc_size_of = "Currently no way to have serde_json::Value"]
70    arguments: Vec<Value>,
71    #[serde(skip_serializing_if = "Option::is_none")]
72    stacktrace: Option<Vec<StackFrame>>,
73    // Not implemented in Servo
74    // inner_window_id
75    // source_id
76}
77
78impl DevtoolsConsoleMessage {
79    pub(crate) fn new(message: ConsoleMessage, registry: &ActorRegistry) -> Self {
80        if matches!(message.fields.level, ConsoleLogLevel::Table) {
81            Self {
82                fields: message.fields,
83                arguments: console_table_arguments(registry, message.arguments),
84                stacktrace: message.stacktrace,
85            }
86        } else {
87            Self {
88                fields: message.fields,
89                arguments: message
90                    .arguments
91                    .into_iter()
92                    .map(|argument| debugger_value_to_json(registry, argument))
93                    .collect(),
94                stacktrace: message.stacktrace,
95            }
96        }
97    }
98}
99
100#[derive(Clone, Serialize, MallocSizeOf)]
101#[serde(rename_all = "camelCase")]
102struct DevtoolsPageError {
103    #[serde(flatten)]
104    page_error: PageError,
105    category: String,
106    error: bool,
107    warning: bool,
108    info: bool,
109    private: bool,
110    #[serde(skip_serializing_if = "Option::is_none")]
111    stacktrace: Option<Vec<StackFrame>>,
112    // Not implemented in Servo
113    // inner_window_id
114    // source_id
115    // has_exception
116    // exception
117}
118
119impl From<PageError> for DevtoolsPageError {
120    fn from(page_error: PageError) -> Self {
121        Self {
122            page_error,
123            category: "script".to_string(),
124            error: true,
125            warning: false,
126            info: false,
127            private: false,
128            stacktrace: None,
129        }
130    }
131}
132#[derive(Clone, Serialize, MallocSizeOf)]
133#[serde(rename_all = "camelCase")]
134pub(crate) struct PageErrorWrapper {
135    page_error: DevtoolsPageError,
136}
137
138impl From<PageError> for PageErrorWrapper {
139    fn from(page_error: PageError) -> Self {
140        Self {
141            page_error: page_error.into(),
142        }
143    }
144}
145
146#[derive(Clone, Serialize, MallocSizeOf)]
147#[serde(untagged)]
148pub(crate) enum ConsoleResource {
149    ConsoleMessage(DevtoolsConsoleMessage),
150    PageError(PageErrorWrapper),
151}
152
153impl ConsoleResource {
154    pub fn resource_type(&self) -> String {
155        match self {
156            ConsoleResource::ConsoleMessage(_) => "console-message".into(),
157            ConsoleResource::PageError(_) => "error-message".into(),
158        }
159    }
160}
161
162#[derive(Serialize)]
163pub struct ConsoleClearMessage {
164    pub level: String,
165}
166
167#[derive(Serialize)]
168#[serde(rename_all = "camelCase")]
169struct AutocompleteReply {
170    from: String,
171    matches: Vec<String>,
172    match_prop: String,
173    is_element_access: bool,
174}
175
176#[derive(Serialize)]
177#[serde(rename_all = "camelCase")]
178struct EvaluateJSReply {
179    from: String,
180    input: String,
181    result: Value,
182    timestamp: u64,
183    exception: Value,
184    exception_message: Option<String>,
185    has_exception: bool,
186    helper_result: Value,
187}
188
189#[derive(Serialize)]
190#[serde(rename_all = "camelCase")]
191struct EvaluateJSEvent {
192    from: String,
193    #[serde(rename = "type")]
194    type_: String,
195    input: String,
196    result: Value,
197    timestamp: u64,
198    #[serde(rename = "resultID")]
199    result_id: String,
200    exception: Value,
201    exception_message: Option<String>,
202    has_exception: bool,
203    helper_result: Value,
204}
205
206#[derive(Serialize)]
207struct EvaluateJSAsyncReply {
208    from: String,
209    #[serde(rename = "resultID")]
210    result_id: String,
211}
212
213#[derive(Serialize)]
214struct SetPreferencesReply {
215    from: String,
216    updated: Vec<String>,
217}
218
219#[derive(MallocSizeOf)]
220pub(crate) enum Root {
221    BrowsingContext(String),
222    DedicatedWorker(String),
223}
224
225#[derive(MallocSizeOf)]
226pub(crate) struct ConsoleActor {
227    name: String,
228    root: Root,
229    cached_events: AtomicRefCell<HashMap<UniqueId, Vec<ConsoleResource>>>,
230    /// Used to control whether to send resource array messages from
231    /// `handle_console_resource`. It starts being false, and it only gets
232    /// activated after the client requests `console-message` or `error-message`
233    /// resources for the first time. Otherwise we would be sending messages
234    /// before the client is ready to receive them.
235    client_ready_to_receive_messages: AtomicBool,
236}
237
238impl ConsoleActor {
239    pub fn register(registry: &ActorRegistry, name: String, root: Root) -> Arc<Self> {
240        let actor = Self {
241            name,
242            root,
243            cached_events: Default::default(),
244            client_ready_to_receive_messages: false.into(),
245        };
246        registry.register::<Self>(actor)
247    }
248
249    fn script_chan(&self, registry: &ActorRegistry) -> GenericSender<DevtoolScriptControlMsg> {
250        match &self.root {
251            Root::BrowsingContext(browsing_context_name) => registry
252                .find::<BrowsingContextActor>(browsing_context_name)
253                .script_chan(),
254            Root::DedicatedWorker(worker_name) => registry
255                .find::<WorkerTargetActor>(worker_name)
256                .script_sender
257                .clone(),
258        }
259    }
260
261    fn current_unique_id(&self, registry: &ActorRegistry) -> UniqueId {
262        match &self.root {
263            Root::BrowsingContext(browsing_context_name) => UniqueId::Pipeline(
264                registry
265                    .find::<BrowsingContextActor>(browsing_context_name)
266                    .pipeline_id(),
267            ),
268            Root::DedicatedWorker(worker_name) => {
269                UniqueId::Worker(registry.find::<WorkerTargetActor>(worker_name).worker_id)
270            },
271        }
272    }
273
274    fn pipeline_id(&self, registry: &ActorRegistry) -> PipelineId {
275        // FIXME: Redesign messages so we don't have to fake pipeline ids when communicating with workers.
276        match self.current_unique_id(registry) {
277            UniqueId::Pipeline(p) => p,
278            UniqueId::Worker(_) => TEST_PIPELINE_ID,
279        }
280    }
281
282    fn evaluate_js(
283        &self,
284        registry: &ActorRegistry,
285        msg: &Map<String, Value>,
286    ) -> Result<EvaluateJSReply, ()> {
287        let input = msg.get("text").unwrap().as_str().unwrap().to_owned();
288        let eager = msg.get("eager").and_then(|v| v.as_bool()).unwrap_or(false);
289        let frame_actor_id = msg
290            .get("frameActor")
291            .and_then(|v| v.as_str())
292            .map(String::from);
293
294        let (chan, port) = generic_channel::channel().unwrap();
295        self.script_chan(registry)
296            .send(DevtoolScriptControlMsg::Eval(
297                input.clone(),
298                self.pipeline_id(registry),
299                frame_actor_id,
300                eager,
301                chan,
302            ))
303            .unwrap();
304
305        let eval_result = port.recv().map_err(|_| ())?;
306        let has_exception = eval_result.has_exception;
307        let (result, exception) = if has_exception {
308            (
309                Value::Null,
310                debugger_value_to_json(registry, eval_result.value),
311            )
312        } else {
313            (
314                debugger_value_to_json(registry, eval_result.value),
315                Value::Null,
316            )
317        };
318        let reply = EvaluateJSReply {
319            from: self.name().into(),
320            input,
321            result,
322            timestamp: get_time_stamp(),
323            exception,
324            exception_message: eval_result.exception_message,
325            has_exception,
326            helper_result: Value::Null,
327        };
328        Ok(reply)
329    }
330
331    pub(crate) fn handle_console_resource(
332        &self,
333        resource: ConsoleResource,
334        id: UniqueId,
335        registry: &ActorRegistry,
336        stream: &mut DevtoolsConnection,
337    ) {
338        self.cached_events
339            .borrow_mut()
340            .entry(id.clone())
341            .or_default()
342            .push(resource.clone());
343        if !self
344            .client_ready_to_receive_messages
345            .load(Ordering::Relaxed)
346        {
347            return;
348        }
349        let resource_type = resource.resource_type();
350        if id == self.current_unique_id(registry) &&
351            let Root::BrowsingContext(browsing_context_name) = &self.root
352        {
353            registry
354                .find::<BrowsingContextActor>(browsing_context_name)
355                .resource_array(
356                    resource,
357                    resource_type,
358                    ResourceArrayType::Available,
359                    stream,
360                )
361        };
362    }
363
364    pub(crate) fn send_clear_message(
365        &self,
366        id: UniqueId,
367        registry: &ActorRegistry,
368        stream: &mut DevtoolsConnection,
369    ) {
370        if id == self.current_unique_id(registry) &&
371            let Root::BrowsingContext(browsing_context_name) = &self.root
372        {
373            registry
374                .find::<BrowsingContextActor>(browsing_context_name)
375                .resource_array(
376                    ConsoleClearMessage {
377                        level: "clear".to_owned(),
378                    },
379                    "console-message".into(),
380                    ResourceArrayType::Available,
381                    stream,
382                )
383        };
384    }
385
386    pub(crate) fn get_cached_messages(
387        &self,
388        registry: &ActorRegistry,
389        resource: &str,
390    ) -> Vec<ConsoleResource> {
391        let id = self.current_unique_id(registry);
392        let cached_events = self.cached_events.borrow();
393        let Some(events) = cached_events.get(&id) else {
394            return vec![];
395        };
396        events
397            .iter()
398            .filter(|event| event.resource_type() == resource)
399            .cloned()
400            .collect()
401    }
402
403    pub(crate) fn received_first_message_from_client(&self) {
404        self.client_ready_to_receive_messages
405            .store(true, Ordering::Relaxed);
406    }
407
408    /// Matching function with conditional case-sensitivity as per:
409    /// <https://searchfox.org/firefox-main/rev/7fa9b602777418732e08b26d1ef6c9945c4bbd72/devtools/shared/webconsole/js-property-provider.js#617-622>
410    pub(crate) fn autocomplete_match(prefix: &str, identifier: &str) -> bool {
411        let is_insensitive = prefix.chars().next().is_some_and(|c| c.is_lowercase());
412        if is_insensitive {
413            identifier
414                .to_lowercase()
415                .starts_with(&prefix.to_lowercase())
416        } else {
417            identifier.starts_with(prefix)
418        }
419    }
420}
421
422impl Actor for ConsoleActor {
423    fn name(&self) -> &str {
424        &self.name
425    }
426
427    fn handle_message(
428        &self,
429        request: ClientRequest,
430        registry: &ActorRegistry,
431        msg_type: &str,
432        msg: &Map<String, Value>,
433        _id: StreamId,
434    ) -> Result<(), ActorError> {
435        match msg_type {
436            "clearMessagesCacheAsync" => {
437                self.cached_events
438                    .borrow_mut()
439                    .remove(&self.current_unique_id(registry));
440                let msg = EmptyReplyMsg {
441                    from: self.name().into(),
442                };
443                request.reply_final(&msg)?
444            },
445
446            "autocomplete" => {
447                let Some((tx, rx)) = channel() else {
448                    return Err(ActorError::Internal);
449                };
450
451                let env_request = if let Some(frame_actor) = msg
452                    .get("frameActor")
453                    .and_then(|v| v.as_str())
454                    .map(String::from)
455                {
456                    GetEnvironmentRequest::Frame(frame_actor)
457                } else {
458                    GetEnvironmentRequest::Global(self.pipeline_id(registry))
459                };
460
461                self.script_chan(registry)
462                    .send(DevtoolScriptControlMsg::GetEnvironment(env_request, tx))
463                    .map_err(|_| ActorError::Internal)?;
464
465                let environment_name = rx.recv().map_err(|_| ActorError::Internal)?;
466                let environment_actor = registry.find::<EnvironmentActor>(&environment_name);
467
468                let prompt = msg
469                    .get("text")
470                    .and_then(|v| v.as_str())
471                    .map(String::from)
472                    .ok_or(ActorError::Internal)?;
473
474                let identifiers = environment_actor.search_identifiers_recursive(registry, &prompt);
475
476                let matches: Vec<String> = identifiers
477                    .into_iter()
478                    .filter(|name| ConsoleActor::autocomplete_match(&prompt, name))
479                    .collect();
480
481                let msg = if matches.is_empty() {
482                    AutocompleteReply {
483                        from: self.name().into(),
484                        matches: vec![],
485                        match_prop: String::new(),
486                        is_element_access: false,
487                    }
488                } else {
489                    AutocompleteReply {
490                        from: self.name().into(),
491                        matches,
492                        match_prop: prompt,
493                        is_element_access: false,
494                    }
495                };
496                request.reply_final(&msg)?
497            },
498
499            "evaluateJS" => {
500                let msg = self.evaluate_js(registry, msg);
501                request.reply_final(&msg)?
502            },
503
504            "evaluateJSAsync" => {
505                let result_id = Uuid::new_v4().to_string();
506                let early_reply = EvaluateJSAsyncReply {
507                    from: self.name().into(),
508                    result_id: result_id.clone(),
509                };
510                // Emit an eager reply so that the client starts listening
511                // for an async event with the resultID
512                let mut stream = request.reply(&early_reply)?;
513
514                let reply = self.evaluate_js(registry, msg).unwrap();
515                let msg = EvaluateJSEvent {
516                    from: self.name().into(),
517                    type_: "evaluationResult".to_owned(),
518                    input: reply.input,
519                    result: reply.result,
520                    timestamp: reply.timestamp,
521                    result_id,
522                    exception: reply.exception,
523                    exception_message: reply.exception_message,
524                    has_exception: reply.has_exception,
525                    helper_result: reply.helper_result,
526                };
527                // Send the data from evaluateJS along with a resultID
528                stream.write_json_packet(&msg)?
529            },
530
531            "setPreferences" => {
532                let msg = SetPreferencesReply {
533                    from: self.name().into(),
534                    updated: vec![],
535                };
536                request.reply_final(&msg)?
537            },
538
539            // NOTE: Do not handle `startListeners`, it is a legacy API.
540            // Instead, enable the resource in `WatcherActor::supported_resources`
541            // and handle the messages there.
542            _ => return Err(ActorError::UnrecognizedPacketType),
543        };
544        Ok(())
545    }
546}