mirror of
https://github.com/lexmount/moli.git
synced 2026-11-18 16:08:37 +00:00
fix(files): prepare shared directory selections off the protocol thread
This commit is contained in:
@@ -32,6 +32,27 @@ impl PageDocumentCommandTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The original Page/DevToolsSession admission, held without a Page borrow
|
||||
/// while Browser work runs. Dispatch never resolves a replacement active Page.
|
||||
pub struct PreparedNativeCall {
|
||||
target: moli_renderer_v8::RendererPageProtocolCommandTarget,
|
||||
attachment: RendererAgentAttachmentId,
|
||||
session: Option<String>,
|
||||
response: moli_renderer_v8::RendererNativeCommandAdmission,
|
||||
}
|
||||
|
||||
impl PreparedNativeCall {
|
||||
pub fn start(self, operation: crate::RendererNativeOperation) -> Result<PendingPageCommand> {
|
||||
let mut command = RendererPageCommand::Native(self.response.bind(operation));
|
||||
command.bind_inspector_attachment(self.attachment);
|
||||
let pending = self.target.enqueue(command, self.session)?;
|
||||
Ok(PendingPageCommand {
|
||||
pending,
|
||||
renderer_agent_attachment_id: Some(self.attachment),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PendingPageCommand {
|
||||
pending: RendererPageCommandPending,
|
||||
renderer_agent_attachment_id: Option<RendererAgentAttachmentId>,
|
||||
@@ -210,6 +231,33 @@ impl CompletedPageCommand {
|
||||
}
|
||||
|
||||
impl Page {
|
||||
pub fn prepare_cdp_call(
|
||||
&self,
|
||||
command_id: u64,
|
||||
frontend_session_id: Option<&str>,
|
||||
) -> Result<(
|
||||
PreparedNativeCall,
|
||||
crate::RendererNativeCommandResponseGuard,
|
||||
)> {
|
||||
let attachment = self.renderer_agent_attachment_id.ok_or_else(|| {
|
||||
anyhow::anyhow!("native frontend command requires a renderer attachment")
|
||||
})?;
|
||||
let (response, guard) = crate::RendererCdpCall::reserve(
|
||||
moli_page_types::FrontendCommandId::new(command_id),
|
||||
moli_page_types::DevToolsSessionKey::from_wire_session_id(frontend_session_id),
|
||||
attachment,
|
||||
);
|
||||
Ok((
|
||||
PreparedNativeCall {
|
||||
target: self.handle.protocol_command_target(),
|
||||
attachment,
|
||||
session: self.renderer_devtools_command_session_id.clone(),
|
||||
response,
|
||||
},
|
||||
guard,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn document_command_target(
|
||||
&self,
|
||||
document: crate::RendererDocumentLifecycleIdentity,
|
||||
|
||||
@@ -42,6 +42,7 @@ pub use command_dispatch::{
|
||||
CompletedDevToolsIoCommandDispatch, CompletedPageCommand,
|
||||
CompletedRuntimeInspectorCommandDispatch, PageDocumentCommandTarget,
|
||||
PendingDevToolsIoCommandDispatch, PendingPageCommand, PendingRuntimeInspectorCommandDispatch,
|
||||
PreparedNativeCall,
|
||||
};
|
||||
pub use moli_renderer_v8::RendererPageRequestPolicyUpdate;
|
||||
|
||||
|
||||
@@ -2050,19 +2050,8 @@ impl Page {
|
||||
PendingPageCommand,
|
||||
crate::RendererNativeCommandResponseGuard,
|
||||
)> {
|
||||
let attachment = self.renderer_agent_attachment_id.ok_or_else(|| {
|
||||
anyhow::anyhow!("native frontend command requires a renderer attachment")
|
||||
})?;
|
||||
let (command, guard) = crate::RendererCdpCall::new(
|
||||
moli_page_types::FrontendCommandId::new(command_id),
|
||||
moli_page_types::DevToolsSessionKey::from_wire_session_id(frontend_session_id),
|
||||
attachment,
|
||||
operation,
|
||||
);
|
||||
Ok((
|
||||
self.start_page_command(RendererPageCommand::Native(command))?,
|
||||
guard,
|
||||
))
|
||||
let (admission, guard) = self.prepare_cdp_call(command_id, frontend_session_id)?;
|
||||
Ok((admission.start(operation)?, guard))
|
||||
}
|
||||
|
||||
pub fn finish_child_frame_tree_snapshot(
|
||||
|
||||
@@ -10,8 +10,14 @@ pub type BlobReadCompletion = Box<dyn FnOnce(io::Result<Vec<u8>>) + Send>;
|
||||
|
||||
/// An immutable byte source. Implementations perform I/O on their owning
|
||||
/// backend, then complete the read without entering a JavaScript context.
|
||||
pub trait BlobSource: fmt::Debug + Send + Sync + 'static {
|
||||
pub trait BlobSource: fmt::Debug + Send + Sync + std::any::Any {
|
||||
fn read(&self, range: Range<usize>, complete: BlobReadCompletion);
|
||||
|
||||
/// Compare backend snapshot identities without reading bytes. Unknown
|
||||
/// sources retain allocation identity; implementations must be symmetric.
|
||||
fn same_snapshot(&self, _other: &dyn BlobSource) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Blob data is immutable. Slices and concatenation retain their source rather
|
||||
@@ -43,9 +49,12 @@ impl PartialEq for BlobData {
|
||||
match (self.as_bytes(), other.as_bytes()) {
|
||||
(Some(left), Some(right)) => left == right,
|
||||
_ => {
|
||||
Arc::ptr_eq(&self.backing, &other.backing)
|
||||
&& self.offset == other.offset
|
||||
self.offset == other.offset
|
||||
&& self.length == other.length
|
||||
&& (Arc::ptr_eq(&self.backing, &other.backing)
|
||||
|| matches!((self.backing.as_ref(), other.backing.as_ref()),
|
||||
(Backing::Source(left), Backing::Source(right))
|
||||
if Arc::ptr_eq(left, right) || left.same_snapshot(right.as_ref())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ pub(super) async fn start_bidi_input_command(
|
||||
));
|
||||
}
|
||||
};
|
||||
let files = match selected_files_from_paths(&paths, "input.setFiles") {
|
||||
let files = match selected_files_from_paths(&paths).await {
|
||||
Ok(files) => files,
|
||||
Err(error) => return failed(bidi_response_from_devtools_error(dispatch.id, error)),
|
||||
};
|
||||
|
||||
@@ -4616,7 +4616,8 @@ async fn webdriver_classic_send_file_input_keys(
|
||||
"the element can not hold multiple files",
|
||||
));
|
||||
}
|
||||
let files = selected_files_from_paths(&paths, "WebDriver Classic file upload")
|
||||
let files = selected_files_from_paths(&paths)
|
||||
.await
|
||||
.map_err(|error| ClassicError::new(ClassicErrorCode::InvalidArgument, error.message))?;
|
||||
let object_id = resolve_classic_remote_object(
|
||||
binding,
|
||||
|
||||
@@ -15,60 +15,14 @@ const MAX_UPLOAD_ZIP_ARCHIVE_BYTES: usize = MAX_UPLOAD_BYTES + 1024 * 1024;
|
||||
const MAX_UPLOAD_BASE64_CHARS: usize = MAX_UPLOAD_ZIP_ARCHIVE_BYTES.div_ceil(3) * 4;
|
||||
const MAX_DOWNLOAD_BYTES: usize = 50 * 1024 * 1024;
|
||||
|
||||
pub(super) fn selected_files_from_paths(
|
||||
pub(super) async fn selected_files_from_paths(
|
||||
paths: &[String],
|
||||
label: &str,
|
||||
) -> Result<Vec<SelectedFile>, DevToolsError> {
|
||||
paths
|
||||
.iter()
|
||||
.map(|path| selected_file_from_path(path, label))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn selected_file_from_path(path: &str, label: &str) -> Result<SelectedFile, DevToolsError> {
|
||||
let file_path = Path::new(path);
|
||||
let metadata = fs::metadata(file_path).map_err(|_| {
|
||||
DevToolsError::new(
|
||||
DevToolsErrorKind::UnableToSetFileInput,
|
||||
format!("File not found : {path}"),
|
||||
)
|
||||
})?;
|
||||
if !metadata.is_file() {
|
||||
return Err(DevToolsError::new(
|
||||
DevToolsErrorKind::UnableToSetFileInput,
|
||||
format!("File not found : {path}"),
|
||||
));
|
||||
}
|
||||
let bytes = fs::read(file_path).map_err(|error| {
|
||||
DevToolsError::new(
|
||||
DevToolsErrorKind::UnableToSetFileInput,
|
||||
format!("could not read file for {label}: {error}"),
|
||||
)
|
||||
})?;
|
||||
let name = file_path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or(path)
|
||||
.to_owned();
|
||||
let last_modified = metadata
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|duration| duration.as_millis() as f64)
|
||||
.unwrap_or_else(|| {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|duration| duration.as_millis() as f64)
|
||||
.unwrap_or(0.0)
|
||||
});
|
||||
Ok(SelectedFile {
|
||||
relative_path: String::new(),
|
||||
data: bytes.into(),
|
||||
mime_type: String::new(),
|
||||
name,
|
||||
last_modified,
|
||||
})
|
||||
moli_protocol::file_upload::selected_files_from_paths_async(paths.to_vec())
|
||||
.await
|
||||
.map_err(|error| {
|
||||
DevToolsError::new(DevToolsErrorKind::UnableToSetFileInput, error.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn uploaded_file_from_base64_zip(
|
||||
|
||||
@@ -40,6 +40,9 @@ pub(crate) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<Nativ
|
||||
"DOM agent hasn't been enabled",
|
||||
)));
|
||||
}
|
||||
if action == DomAction::SetFileInputFiles {
|
||||
return Some(files::try_start(conn, cmd));
|
||||
}
|
||||
match prepare(conn, cmd, action) {
|
||||
Ok(Some(operation)) => Some(native::start_operation(conn, cmd, operation)),
|
||||
Ok(None) => None,
|
||||
@@ -58,9 +61,6 @@ fn prepare(
|
||||
if action == DomAction::ResolveNode {
|
||||
return remote_object::prepare(conn, cmd).map(Some);
|
||||
}
|
||||
if action == DomAction::SetFileInputFiles {
|
||||
return files::prepare(conn, cmd).map(Some);
|
||||
}
|
||||
if let Some(operation) = mutation::prepare(conn, cmd, action)? {
|
||||
return Ok(Some(operation));
|
||||
}
|
||||
|
||||
@@ -1,62 +1,87 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn prepare(conn: &CdpConnection, cmd: &Cmd<'_>) -> Result<Operation, StartError> {
|
||||
enum FileInputTarget {
|
||||
ObjectId(String),
|
||||
Node(DevToolsDomNodeReference),
|
||||
}
|
||||
|
||||
pub(super) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> NativeCommandStep {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Params {
|
||||
#[serde(flatten)]
|
||||
reference: NodeReferenceParams,
|
||||
files: Vec<String>,
|
||||
}
|
||||
let params: Params = cmd
|
||||
.get_params()
|
||||
.ok()
|
||||
.flatten()
|
||||
.ok_or_else(StartError::invalid_params)?;
|
||||
let params: Params = match cmd.get_params().ok().flatten() {
|
||||
Some(params) => params,
|
||||
None => {
|
||||
return NativeCommandStep::Complete(CommandOutputPlan::error(-32602, "InvalidParams"));
|
||||
}
|
||||
};
|
||||
let owner = CommandOwnerScope::capture(conn, cmd.session_id);
|
||||
let session = conn.target_renderer_runtime_inspector_session_id_for_owner(&owner);
|
||||
// File access belongs to Browser admission. For node ids, retain an error
|
||||
// until the renderer preflight has succeeded, preserving node-error priority.
|
||||
let files = crate::domains::dom::set_file_input::selected_files_from_paths(¶ms.files);
|
||||
if let Some(object_id) = params.reference.object_id {
|
||||
let object_id = dom_object_reference_id_for_owner(
|
||||
let target = if let Some(object_id) = params.reference.object_id {
|
||||
FileInputTarget::ObjectId(dom_object_reference_id_for_owner(
|
||||
conn,
|
||||
&owner,
|
||||
&DevToolsRemoteHandleId::from(object_id),
|
||||
);
|
||||
return Ok(Operation::new(
|
||||
Command::set_file_input_files_for_object_id(session, object_id, files?, false),
|
||||
project,
|
||||
));
|
||||
}
|
||||
let reference = devtools_node_reference_from_ids(
|
||||
params.reference.node_id,
|
||||
params.reference.backend_node_id,
|
||||
)
|
||||
.ok_or_else(StartError::invalid_params)?;
|
||||
Ok(with_backend(session, reference, move |backend_node_id| {
|
||||
Operation::then(
|
||||
Command::DocumentNodeExistsForBackendNodeId { backend_node_id },
|
||||
move |reply| match reply {
|
||||
Ok(Reply::Bool(true)) => match files {
|
||||
Ok(files) => Step::Continue(Operation::new(
|
||||
Command::SetFileInputFilesForBackendNodeId {
|
||||
backend_node_id,
|
||||
files,
|
||||
append: false,
|
||||
))
|
||||
} else {
|
||||
let Some(reference) = devtools_node_reference_from_ids(
|
||||
params.reference.node_id,
|
||||
params.reference.backend_node_id,
|
||||
) else {
|
||||
return NativeCommandStep::Complete(CommandOutputPlan::error(-32602, "InvalidParams"));
|
||||
};
|
||||
FileInputTarget::Node(reference)
|
||||
};
|
||||
native::start_prepared_operation(conn, cmd, async move {
|
||||
let files = crate::file_upload::selected_files_from_paths_async(params.files)
|
||||
.await
|
||||
.map_err(|error| StartError {
|
||||
code: -32000,
|
||||
message: error.to_string(),
|
||||
});
|
||||
// Retain the result until the node preflight succeeds, so a bad node
|
||||
// keeps precedence over a bad path. No filesystem work enters a Page.
|
||||
match target {
|
||||
FileInputTarget::ObjectId(object_id) => {
|
||||
let files = files.map_err(|error| anyhow::anyhow!(error.message))?;
|
||||
Ok(Operation::new(
|
||||
Command::set_file_input_files_for_object_id(session, object_id, files, false),
|
||||
project,
|
||||
))
|
||||
}
|
||||
FileInputTarget::Node(reference) => {
|
||||
Ok(with_backend(session, reference, move |backend_node_id| {
|
||||
Operation::then(
|
||||
Command::DocumentNodeExistsForBackendNodeId { backend_node_id },
|
||||
move |reply| match reply {
|
||||
Ok(Reply::Bool(true)) => match files {
|
||||
Ok(files) => Step::Continue(Operation::new(
|
||||
Command::SetFileInputFilesForBackendNodeId {
|
||||
backend_node_id,
|
||||
files,
|
||||
append: false,
|
||||
},
|
||||
project,
|
||||
)),
|
||||
Err(error) => {
|
||||
Step::Complete(Response::error(error.code, error.message))
|
||||
}
|
||||
},
|
||||
Ok(Reply::Bool(false)) => Step::Complete(node_not_found()),
|
||||
Err(error) => Step::Complete(Response::error(
|
||||
-32000,
|
||||
format!("Could not preflight file input node: {error}"),
|
||||
)),
|
||||
_ => unreachable!("DOM file input preflight reply"),
|
||||
},
|
||||
project,
|
||||
)),
|
||||
Err(error) => Step::Complete(Response::error(error.code, error.message)),
|
||||
},
|
||||
Ok(Reply::Bool(false)) => Step::Complete(node_not_found()),
|
||||
Err(error) => Step::Complete(Response::error(
|
||||
-32000,
|
||||
format!("Could not preflight file input node: {error}"),
|
||||
)),
|
||||
_ => unreachable!("DOM file input preflight reply"),
|
||||
},
|
||||
)
|
||||
}))
|
||||
)
|
||||
}))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn project(reply: anyhow::Result<Reply>) -> Response {
|
||||
|
||||
@@ -152,6 +152,40 @@ impl PendingNativeCommand {
|
||||
}
|
||||
}
|
||||
|
||||
fn new_prepared(
|
||||
command_id: u64,
|
||||
session_id: Option<String>,
|
||||
residence: TargetPageResidenceIdentity,
|
||||
admission: moli_core::page::PreparedNativeCall,
|
||||
guard: RendererNativeCommandResponseGuard,
|
||||
prepare: impl std::future::Future<Output = Result<moli_core::RendererNativeOperation>> + 'static,
|
||||
) -> Self {
|
||||
let scope = NativeCommandFailureCleanup::new(command_id, session_id, guard);
|
||||
let wait = scope.clone();
|
||||
let cancellation = scope.wait_cancellation();
|
||||
Self {
|
||||
scope,
|
||||
pending: async move {
|
||||
let operation = match prepare.await {
|
||||
Ok(operation) => operation,
|
||||
Err(error) => {
|
||||
drop(admission);
|
||||
return wait.settle(Err(error), residence).await;
|
||||
}
|
||||
};
|
||||
let completed = match admission.start(operation) {
|
||||
Ok(pending) => pending.wait().await,
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
wait.settle(completed, residence).await
|
||||
}
|
||||
.boxed_local(),
|
||||
unpublished_failure: None,
|
||||
recovering: false,
|
||||
_cancellation: cancellation,
|
||||
}
|
||||
}
|
||||
|
||||
/// Browser policy may outlive a rejected old attachment. This projection
|
||||
/// only runs after publication lost; it cannot replace a committed reply.
|
||||
pub(crate) fn on_unpublished_failure(
|
||||
@@ -250,17 +284,13 @@ pub(crate) fn start_operation(
|
||||
cmd: &Cmd<'_>,
|
||||
operation: moli_core::RendererNativeOperation,
|
||||
) -> NativeCommandStep {
|
||||
let owner = CommandOwnerScope::capture(conn, cmd.session_id);
|
||||
let Some(residence) = conn.target_page_residence_identity_for_owner(&owner) else {
|
||||
return NativeCommandStep::Complete(CommandOutputPlan::error(-32000, "NoDocumentLoaded"));
|
||||
};
|
||||
let page = match conn.loaded_page_mut_for_protocol_access_for_owner(&owner) {
|
||||
Ok(page) => page,
|
||||
Err(error) => return NativeCommandStep::Complete(CommandOutputPlan::error(-32000, error)),
|
||||
let (residence, admission, guard) = match reserve_call(conn, cmd) {
|
||||
Ok(admission) => admission,
|
||||
Err(plan) => return NativeCommandStep::Complete(plan),
|
||||
};
|
||||
let command_id = cmd.id.expect("a native frontend command has a call id");
|
||||
match page.start_cdp_call(command_id, cmd.session_id, operation) {
|
||||
Ok((pending, guard)) => NativeCommandStep::Pending(PendingNativeCommand::new(
|
||||
match admission.start(operation) {
|
||||
Ok(pending) => NativeCommandStep::Pending(PendingNativeCommand::new(
|
||||
command_id,
|
||||
cmd.session_id.map(str::to_owned),
|
||||
residence,
|
||||
@@ -273,6 +303,52 @@ pub(crate) fn start_operation(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn start_prepared_operation(
|
||||
conn: &mut CdpConnection,
|
||||
cmd: &Cmd<'_>,
|
||||
prepare: impl std::future::Future<Output = Result<moli_core::RendererNativeOperation>> + 'static,
|
||||
) -> NativeCommandStep {
|
||||
let (residence, admission, guard) = match reserve_call(conn, cmd) {
|
||||
Ok(admission) => admission,
|
||||
Err(plan) => return NativeCommandStep::Complete(plan),
|
||||
};
|
||||
NativeCommandStep::Pending(PendingNativeCommand::new_prepared(
|
||||
cmd.id.expect("a native frontend command has a call id"),
|
||||
cmd.session_id.map(str::to_owned),
|
||||
residence,
|
||||
admission,
|
||||
guard,
|
||||
prepare,
|
||||
))
|
||||
}
|
||||
|
||||
fn reserve_call(
|
||||
conn: &mut CdpConnection,
|
||||
cmd: &Cmd<'_>,
|
||||
) -> Result<
|
||||
(
|
||||
TargetPageResidenceIdentity,
|
||||
moli_core::page::PreparedNativeCall,
|
||||
RendererNativeCommandResponseGuard,
|
||||
),
|
||||
CommandOutputPlan,
|
||||
> {
|
||||
let owner = CommandOwnerScope::capture(conn, cmd.session_id);
|
||||
let residence = conn
|
||||
.target_page_residence_identity_for_owner(&owner)
|
||||
.ok_or_else(|| CommandOutputPlan::error(-32000, "NoDocumentLoaded"))?;
|
||||
let page = conn
|
||||
.loaded_page_mut_for_protocol_access_for_owner(&owner)
|
||||
.map_err(|error| CommandOutputPlan::error(-32000, error))?;
|
||||
let (admission, guard) = page
|
||||
.prepare_cdp_call(
|
||||
cmd.id.expect("a native frontend command has a call id"),
|
||||
cmd.session_id,
|
||||
)
|
||||
.map_err(|error| CommandOutputPlan::error(-32000, error.to_string()))?;
|
||||
Ok((residence, admission, guard))
|
||||
}
|
||||
|
||||
/// Admit only frontend calls with an accessible document and renderer.
|
||||
/// Return the checked attachment so preparation can retain its replay identity.
|
||||
/// Enqueue revalidates access after preparation, which may update Browser policy.
|
||||
@@ -748,4 +824,148 @@ mod tests {
|
||||
assert_eq!(terminal["result"]["nodeId"], 7);
|
||||
assert!(events.next().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_browser_preparation_yields_and_does_not_retarget_a_replacement_page() {
|
||||
use crate::conn::BrowserContext;
|
||||
use crate::testing::TestContext;
|
||||
use futures_util::poll;
|
||||
for retire in [false, true] {
|
||||
let mut context = TestContext::new();
|
||||
let mut browser = BrowserContext::new("BID-native-preparation".into());
|
||||
browser.set_active_target_id("TID-native-preparation");
|
||||
context.with_fixture(|conn| conn.install_browser_context_fixture_for_test(browser));
|
||||
context
|
||||
.install_navigation_fixture_for_session_owner("about:blank", None)
|
||||
.await;
|
||||
let (residence, admission, guard) = context.with_fixture(|conn| {
|
||||
let owner = CommandOwnerScope::capture(conn, None);
|
||||
let residence = conn
|
||||
.target_page_residence_identity_for_owner(&owner)
|
||||
.unwrap();
|
||||
let (admission, guard) = conn
|
||||
.loaded_page_mut_for_protocol_access(None)
|
||||
.unwrap()
|
||||
.prepare_cdp_call(871, None)
|
||||
.unwrap();
|
||||
(residence, admission, guard)
|
||||
});
|
||||
let (release, held) = tokio::sync::oneshot::channel();
|
||||
let pending = PendingNativeCommand::new_prepared(
|
||||
871,
|
||||
None,
|
||||
residence,
|
||||
admission,
|
||||
guard,
|
||||
async move {
|
||||
held.await?;
|
||||
Ok(moli_core::RendererNativeOperation::new(
|
||||
RendererPageCommand::ChildFrameTreeSnapshot,
|
||||
|_| RendererNativeProtocolResponse::success(json!({"prepared":true})),
|
||||
))
|
||||
},
|
||||
);
|
||||
let mut pending = Box::pin(pending.wait());
|
||||
assert!(poll!(pending.as_mut()).is_pending());
|
||||
context.process_async(json!({"id":872,"method":"Runtime.evaluate","params":{"expression":"6 * 7","returnByValue":true}})).await;
|
||||
assert!(
|
||||
context
|
||||
.sent
|
||||
.iter()
|
||||
.any(|message| message["id"] == 872
|
||||
&& message["result"]["result"]["value"] == 42),
|
||||
"Browser preparation must not hold protocol or renderer execution"
|
||||
);
|
||||
if retire {
|
||||
context
|
||||
.install_navigation_fixture_for_session_owner(
|
||||
"data:text/html,retained replacement",
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
release.send(()).unwrap();
|
||||
let completed = tokio::time::timeout(std::time::Duration::from_secs(5), pending)
|
||||
.await
|
||||
.unwrap();
|
||||
if retire {
|
||||
assert!(
|
||||
matches!(completed.result, NativeCommandCompletion::Unpublished(_)),
|
||||
"old admission must not publish from the replacement Page"
|
||||
);
|
||||
} else {
|
||||
let NativeCommandCompletion::Page { completed, .. } = completed.result else {
|
||||
panic!("prepared Native command must settle normally")
|
||||
};
|
||||
assert!(
|
||||
completed
|
||||
.into_output()
|
||||
.completion()
|
||||
.native_response_was_published()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_native_browser_preparation_cancels_before_enqueue() {
|
||||
use crate::conn::BrowserContext;
|
||||
use crate::testing::TestContext;
|
||||
use futures_util::poll;
|
||||
let mut context = TestContext::new();
|
||||
let mut browser = BrowserContext::new("BID-native-preparation-drop".into());
|
||||
browser.set_active_target_id("TID-native-preparation-drop");
|
||||
context.with_fixture(|conn| conn.install_browser_context_fixture_for_test(browser));
|
||||
context
|
||||
.install_navigation_fixture_for_session_owner("about:blank", None)
|
||||
.await;
|
||||
let (residence, admission, guard) = context.with_fixture(|conn| {
|
||||
let owner = CommandOwnerScope::capture(conn, None);
|
||||
let residence = conn
|
||||
.target_page_residence_identity_for_owner(&owner)
|
||||
.unwrap();
|
||||
let (admission, guard) = conn
|
||||
.loaded_page_mut_for_protocol_access(None)
|
||||
.unwrap()
|
||||
.prepare_cdp_call(873, None)
|
||||
.unwrap();
|
||||
(residence, admission, guard)
|
||||
});
|
||||
let (release, held) = tokio::sync::oneshot::channel::<()>();
|
||||
let pending = PendingNativeCommand::new_prepared(
|
||||
873,
|
||||
None,
|
||||
residence,
|
||||
admission,
|
||||
guard,
|
||||
async move {
|
||||
held.await?;
|
||||
Ok(moli_core::RendererNativeOperation::new(
|
||||
RendererPageCommand::ChildFrameTreeSnapshot,
|
||||
|_| RendererNativeProtocolResponse::success(json!({})),
|
||||
))
|
||||
},
|
||||
);
|
||||
let cleanup = pending.scope.clone();
|
||||
let mut waiting = Box::pin(pending.wait());
|
||||
assert!(poll!(waiting.as_mut()).is_pending());
|
||||
drop(waiting);
|
||||
assert!(
|
||||
release.send(()).is_err(),
|
||||
"cancelled Browser work must not resume and enqueue"
|
||||
);
|
||||
let completed = cleanup
|
||||
.recover(CommandOutputPlan::error(-32000, "cancelled preparation"))
|
||||
.wait()
|
||||
.await;
|
||||
let mut dispatch = CommandDispatchContext::default();
|
||||
let plan = context.with_fixture(|conn| completed.complete(conn, &mut dispatch));
|
||||
assert!(dispatch.take_renderer_output_predecessor().is_none());
|
||||
let mut messages = Vec::new();
|
||||
plan.emit_into(&mut messages, Some(873), None);
|
||||
assert_eq!(
|
||||
messages,
|
||||
vec![json!({"id":873,"error":{"code":-32000,"message":"cancelled preparation"}})]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +69,13 @@ impl Drop for ReadReply {
|
||||
}
|
||||
|
||||
impl BlobSource for FileSource {
|
||||
fn same_snapshot(&self, other: &dyn BlobSource) -> bool {
|
||||
let other: &dyn std::any::Any = other;
|
||||
other.downcast_ref::<Self>().is_some_and(|other| {
|
||||
self.path == other.path && self.size == other.size && self.modified == other.modified
|
||||
})
|
||||
}
|
||||
|
||||
fn read(&self, range: Range<usize>, complete: BlobReadCompletion) {
|
||||
let source = self.clone();
|
||||
let reply = ReadReply(Some(complete));
|
||||
@@ -83,6 +90,45 @@ impl BlobSource for FileSource {
|
||||
/// directory is enumerated in stable order; links below it are not traversed.
|
||||
/// An explicitly selected directory link retains its chosen display name.
|
||||
pub fn selected_files_from_paths(paths: &[String]) -> io::Result<Vec<SelectedFile>> {
|
||||
select_files(paths, None)
|
||||
}
|
||||
|
||||
struct SelectionCancellation(Arc<std::sync::atomic::AtomicBool>);
|
||||
impl Drop for SelectionCancellation {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Browser filesystem admission runs outside protocol and renderer turns. A
|
||||
/// dropped caller stops the enumeration at its next filesystem entry boundary.
|
||||
pub async fn selected_files_from_paths_async(paths: Vec<String>) -> io::Result<Vec<SelectedFile>> {
|
||||
if paths.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let _cancel = SelectionCancellation(cancelled.clone());
|
||||
tokio::task::spawn_blocking(move || select_files(&paths, Some(&cancelled)))
|
||||
.await
|
||||
.map_err(io::Error::other)?
|
||||
}
|
||||
|
||||
fn check_selection_cancelled(cancelled: Option<&std::sync::atomic::AtomicBool>) -> io::Result<()> {
|
||||
if cancelled.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Relaxed)) {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"File selection cancelled",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn select_files(
|
||||
paths: &[String],
|
||||
cancelled: Option<&std::sync::atomic::AtomicBool>,
|
||||
) -> io::Result<Vec<SelectedFile>> {
|
||||
check_selection_cancelled(cancelled)?;
|
||||
if paths.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
@@ -97,6 +143,7 @@ pub fn selected_files_from_paths(paths: &[String]) -> io::Result<Vec<SelectedFil
|
||||
let mut files = Vec::new();
|
||||
while let Some(directory) = directories.pop() {
|
||||
for entry in fs::read_dir(directory)? {
|
||||
check_selection_cancelled(cancelled)?;
|
||||
let entry = entry?;
|
||||
let kind = entry.file_type()?;
|
||||
if kind.is_dir() {
|
||||
@@ -110,6 +157,7 @@ pub fn selected_files_from_paths(paths: &[String]) -> io::Result<Vec<SelectedFil
|
||||
return files
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
check_selection_cancelled(cancelled)?;
|
||||
let mut file = selected_file_from_file_path(&path, &runtime)?;
|
||||
file.relative_path = upload_relative_path(&root, &path);
|
||||
Ok(file)
|
||||
@@ -118,7 +166,10 @@ pub fn selected_files_from_paths(paths: &[String]) -> io::Result<Vec<SelectedFil
|
||||
}
|
||||
paths
|
||||
.iter()
|
||||
.map(|path| selected_file_from_file_path(Path::new(path), &runtime))
|
||||
.map(|path| {
|
||||
check_selection_cancelled(cancelled)?;
|
||||
selected_file_from_file_path(Path::new(path), &runtime)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -344,6 +395,18 @@ mod backing_tests {
|
||||
let path = directory.0.join("file.txt");
|
||||
fs::write(&path, b"abcdef").unwrap();
|
||||
let selected = selected_files_from_paths(&[path.to_string_lossy().into_owned()]).unwrap();
|
||||
let reselected = selected_files_from_paths(&[path.to_string_lossy().into_owned()]).unwrap();
|
||||
assert_eq!(
|
||||
selected, reselected,
|
||||
"same snapshot selection emits cancel, not change"
|
||||
);
|
||||
let other = directory.0.join("same-bytes.txt");
|
||||
fs::copy(&path, &other).unwrap();
|
||||
let other = selected_files_from_paths(&[other.to_string_lossy().into_owned()]).unwrap();
|
||||
assert_ne!(
|
||||
selected[0].data, other[0].data,
|
||||
"different disk files retain different identities"
|
||||
);
|
||||
let data = selected[0].data.clone();
|
||||
assert!(
|
||||
data.as_bytes().is_none(),
|
||||
@@ -407,4 +470,14 @@ mod backing_tests {
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_selection_stops_before_filesystem_admission() {
|
||||
let cancelled = std::sync::atomic::AtomicBool::new(true);
|
||||
let result = select_files(
|
||||
&["missing-file-must-not-be-inspected".into()],
|
||||
Some(&cancelled),
|
||||
);
|
||||
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,9 +289,9 @@ pub use runtime::{
|
||||
RendererLifecycleTerminationStamp, RendererMainDocumentCommit, RendererMainDocumentResource,
|
||||
RendererMarkdownOptions, RendererMoliDomMemoryDiagnostics, RendererMoliMemoryDiagnostics,
|
||||
RendererMoliMemoryScopeDiagnostics, RendererMoliRuntimeMemoryDiagnostics,
|
||||
RendererNativeCommandReadyResponse, RendererNativeCommandResponseGuard,
|
||||
RendererNativeCommandTerminal, RendererNativeOperation, RendererNativeOperationStep,
|
||||
RendererNativeProtocolError, RendererNativeProtocolNotification,
|
||||
RendererNativeCommandAdmission, RendererNativeCommandReadyResponse,
|
||||
RendererNativeCommandResponseGuard, RendererNativeCommandTerminal, RendererNativeOperation,
|
||||
RendererNativeOperationStep, RendererNativeProtocolError, RendererNativeProtocolNotification,
|
||||
RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate, RendererNavigationInitiator,
|
||||
RendererOutputCursor, RendererOutputFence, RendererOutputFenceLeaseId, RendererOutputItem,
|
||||
RendererOutputPublication, RendererOutputPublicationOrdering, RendererOutputRecord,
|
||||
@@ -305,7 +305,7 @@ pub use runtime::{
|
||||
RendererPageCommandPostResponseContinuation, RendererPageCookieFacadeSnapshotReply,
|
||||
RendererPageCreationArtifacts, RendererPageCreationDiagnostics, RendererPageCreationPhase,
|
||||
RendererPageCreationProgress, RendererPageDiagnosticsSnapshot, RendererPageHandle,
|
||||
RendererPageReplacementCommit, RendererPageReplacementError,
|
||||
RendererPageProtocolCommandTarget, RendererPageReplacementCommit, RendererPageReplacementError,
|
||||
RendererPageReplacementFailureDisposition, RendererPageReplacementReservationRequest,
|
||||
RendererPageReplacementTarget, RendererPageReply, RendererPageRequestPolicyUpdate,
|
||||
RendererPageReservationToken, RendererPageState, RendererPageStateRevision,
|
||||
|
||||
@@ -315,7 +315,7 @@ pub use self::owner_local::RendererPageReplacementCommit;
|
||||
pub use self::owner_local::RendererPageTestingHandle;
|
||||
pub use self::owner_local::{
|
||||
RendererDocumentCommandTarget, RendererPageAccessError, RendererPageCommandPending,
|
||||
RendererPageHandle, RendererPageRequestPolicyUpdate,
|
||||
RendererPageHandle, RendererPageProtocolCommandTarget, RendererPageRequestPolicyUpdate,
|
||||
RendererRuntimeInspectorSessionDetachGuard,
|
||||
};
|
||||
pub(crate) use self::owner_local_store::RendererPageToken;
|
||||
@@ -445,9 +445,10 @@ pub(in crate::runtime) use self::phase_one::{
|
||||
};
|
||||
pub(crate) use self::protocol_output::{PendingRendererOutputRecord, RendererTurnOutputJournal};
|
||||
pub use self::protocol_output::{
|
||||
RendererCdpCall, RendererDocumentTitleChanged, RendererNativeCommandReadyResponse,
|
||||
RendererNativeCommandResponseGuard, RendererNativeCommandTerminal, RendererNativeOperation,
|
||||
RendererNativeOperationStep, RendererNativeProtocolError, RendererNativeProtocolNotification,
|
||||
RendererCdpCall, RendererDocumentTitleChanged, RendererNativeCommandAdmission,
|
||||
RendererNativeCommandReadyResponse, RendererNativeCommandResponseGuard,
|
||||
RendererNativeCommandTerminal, RendererNativeOperation, RendererNativeOperationStep,
|
||||
RendererNativeProtocolError, RendererNativeProtocolNotification,
|
||||
RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate, RendererOutputCursor,
|
||||
RendererOutputFence, RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,
|
||||
RendererOutputPublicationOrdering, RendererOutputRecord, RendererOutputResidenceIdentity,
|
||||
|
||||
@@ -140,6 +140,38 @@ pub struct RendererPageHandle {
|
||||
_not_send: PhantomData<Rc<()>>,
|
||||
}
|
||||
|
||||
/// Revocable DevTools command destination for the exact admitted agent. It
|
||||
/// carries no Page close authority and cannot follow a replacement Document.
|
||||
pub struct RendererPageProtocolCommandTarget {
|
||||
token: RendererPageToken,
|
||||
agent: RendererDevToolsAgentToken,
|
||||
target: crate::devtools::target::RendererDevToolsTargetHandle,
|
||||
dialogs: RendererJavaScriptDialogBroker,
|
||||
}
|
||||
|
||||
impl RendererPageProtocolCommandTarget {
|
||||
pub fn enqueue(
|
||||
self,
|
||||
command: RendererPageCommand,
|
||||
session: Option<String>,
|
||||
) -> Result<RendererPageCommandPending> {
|
||||
let javascript_dialog_watch = command
|
||||
.interruptible_by_javascript_dialog()
|
||||
.then(|| self.dialogs.watch());
|
||||
let route = self.target.main_ref().enqueue_protocol_page_command(
|
||||
self.token,
|
||||
self.agent,
|
||||
command,
|
||||
session,
|
||||
RendererPageStateCapturePolicy::ProtocolTurn,
|
||||
);
|
||||
Ok(RendererPageCommandPending {
|
||||
dispatch: RendererPageCommandPendingDispatch::InspectorMain(Box::new(route)),
|
||||
javascript_dialog_watch,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, thiserror::Error)]
|
||||
pub enum RendererPageAccessError {
|
||||
#[error("Renderer Document is no longer current")]
|
||||
@@ -289,6 +321,15 @@ impl RendererPageHandle {
|
||||
.expect("renderer page handle should remain open while in use")
|
||||
}
|
||||
|
||||
pub fn protocol_command_target(&self) -> RendererPageProtocolCommandTarget {
|
||||
RendererPageProtocolCommandTarget {
|
||||
token: self.token(),
|
||||
agent: self.devtools_agent_token,
|
||||
target: self.devtools_target.clone(),
|
||||
dialogs: self.javascript_dialog_broker.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn document_command_target(
|
||||
&self,
|
||||
document: RendererDocumentLifecycleIdentity,
|
||||
|
||||
@@ -23,9 +23,9 @@ pub use item::{
|
||||
RendererProtocolObservation,
|
||||
};
|
||||
pub use native_response::{
|
||||
RendererCdpCall, RendererNativeCommandReadyResponse, RendererNativeCommandResponseGuard,
|
||||
RendererNativeCommandTerminal, RendererNativeOperation, RendererNativeOperationStep,
|
||||
RendererNativeProtocolError, RendererNativeProtocolNotification,
|
||||
RendererCdpCall, RendererNativeCommandAdmission, RendererNativeCommandReadyResponse,
|
||||
RendererNativeCommandResponseGuard, RendererNativeCommandTerminal, RendererNativeOperation,
|
||||
RendererNativeOperationStep, RendererNativeProtocolError, RendererNativeProtocolNotification,
|
||||
RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate,
|
||||
};
|
||||
pub use transport::{
|
||||
|
||||
@@ -88,13 +88,30 @@ struct RendererNativeCommandResponse {
|
||||
lease: Lease,
|
||||
}
|
||||
|
||||
/// Reserves only the original reply authority while Browser I/O prepares an
|
||||
/// operation. It does not occupy a renderer journal position or enter a Page.
|
||||
pub struct RendererNativeCommandAdmission {
|
||||
response: RendererNativeCommandResponse,
|
||||
}
|
||||
|
||||
impl RendererNativeCommandAdmission {
|
||||
pub fn bind(self, operation: RendererNativeOperation) -> RendererCdpCall {
|
||||
RendererCdpCall {
|
||||
operation,
|
||||
response: self.response,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RendererCdpCall {
|
||||
pub fn new(
|
||||
pub fn reserve(
|
||||
command_id: FrontendCommandId,
|
||||
session: DevToolsSessionKey,
|
||||
attachment_id: RendererAgentAttachmentId,
|
||||
operation: RendererNativeOperation,
|
||||
) -> (Self, RendererNativeCommandResponseGuard) {
|
||||
) -> (
|
||||
RendererNativeCommandAdmission,
|
||||
RendererNativeCommandResponseGuard,
|
||||
) {
|
||||
let authority = Authority::session();
|
||||
let lease = authority
|
||||
.activate()
|
||||
@@ -103,8 +120,7 @@ impl RendererCdpCall {
|
||||
.take_session_response_settlement_receiver()
|
||||
.expect("native frontend calls retain a publication receipt");
|
||||
(
|
||||
Self {
|
||||
operation,
|
||||
RendererNativeCommandAdmission {
|
||||
response: RendererNativeCommandResponse {
|
||||
command_id,
|
||||
session,
|
||||
@@ -118,6 +134,16 @@ impl RendererCdpCall {
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
command_id: FrontendCommandId,
|
||||
session: DevToolsSessionKey,
|
||||
attachment_id: RendererAgentAttachmentId,
|
||||
operation: RendererNativeOperation,
|
||||
) -> (Self, RendererNativeCommandResponseGuard) {
|
||||
let (admission, guard) = Self::reserve(command_id, session, attachment_id);
|
||||
(admission.bind(operation), guard)
|
||||
}
|
||||
}
|
||||
|
||||
/// Created by the native backend with fully resolved payload, then published
|
||||
|
||||
@@ -819,6 +819,43 @@ async def _run_bidi_input_smoke(
|
||||
"input:2,change:2",
|
||||
"BiDi input.setFiles event order",
|
||||
)
|
||||
chosen = Path(directory) / "chosen"
|
||||
(chosen / "nested").mkdir(parents=True)
|
||||
(chosen / "a.txt").write_text("alpha", encoding="utf-8")
|
||||
(chosen / "nested" / "b.txt").write_text("beta", encoding="utf-8")
|
||||
await _send(
|
||||
websocket, 191, "script.evaluate",
|
||||
{
|
||||
"expression": "const input = document.getElementById('bidi-upload'); input.multiple = false; input.webkitdirectory = true;",
|
||||
"target": {"context": context}, "awaitPromise": False,
|
||||
},
|
||||
)
|
||||
directory_setup = (await _recv_until_id(websocket, 191))[-1]
|
||||
assert_equal(directory_setup["type"], "success", "BiDi directory setup")
|
||||
await _send(
|
||||
websocket, 192, "input.setFiles",
|
||||
{"context": context, "element": {"sharedId": file_shared_id}, "files": [str(chosen)]},
|
||||
)
|
||||
directory_set = (await _recv_until_id(websocket, 192))[-1]
|
||||
assert_equal(directory_set["type"], "success", "BiDi directory upload")
|
||||
await _send(
|
||||
websocket, 193, "script.evaluate",
|
||||
{
|
||||
"expression": (
|
||||
"Promise.all(Array.from(document.getElementById('bidi-upload').files, "
|
||||
"async file => file.webkitRelativePath + ':' + await structuredClone(file).text()))"
|
||||
".then(values => values.sort().join('|'))"
|
||||
),
|
||||
"target": {"context": context}, "awaitPromise": True,
|
||||
},
|
||||
)
|
||||
directory_summary = (await _recv_until_id(websocket, 193))[-1]
|
||||
assert_equal(directory_summary["type"], "success", "BiDi directory summary")
|
||||
assert_equal(
|
||||
directory_summary["result"]["result"]["value"],
|
||||
"chosen/a.txt:alpha|chosen/nested/b.txt:beta",
|
||||
"BiDi directory relative paths and lazy clone bytes",
|
||||
)
|
||||
record(results, "bidi_input_set_files", {"context": context})
|
||||
|
||||
input_navigation_url = f"{fixture}/webdriver/input-navigation"
|
||||
|
||||
@@ -785,6 +785,39 @@ async def _run_file_upload_smoke(
|
||||
except WebDriverHttpError as error:
|
||||
assert_equal(error.response.status, 400, "Classic non-multiple upload HTTP status")
|
||||
assert_equal(error.response.body["value"]["error"], "invalid argument", "Classic non-multiple upload error")
|
||||
chosen = Path(tempdir) / "chosen"
|
||||
(chosen / "nested").mkdir(parents=True)
|
||||
(chosen / "a.txt").write_text("alpha", encoding="utf-8")
|
||||
(chosen / "nested" / "b.txt").write_text("beta", encoding="utf-8")
|
||||
client.post(
|
||||
f"/session/{session_id}/execute/sync",
|
||||
{
|
||||
"script": "const input = document.getElementById('upload-single'); input.webkitdirectory = true; window.__fileEvents = [];",
|
||||
"args": [],
|
||||
},
|
||||
)
|
||||
client.post(
|
||||
f"/session/{session_id}/element/{single_id}/value", {"text": str(chosen)}
|
||||
)
|
||||
directory_files = classic_value(
|
||||
client.post(
|
||||
f"/session/{session_id}/execute/async",
|
||||
{
|
||||
"script": (
|
||||
"const done = arguments[arguments.length - 1];"
|
||||
"const input = document.getElementById('upload-single');"
|
||||
"Promise.all(Array.from(input.files, async file => "
|
||||
"file.webkitRelativePath + ':' + await structuredClone(file).text()))"
|
||||
".then(values => done(values.sort().join('|')));"
|
||||
),
|
||||
"args": [],
|
||||
},
|
||||
)
|
||||
)
|
||||
assert_equal(
|
||||
directory_files, "chosen/a.txt:alpha|chosen/nested/b.txt:beta",
|
||||
"Classic directory upload relative paths and lazy clone bytes",
|
||||
)
|
||||
record(results, "classic_file_upload")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user