Add direct script to embedder channel (#39039)

This PR **removes** `ScriptToConstellationMessage::ForwardToEmbedder`,
and replaces it with an explicit `ScriptToEmbedderChannel`. This new
channel is based on `GenericCallback` and in single-process mode will
directly send the message the to the embedder and wake it. In
multi-process mode, the message is routed via the ROUTER, since waking
is only possible from the same process currently. This means in
multi-process mode there are likely no direct perf benefits, since we
still need to hop the message over the ROUTER (instead of over the
constellation).
In single-process mode we can directly send the message to the embedder,
which should provide a noticable latency improvement in all cases where
script is blocked waiting on the embedder to reply.

This does not change the way the embedder receives messages - the
receiving end is unchanged.

## How was sending messages to the embedder working before?

1. Script wraps it's message to the embedder in
`ScriptToConstellationMessage::ForwardToEmbedder` and sends it to
constellation.
2. The [constellation event loop] receives the message in
[handle_request]
3. If deserialization fails, [an error is logged and the message is
ignored]
4. Since our message came from script, it is handle in
[handle_request_from_script]
5. The message is logged with trace log level
6. If the pipeline is closed, [a warning is logged and the message
ignored]
7. The wrapped `EmbedderMsg` [is forwarded to the embedder]. Sending the
message also invokes `wake()` on the embedder eventloop waker.

[constellation event loop]:
2e1b2e7260/components/constellation/constellation.rs (L755)

[handle request]:
2e1b2e7260/components/constellation/constellation.rs (L1182)

[an error is logged and the message is ignored]:
2e1b2e7260/components/constellation/constellation.rs (L1252)

[handle_request_from_script]:
https://github.com/servo/servo/blob/main/components/constellation/constellation.rs#L1590
 
[a warning is logged and the message ignored]:
2e1b2e7260/components/constellation/constellation.rs (L1599)

[is forwarded to the embedder]:
2e1b2e7260/components/constellation/constellation.rs (L1701)

Testing: Communication between Script and Embedder is extensive, so this
should be covered by existing tests.

Signed-off-by: Jonathan Schwender <schwenderjonathan@gmail.com>
This commit is contained in:
Jonathan Schwender 2025-09-02 08:33:44 +02:00 committed by GitHub
parent 97c8c83cbb
commit f4dd2960b8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 120 additions and 113 deletions

View file

@ -17,9 +17,9 @@ use canvas_traits::canvas::{CanvasId, CanvasMsg};
use compositing_traits::CrossProcessCompositorApi;
use devtools_traits::{DevtoolScriptControlMsg, ScriptToDevtoolsControlMsg, WorkerId};
use embedder_traits::{
AnimationState, EmbedderMsg, FocusSequenceNumber, JSValue, JavaScriptEvaluationError,
JavaScriptEvaluationId, MediaSessionEvent, Theme, TouchEventResult, ViewportDetails,
WebDriverMessageId,
AnimationState, FocusSequenceNumber, JSValue, JavaScriptEvaluationError,
JavaScriptEvaluationId, MediaSessionEvent, ScriptToEmbedderChan, Theme, TouchEventResult,
ViewportDetails, WebDriverMessageId,
};
use euclid::default::Size2D as UntypedSize2D;
use fonts_traits::SystemFontServiceProxySender;
@ -444,6 +444,8 @@ pub struct WorkerGlobalScopeInit {
pub from_devtools_sender: Option<IpcSender<DevtoolScriptControlMsg>>,
/// Messages to send to constellation
pub script_to_constellation_chan: ScriptToConstellationChan,
/// Messages to send to the Embedder
pub script_to_embedder_chan: ScriptToEmbedderChan,
/// The worker id
pub worker_id: WorkerId,
/// The pipeline id
@ -525,8 +527,6 @@ pub enum ScriptToConstellationMessage {
/// Broadcast a message to all same-origin broadcast channels,
/// excluding the source of the broadcast.
ScheduleBroadcast(BroadcastChannelRouterId, BroadcastChannelMsg),
/// Forward a message to the embedder.
ForwardToEmbedder(EmbedderMsg),
/// Broadcast a storage event to every same-origin pipeline.
/// The strings are key, old value and new value.
BroadcastStorageEvent(

View file

@ -21,7 +21,7 @@ use std::ops::Range;
use std::path::PathBuf;
use std::sync::Arc;
use base::generic_channel::GenericSender;
use base::generic_channel::{GenericCallback, GenericSender, SendResult};
use base::id::{PipelineId, WebViewId};
use crossbeam_channel::Sender;
use euclid::{Point2D, Scale, Size2D};
@ -1081,3 +1081,34 @@ pub struct RgbColor {
pub green: u8,
pub blue: u8,
}
/// A Script to Embedder Channel
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
pub struct ScriptToEmbedderChan(GenericCallback<EmbedderMsg>);
impl ScriptToEmbedderChan {
/// Create a new Channel allowing script to send messages to the Embedder
pub fn new(
embedder_chan: Sender<EmbedderMsg>,
waker: Box<dyn EventLoopWaker>,
) -> ScriptToEmbedderChan {
let embedder_callback = GenericCallback::new(move |embedder_msg| {
let msg = match embedder_msg {
Ok(embedder_msg) => embedder_msg,
Err(err) => {
log::warn!("Script to Embedder message error: {err}");
return;
},
};
let _ = embedder_chan.send(msg);
waker.wake();
})
.expect("Failed to create channel");
ScriptToEmbedderChan(embedder_callback)
}
/// Send a message to and wake the Embedder
pub fn send(&self, msg: EmbedderMsg) -> SendResult {
self.0.send(msg)
}
}

View file

@ -44,3 +44,4 @@ stylo_traits = { workspace = true }
webgpu_traits = { workspace = true, optional = true }
webrender_api = { workspace = true }
webxr-api = { workspace = true, features = ["ipc"] }
log = "0.4.27"

View file

@ -30,7 +30,7 @@ use devtools_traits::ScriptToDevtoolsControlMsg;
use embedder_traits::user_content_manager::UserContentManager;
use embedder_traits::{
CompositorHitTestResult, FocusSequenceNumber, InputEvent, JavaScriptEvaluationId,
MediaSessionActionType, Theme, ViewportDetails, WebDriverScriptCommand,
MediaSessionActionType, ScriptToEmbedderChan, Theme, ViewportDetails, WebDriverScriptCommand,
};
use euclid::{Rect, Scale, Size2D, UnknownUnit};
use ipc_channel::ipc::{IpcReceiver, IpcSender};
@ -321,6 +321,9 @@ pub struct InitialScriptState {
pub constellation_receiver: GenericReceiver<ScriptThreadMessage>,
/// A channel on which messages can be sent to the constellation from script.
pub pipeline_to_constellation_sender: ScriptToConstellationChan,
/// A channel which allows script to send messages directly to the Embedder
/// This will pump the embedder event loop.
pub pipeline_to_embedder_sender: ScriptToEmbedderChan,
/// A handle to register script-(and associated layout-)threads for hang monitoring.
pub background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
/// A channel to the resource manager thread.