Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(cdp): search resource content on the renderer owner

ldm091aec378a441
diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rs
index af0cb5aba..e691bf082 100644
--- a/moli-core/src/page/mod.rs
+++ b/moli-core/src/page/mod.rs
@@ -109,7 +109,7 @@ pub use moli_renderer_v8::{
RendererJavaScriptDialogCompletion, RendererJavaScriptDialogId, RendererJavaScriptDialogResult,
RendererJavaScriptDialogSource, RendererLayoutMetrics, RendererLifecycleEpoch,
RendererLifecycleEventStamp, RendererLifecycleStartReason, RendererLifecycleTerminationStamp,
- RendererMainDocumentCommit, RendererNavigationInitiator,
+ RendererMainDocumentCommit, RendererMainDocumentResource, RendererNavigationInitiator,
RendererPageCommandPostResponseContinuation, RendererPageCreationArtifacts,
RendererPageCreationDiagnostics, RendererPageDiagnosticsSnapshot, RendererPageDumpFormat,
RendererPageDumpOptions, RendererPageDumpStripOptions, RendererPageReplacementError,
@@ -119,8 +119,9 @@ pub use moli_renderer_v8::{
RendererPendingPopupActivation, RendererPendingSameDocumentNavigation,
RendererPendingTopLevelHistoryTraversal, RendererPendingWindowOpenEvent,
RendererPerformanceMetricSnapshot, RendererPointerEventProperties,
- RendererPopupActivationSource, RendererPopupDisposition, RendererResourceTextSearchOutcome,
- RendererRuntimeCommandOutput, RendererRuntimeHeapUsage, RendererRuntimeInspectorIoCommandClaim,
+ RendererPopupActivationSource, RendererPopupDisposition, RendererResourceContentBody,
+ RendererResourceSearchRequest, RendererResourceTextSearchOutcome, RendererRuntimeCommandOutput,
+ RendererRuntimeHeapUsage, RendererRuntimeInspectorIoCommandClaim,
RendererRuntimeInspectorIoCommandRoute, RendererRuntimeInspectorMainCommandCompletion,
RendererRuntimeInspectorMainCommandRoute, RendererRuntimeInspectorMessage,
RendererRuntimeInspectorMessageBatch, RendererRuntimeInspectorProtocolMessage,
diff --git a/moli-core/src/page/resource_search_support.rs b/moli-core/src/page/resource_search_support.rs
index 5e4ec90de..8d29ae1ff 100644
--- a/moli-core/src/page/resource_search_support.rs
+++ b/moli-core/src/page/resource_search_support.rs
@@ -2,45 +2,18 @@ use anyhow::Result;
use super::{
CompletedPageCommand, Page, PendingPageCommand, RendererPageCommand, RendererPageReply,
- RendererResourceTextSearchOutcome,
+ RendererResourceSearchRequest, RendererResourceTextSearchOutcome,
};
impl Page {
- /// Capture current resource records before selecting the immutable source.
- pub fn start_resource_search_snapshot(&self) -> Result<PendingPageCommand> {
- self.start_page_command(RendererPageCommand::ResourceSearchSnapshot)
- }
-
- pub fn start_text_search_by_lines(
- &self,
- text: String,
- query: String,
- case_sensitive: bool,
- is_regex: bool,
- ) -> Result<PendingPageCommand> {
- self.start_page_command(RendererPageCommand::SearchTextByLines {
- text,
- query,
- case_sensitive,
- is_regex,
- })
- }
-
- pub fn start_child_frame_resource_search_by_lines(
+ /// Resolve and search immutable resource content on its renderer owner.
+ pub fn start_resource_search_by_lines(
&self,
- frame_id: String,
- url: String,
- query: String,
- case_sensitive: bool,
- is_regex: bool,
+ request: RendererResourceSearchRequest,
) -> Result<PendingPageCommand> {
- self.start_page_command(RendererPageCommand::SearchChildFrameResourceByLines {
- frame_id,
- url,
- query,
- case_sensitive,
- is_regex,
- })
+ self.start_page_command(RendererPageCommand::SearchResourceByLines(Box::new(
+ request,
+ )))
}
pub fn finish_resource_search_by_lines(
diff --git a/moli-protocol/src/conn/browser_context/page_owner.rs b/moli-protocol/src/conn/browser_context/page_owner.rs
index 751720d4b..be5a516b6 100644
--- a/moli-protocol/src/conn/browser_context/page_owner.rs
+++ b/moli-protocol/src/conn/browser_context/page_owner.rs
@@ -603,6 +603,7 @@ impl CdpConnection {
.main_document_for_loader(&loader_id)
}
+ #[cfg(test)]
pub(crate) fn target_owner_has_attached_child_frame_id_for_session(
&self,
session_id: Option<&str>,
diff --git a/moli-protocol/src/domains/page/resource_search.rs b/moli-protocol/src/domains/page/resource_search.rs
index 420387221..d28282bdd 100644
--- a/moli-protocol/src/domains/page/resource_search.rs
+++ b/moli-protocol/src/domains/page/resource_search.rs
@@ -1,26 +1,17 @@
-use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
+use std::sync::Arc;
+
use moli_core::page::{
- CompletedPageCommand, Page, PendingPageCommand, RendererResourceTextSearchOutcome,
- RendererTextSearchMatch, SubresourceNetworkOutcome, SubresourceNetworkRecord,
- SubresourceResourceType,
-};
-use moli_encoding::{
- decode_classic_script_source, decode_html_document_with_fallback, decode_text_for_legacy_web,
- encoding_from_response_headers,
-};
-use moli_web_mime::{
- effective_response_mime_essence, is_dom_parser_xml_mime, is_html_document_mime,
- is_javascript_mime_essence, is_json_mime, is_text_mime_essence,
+ CompletedPageCommand, PendingPageCommand, RendererMainDocumentResource,
+ RendererResourceContentBody, RendererResourceSearchRequest, RendererResourceTextSearchOutcome,
+ RendererTextSearchMatch,
};
use serde::Deserialize;
use serde_json::json;
-use url::Url;
use super::{PageCommandTaskStep, PendingPageCommandDispatch, PendingPageCommandKind};
-use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};
+use crate::conn::{CapturedBody, CdpConnection, Cmd, CommandOwnerScope};
use crate::domains::command_output::CommandOutputPlan;
-const AGENT_NOT_ENABLED: &str = "Agent is not enabled.";
const FRAME_NOT_FOUND: &str = "No frame for given id found";
const RESOURCE_NOT_FOUND: &str = "No resource with given URL found";
const CONTENT_UNAVAILABLE: &str = "Content unavailable. Resource was not cached";
@@ -37,22 +28,11 @@ struct SearchInResourceParams {
is_regex: bool,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum ResourceSearchSource {
- SubresourceSnapshot,
- SelectedText,
- ChildDocument,
-}
-
pub(super) struct PendingSearchInResourceCommand {
- params: SearchInResourceParams,
- source: ResourceSearchSource,
pending: PendingPageCommand,
}
pub(super) struct CompletedSearchInResourceCommand {
- params: SearchInResourceParams,
- source: ResourceSearchSource,
completed: Result<CompletedPageCommand, String>,
}
@@ -68,23 +48,15 @@ impl CompletedSearchInResourceCommand {
impl PendingSearchInResourceCommand {
pub(super) async fn wait(self) -> CompletedSearchInResourceCommand {
CompletedSearchInResourceCommand {
- params: self.params,
- source: self.source,
completed: self.pending.wait().await.map_err(|error| error.to_string()),
}
}
}
-enum SelectedResource {
- Text(String),
- Unavailable,
- Missing,
-}
-
-#[derive(Clone, Copy)]
-enum ResourceContentKind {
- MainDocument,
- Subresource(SubresourceResourceType),
+impl RendererResourceContentBody for CapturedBody {
+ fn read_bytes(&self, materialize_limit: usize) -> anyhow::Result<Vec<u8>> {
+ self.materialize_bytes_limited(materialize_limit)
+ }
}
pub(super) fn try_start_search_in_resource_command(
@@ -100,10 +72,9 @@ pub(super) fn try_start_search_in_resource_command(
));
}
};
-
match conn.page_domain_enabled_for_session_owner(cmd.session_id) {
Some(true) => {}
- Some(false) => return complete_error(AGENT_NOT_ENABLED),
+ Some(false) => return complete_error("Agent is not enabled."),
None => {
return PageCommandTaskStep::Complete(CommandOutputPlan::error(
-31998,
@@ -111,102 +82,65 @@ pub(super) fn try_start_search_in_resource_command(
));
}
}
-
let Some((root_frame_id, _, _, _)) =
conn.target_session_owner_frame_tree_identity(cmd.session_id)
else {
return PageCommandTaskStep::Complete(CommandOutputPlan::error(-31998, "TargetNotLoaded"));
};
- let is_root_frame = params.frame_id == root_frame_id;
- if !is_root_frame
- && !conn
- .target_owner_has_attached_child_frame_id_for_session(cmd.session_id, &params.frame_id)
- .unwrap_or(false)
- {
- return complete_error(FRAME_NOT_FOUND);
- }
- let materialize_limit = conn.response_body_materialize_limit();
+ // The browser network owner retains the exact response body by loader.
+ // Pass its immutable handle; source selection and decoding belong to the renderer.
+ let main_document = conn
+ .current_main_document_resource_for_session_owner(cmd.session_id)
+ .map(|resource| RendererMainDocumentResource {
+ frame_id: resource.frame_id,
+ url: resource.url,
+ response_headers: resource.response_headers,
+ from_cache: resource.from_cache,
+ body: resource
+ .body
+ .map(|body| Arc::new(body) as Arc<dyn RendererResourceContentBody>),
+ });
+ let request = RendererResourceSearchRequest {
+ root_frame_id,
+ frame_id: params.frame_id,
+ url: params.url,
+ query: params.query,
+ case_sensitive: params.case_sensitive,
+ is_regex: params.is_regex,
+ materialize_limit: conn.response_body_materialize_limit(),
+ main_document,
+ };
let owner = CommandOwnerScope::capture(conn, cmd.session_id);
-
- if is_root_frame {
- let main_document = conn.current_main_document_resource_for_session_owner(cmd.session_id);
- if main_document.as_ref().is_some_and(|resource| {
- resource.frame_id == root_frame_id
- && resource_urls_match(resource.url.as_str(), &params.url)
- }) {
- let selected = match main_document.and_then(|resource| {
- resource
- .body
- .map(|body| (body, resource.response_headers, resource.from_cache))
- }) {
- Some((body, headers, from_cache))
- if resource_has_searchable_content(body.len(), from_cache) =>
- {
- match body.materialize_bytes_limited(materialize_limit) {
- Ok(bytes) => SelectedResource::Text(decode_resource_content(
- &bytes,
- &headers,
- ResourceContentKind::MainDocument,
- )),
- Err(_) => SelectedResource::Unavailable,
- }
- }
- Some(_) => SelectedResource::Unavailable,
- None => SelectedResource::Unavailable,
- };
- return start_selected_resource_search(conn, cmd.id, owner, params, selected);
- }
-
- let Some(page) = loaded_page(conn, &owner) else {
- return complete_error(CONTENT_UNAVAILABLE);
- };
- // Native replies can arrive before their adapter updates the Page cache.
- // Select from a fresh renderer snapshot, even after getResourceTree.
- return match page.start_resource_search_snapshot() {
- Ok(pending) => pending_step(
- cmd.id,
- owner,
- PendingSearchInResourceCommand {
- params,
- source: ResourceSearchSource::SubresourceSnapshot,
- pending,
- },
- ),
- Err(error) => complete_error(format!("Failed to search resource: {error}")),
- };
- }
-
- let Some(page) = loaded_page(conn, &owner) else {
+ let Some(page) = conn
+ .runtime_session_owner_slot_mut_for_owner(&owner)
+ .ok()
+ .and_then(|slot| slot.loaded_page_mut())
+ else {
return complete_error(CONTENT_UNAVAILABLE);
};
- match page.start_child_frame_resource_search_by_lines(
- params.frame_id.clone(),
- params.url.clone(),
- params.query.clone(),
- params.case_sensitive,
- params.is_regex,
- ) {
- Ok(pending) => pending_step(
- cmd.id,
- owner,
- PendingSearchInResourceCommand {
- params,
- source: ResourceSearchSource::ChildDocument,
- pending,
- },
- ),
+ match page.start_resource_search_by_lines(request) {
+ Ok(pending) => PageCommandTaskStep::Pending(PendingPageCommandDispatch {
+ command_id: cmd.id,
+ owner_scope: owner,
+ kind: Box::new(PendingPageCommandKind::SearchInResource(
+ PendingSearchInResourceCommand { pending },
+ )),
+ }),
Err(error) => complete_error(format!("Failed to search resource: {error}")),
}
}
pub(super) fn complete_search_in_resource_command(
conn: &mut CdpConnection,
- command_id: Option<u64>,
+ _command_id: Option<u64>,
owner: &CommandOwnerScope,
completed: CompletedSearchInResourceCommand,
) -> PageCommandTaskStep {
- let materialize_limit = conn.response_body_materialize_limit();
- let Some(page) = loaded_page(conn, owner) else {
+ let Some(page) = conn
+ .runtime_session_owner_slot_mut_for_owner(owner)
+ .ok()
+ .and_then(|slot| slot.loaded_page_mut())
+ else {
return complete_error(CONTENT_UNAVAILABLE);
};
let completion = match completed.completed {
@@ -216,309 +150,26 @@ pub(super) fn complete_search_in_resource_command(
if page.renderer_agent_attachment_id() != completion.renderer_agent_attachment_id() {
return complete_error(CONTENT_UNAVAILABLE);
}
- if completed.source == ResourceSearchSource::SubresourceSnapshot {
- if let Err(error) =
- page.finish_unit_runtime_page_command(completion, "resource search snapshot")
- {
- return complete_error(format!("Failed to search resource: {error}"));
+ match page.finish_resource_search_by_lines(completion) {
+ Ok(RendererResourceTextSearchOutcome::Matches(matches)) => {
+ PageCommandTaskStep::Complete(CommandOutputPlan::result(json!({
+ "result": matches.into_iter().map(|matched: RendererTextSearchMatch| json!({
+ "lineNumber": matched.line_number,
+ "lineContent": matched.line_content,
+ })).collect::<Vec<_>>(),
+ })))
}
- let selected = select_subresource(
- page,
- &completed.params.frame_id,
- true,
- &completed.params.url,
- materialize_limit,
- );
- return start_selected_resource_search(
- conn,
- command_id,
- owner.clone(),
- completed.params,
- selected,
- );
- }
- let outcome = match page.finish_resource_search_by_lines(completion) {
- Ok(outcome) => outcome,
- Err(error) => return complete_error(format!("Failed to search resource: {error}")),
- };
-
- match (completed.source, outcome) {
- (_, RendererResourceTextSearchOutcome::Matches(matches)) => complete_matches(matches),
- (_, RendererResourceTextSearchOutcome::FrameNotFound) => complete_error(FRAME_NOT_FOUND),
- (_, RendererResourceTextSearchOutcome::ContentUnavailable) => {
- complete_error(CONTENT_UNAVAILABLE)
- }
- (
- ResourceSearchSource::ChildDocument,
- RendererResourceTextSearchOutcome::ResourceNotFound,
- ) => {
- let selected = select_subresource(
- page,
- &completed.params.frame_id,
- false,
- &completed.params.url,
- materialize_limit,
- );
- start_selected_resource_search(
- conn,
- command_id,
- owner.clone(),
- completed.params,
- selected,
- )
- }
- (_, RendererResourceTextSearchOutcome::ResourceNotFound) => {
+ Ok(RendererResourceTextSearchOutcome::FrameNotFound) => complete_error(FRAME_NOT_FOUND),
+ Ok(RendererResourceTextSearchOutcome::ResourceNotFound) => {
complete_error(RESOURCE_NOT_FOUND)
}
- }
-}
-
-fn start_selected_resource_search(
- conn: &mut CdpConnection,
- command_id: Option<u64>,
- owner: CommandOwnerScope,
- params: SearchInResourceParams,
- selected: SelectedResource,
-) -> PageCommandTaskStep {
- let text = match selected {
- SelectedResource::Text(text) => text,
- SelectedResource::Unavailable => return complete_error(CONTENT_UNAVAILABLE),
- SelectedResource::Missing => return complete_error(RESOURCE_NOT_FOUND),
- };
- let Some(page) = loaded_page(conn, &owner) else {
- return complete_error(CONTENT_UNAVAILABLE);
- };
- match page.start_text_search_by_lines(
- text,
- params.query.clone(),
- params.case_sensitive,
- params.is_regex,
- ) {
- Ok(pending) => pending_step(
- command_id,
- owner,
- PendingSearchInResourceCommand {
- params,
- source: ResourceSearchSource::SelectedText,
- pending,
- },
- ),
+ Ok(RendererResourceTextSearchOutcome::ContentUnavailable) => {
+ complete_error(CONTENT_UNAVAILABLE)
+ }
Err(error) => complete_error(format!("Failed to search resource: {error}")),
}
}
-fn pending_step(
- command_id: Option<u64>,
- owner_scope: CommandOwnerScope,
- pending: PendingSearchInResourceCommand,
-) -> PageCommandTaskStep {
- PageCommandTaskStep::Pending(PendingPageCommandDispatch {
- command_id,
- owner_scope,
- kind: Box::new(PendingPageCommandKind::SearchInResource(pending)),
- })
-}
-
-fn complete_matches(matches: Vec<RendererTextSearchMatch>) -> PageCommandTaskStep {
- PageCommandTaskStep::Complete(CommandOutputPlan::result(json!({
- "result": matches
- .into_iter()
- .map(|matched| json!({
- "lineNumber": matched.line_number,
- "lineContent": matched.line_content,
- }))
- .collect::<Vec<_>>(),
- })))
-}
-
fn complete_error(message: impl Into<String>) -> PageCommandTaskStep {
PageCommandTaskStep::Complete(CommandOutputPlan::error(-32000, message))
}
-
-fn loaded_page<'a>(conn: &'a mut CdpConnection, owner: &CommandOwnerScope) -> Option<&'a mut Page> {
- conn.runtime_session_owner_slot_mut_for_owner(owner)
- .ok()?
- .loaded_page_mut()
-}
-
-fn select_subresource(
- page: &Page,
- frame_id: &str,
- root_frame: bool,
- requested_url: &str,
- materialize_limit: usize,
-) -> SelectedResource {
- let record = page
- .subresource_network_records()
- .iter()
- .rev()
- .find(|record| {
- resource_belongs_to_frame(record, frame_id, root_frame)
- && subresource_url_matches(record, requested_url)
- });
- let Some(record) = record else {
- return SelectedResource::Missing;
- };
- let SubresourceNetworkOutcome::Success {
- response_headers,
- response_body,
- ..
- } = record.outcome()
- else {
- return SelectedResource::Unavailable;
- };
- if !resource_has_searchable_content(response_body.len(), record.from_cache()) {
- return SelectedResource::Unavailable;
- }
- if response_body.len() > materialize_limit {
- return SelectedResource::Unavailable;
- }
- let Ok(bytes) = response_body.materialize_bytes() else {
- return SelectedResource::Unavailable;
- };
- SelectedResource::Text(decode_resource_content(
- &bytes,
- response_headers,
- ResourceContentKind::Subresource(record.resource_type()),
- ))
-}
-
-fn resource_has_searchable_content(body_len: usize, from_cache: bool) -> bool {
- body_len != 0 || from_cache
-}
-
-fn resource_belongs_to_frame(
- record: &SubresourceNetworkRecord,
- frame_id: &str,
- root_frame: bool,
-) -> bool {
- record.frame_id() == Some(frame_id) || (root_frame && record.frame_id().is_none())
-}
-
-fn subresource_url_matches(record: &SubresourceNetworkRecord, requested_url: &str) -> bool {
- if resource_urls_match(record.url().as_str(), requested_url) {
- return true;
- }
- match record.outcome() {
- SubresourceNetworkOutcome::Success { final_url, .. } => {
- resource_urls_match(final_url.as_str(), requested_url)
- }
- SubresourceNetworkOutcome::Failure { .. } => false,
- }
-}
-
-fn decode_resource_content(
- bytes: &[u8],
- headers: &[(String, Vec<u8>)],
- kind: ResourceContentKind,
-) -> String {
- let mime = effective_response_mime_essence(headers, None).unwrap_or_default();
- if matches!(kind, ResourceContentKind::MainDocument)
- && (mime.is_empty() || is_html_document_mime(&mime))
- {
- return decode_html_document_with_fallback(bytes, headers, Some("utf-8")).0;
- }
- if matches!(
- kind,
- ResourceContentKind::Subresource(SubresourceResourceType::Script)
- ) || is_javascript_mime_essence(&mime)
- {
- return decode_classic_script_source(bytes, headers, None, None);
- }
- let response_charset = encoding_from_response_headers(headers).map(|encoding| encoding.name());
- if matches!(
- kind,
- ResourceContentKind::Subresource(SubresourceResourceType::Stylesheet)
- ) {
- return decode_text_for_legacy_web(bytes, response_charset);
- }
- if is_dom_parser_xml_mime(&mime) || is_json_mime(&mime) {
- return decode_text_for_legacy_web(bytes, response_charset);
- }
- if is_text_mime_essence(&mime) {
- return decode_text_for_legacy_web(bytes, response_charset.or(Some("windows-1252")));
- }
- BASE64_STANDARD.encode(bytes)
-}
-
-fn resource_urls_match(left: &str, right: &str) -> bool {
- match (url_without_fragment(left), url_without_fragment(right)) {
- (Some(left), Some(right)) => left == right,
- _ => left == right,
- }
-}
-
-fn url_without_fragment(value: &str) -> Option<Url> {
- Url::parse(value).ok().map(|mut url| {
- url.set_fragment(None);
- url
- })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn resource_url_identity_ignores_fragments() {
- assert!(resource_urls_match(
- "https://example.test/page#one",
- "https://example.test/page#two"
- ));
- assert!(!resource_urls_match(
- "https://example.test/page",
- "https://example.test/other"
- ));
- }
-
- #[test]
- fn html_resource_decoding_observes_declared_charset() {
- let headers: Vec<(String, Vec<u8>)> = vec![(
- "content-type".to_owned(),
- b"text/html; charset=windows-1252".to_vec(),
- )];
- assert_eq!(
- decode_resource_content(b"<p>\x80</p>", &headers, ResourceContentKind::MainDocument,),
- "<p>\u{20ac}</p>"
- );
- }
-
- #[test]
- fn stylesheet_resource_rejects_invalid_response_charset_whitespace() {
- let headers: Vec<(String, Vec<u8>)> = vec![(
- "content-type".to_owned(),
- b"text/css; charset=\nshift_jis".to_vec(),
- )];
-
- assert_eq!(
- decode_resource_content(
- "body::after { content: '目次'; }".as_bytes(),
- &headers,
- ResourceContentKind::Subresource(SubresourceResourceType::Stylesheet),
- ),
- "body::after { content: '目次'; }"
- );
- }
-
- #[test]
- fn binary_resource_searches_chromium_style_base64_content() {
- assert_eq!(
- decode_resource_content(
- &[0, 255],
- &[(
- "content-type".to_owned(),
- b"application/octet-stream".to_vec(),
- )],
- ResourceContentKind::Subresource(SubresourceResourceType::Image),
- ),
- "AP8="
- );
- }
-
- #[test]
- fn uncached_empty_resource_is_unavailable_but_cached_empty_resource_is_searchable() {
- assert!(!resource_has_searchable_content(0, false));
- assert!(resource_has_searchable_content(0, true));
- assert!(resource_has_searchable_content(1, false));
- }
-}
diff --git a/moli-protocol/src/domains/page/tests/resources.rs b/moli-protocol/src/domains/page/tests/resources.rs
index 2a77fbf0a..61cac0182 100644
--- a/moli-protocol/src/domains/page/tests/resources.rs
+++ b/moli-protocol/src/domains/page/tests/resources.rs
@@ -606,6 +606,11 @@ async fn frame_and_resource_trees_report_main_document_response_mime() {
async fn search_in_resource_reads_renderer_sources_before_native_adapter_settlement() {
use moli_core::{RendererNativeOperation, RendererNativeProtocolResponse, RendererPageCommand};
+ use crate::conn::{Cmd, CommandDispatchContext};
+ use crate::domains::page::{
+ PageCommandTaskStep, complete_pending_page_command, try_start_page_command_dispatch,
+ };
+
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
@@ -706,17 +711,50 @@ async fn search_in_resource_reads_renderer_sources_before_native_adapter_settlem
"native publication must not settle the held adapter Page cache"
);
- ctx.process_async(json!({
+ let params = json!({
+ "frameId": tree["result"]["frameTree"]["frame"]["id"],
+ "url": script_url,
+ "query": "freshSourceNeedle"
+ });
+ let raw_search = json!({
"id": 1204,
"method": "Page.searchInResource",
- "params": {
- "frameId": tree["result"]["frameTree"]["frame"]["id"],
- "url": script_url,
- "query": "freshSourceNeedle"
- }
- }))
- .await;
- let search = take_response_by_id(&mut ctx, 1204);
+ "params": params
+ })
+ .to_string();
+ let cmd = Cmd::for_test(
+ Some(1204),
+ "Page.searchInResource",
+ &params,
+ None,
+ &raw_search,
+ );
+ let PageCommandTaskStep::Pending(pending) =
+ try_start_page_command_dispatch(&mut ctx.conn, &cmd).unwrap()
+ else {
+ panic!("resource search must query the renderer before adapter settlement");
+ };
+ let held_search = pending.wait().await;
+ assert!(
+ ctx.conn
+ .loaded_page_mut_for_protocol_access(None)
+ .unwrap()
+ .subresource_network_records()
+ .is_empty(),
+ "renderer search must finish before the adapter Page cache is updated"
+ );
+ let mut command_context = CommandDispatchContext::default();
+ let PageCommandTaskStep::Complete(plan) =
+ complete_pending_page_command(&mut ctx.conn, held_search, &mut command_context).await
+ else {
+ panic!(
+ "resource search must settle after one renderer command without another pending turn"
+ );
+ };
+ let mut out = Vec::new();
+ plan.emit_into(&mut out, cmd.id, cmd.session_id);
+ let search = &out[0];
+ assert_eq!(search["id"], json!(1204));
assert_eq!(
search["result"]["result"],
json!([{
@@ -733,7 +771,7 @@ async fn search_in_resource_reads_renderer_sources_before_native_adapter_settlem
}
#[tokio::test(flavor = "multi_thread")]
-async fn search_in_resource_rejects_snapshot_from_replaced_document() {
+async fn search_in_resource_rejects_completion_from_replaced_document() {
use crate::conn::{Cmd, CommandDispatchContext};
use crate::domains::page::{
PageCommandTaskStep, complete_pending_page_command, try_start_page_command_dispatch,
@@ -814,11 +852,11 @@ async fn search_in_resource_rejects_snapshot_from_replaced_document() {
let PageCommandTaskStep::Pending(pending) =
try_start_page_command_dispatch(&mut ctx.conn, &cmd).unwrap()
else {
- panic!("subresource search should first capture a renderer snapshot");
+ panic!("subresource search should execute one renderer command");
};
- // Complete the old snapshot in the renderer, then replace its Document
- // before protocol consumes or installs the captured Page state.
- let held_snapshot = pending.wait().await;
+ // Complete the old search in the renderer, then replace its Document
+ // before protocol consumes the result or installs its captured Page state.
+ let held_search = pending.wait().await;
ctx.process_async(json!({
"id": 1302,
@@ -857,9 +895,9 @@ async fn search_in_resource_rejects_snapshot_from_replaced_document() {
let mut command_context = CommandDispatchContext::default();
let PageCommandTaskStep::Complete(plan) =
- complete_pending_page_command(&mut ctx.conn, held_snapshot, &mut command_context).await
+ complete_pending_page_command(&mut ctx.conn, held_search, &mut command_context).await
else {
- panic!("retired snapshot should settle as an error without another search turn");
+ panic!("retired search completion should settle as an error without another search turn");
};
let mut out = Vec::new();
plan.emit_into(&mut out, cmd.id, cmd.session_id);
@@ -877,7 +915,7 @@ async fn search_in_resource_rejects_snapshot_from_replaced_document() {
.map(|record| record.url().as_str().to_owned())
.collect::<Vec<_>>(),
replacement_resources,
- "an old snapshot must not replace the new Document's resource records"
+ "an old search completion must not replace the new Document's resource records"
);
server.abort();
diff --git a/moli-renderer-v8/src/devtools/command/nested.rs b/moli-renderer-v8/src/devtools/command/nested.rs
index ce7184924..edf5001f5 100644
--- a/moli-renderer-v8/src/devtools/command/nested.rs
+++ b/moli-renderer-v8/src/devtools/command/nested.rs
@@ -84,7 +84,6 @@ impl RendererPageCommand {
| Self::BlobBytesForUuid { .. }
| Self::DocumentFrontendNodeIdsForBackendNodeIds { .. }
| Self::DocumentStorageKeySnapshot
- | Self::ResourceSearchSnapshot
| Self::ChildFrameTreeSnapshot
| Self::ChildFrameOwnerNodeReference { .. }
| Self::ChildFrameDocumentRootNodeReference { .. }
@@ -163,8 +162,7 @@ impl RendererPageCommand {
| Self::SetFileInputFilesForBackendNodeId { .. }
| Self::RenderPageDump { .. }
| Self::CaptureScreenshot(..)
- | Self::SearchTextByLines { .. }
- | Self::SearchChildFrameResourceByLines { .. }
+ | Self::SearchResourceByLines(..)
| Self::ContinuePendingSubresourceFetch { .. }
| Self::ContinuePendingSubresourceAuth { .. }
| Self::CancelPendingSubresourceAuth { .. }
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index aa7cb7255..7a3ef57a0 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -273,7 +273,7 @@ pub use runtime::{
RendererLayoutMetrics, RendererLifecycleDecider, RendererLifecycleDecision,
RendererLifecycleEpoch, RendererLifecycleEventStamp, RendererLifecycleSnapshot,
RendererLifecycleStartReason, RendererLifecycleTerminationStamp, RendererMainDocumentCommit,
- RendererMoliDomMemoryDiagnostics, RendererMoliMemoryDiagnostics,
+ RendererMainDocumentResource, RendererMoliDomMemoryDiagnostics, RendererMoliMemoryDiagnostics,
RendererMoliMemoryScopeDiagnostics, RendererMoliRuntimeMemoryDiagnostics,
RendererNativeCommandReadyResponse, RendererNativeCommandResponseGuard,
RendererNativeCommandTerminal, RendererNativeOperation, RendererNativeOperationStep,
@@ -302,7 +302,8 @@ pub use runtime::{
RendererPendingWindowOpenEvent, RendererPerformanceMetricSnapshot,
RendererPointerEventProperties, RendererPopupActivationSource, RendererPopupDisposition,
RendererPreparedDocumentCommitConfiguration, RendererProtocolObservation,
- RendererReservedServiceWorkerClient, RendererResourceTextSearchOutcome,
+ RendererReservedServiceWorkerClient, RendererResourceContentBody,
+ RendererResourceSearchRequest, RendererResourceTextSearchOutcome,
RendererRuntimeCommandCausalIdentity, RendererRuntimeCommandOutput,
RendererRuntimeEvaluationResult, RendererRuntimeHeapSpaceUsage, RendererRuntimeHeapUsage,
RendererRuntimeInspectorAsyncCompletion, RendererRuntimeInspectorIoCommandClaim,
diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rs
index 5632b697a..8ad75f89a 100644
--- a/moli-renderer-v8/src/runtime/mod.rs
+++ b/moli-renderer-v8/src/runtime/mod.rs
@@ -426,6 +426,9 @@ pub(in crate::runtime) use self::page_vm::{
PageVmCommittedNavigationBootstrap, PageVmDocumentCommitPreparation,
PageVmPreparedFollowedNavigationCommit, PageVmValidatedFollowedNavigationCommit,
};
+pub use self::page_vm::{
+ RendererMainDocumentResource, RendererResourceContentBody, RendererResourceSearchRequest,
+};
pub use self::phase_one::ExternalRawDocumentBodyStream;
use self::phase_one::PendingPhaseOneResidence;
pub(in crate::runtime) use self::phase_one::{
diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rs
index e684f708f..550b2e021 100644
--- a/moli-renderer-v8/src/runtime/page_commands.rs
+++ b/moli-renderer-v8/src/runtime/page_commands.rs
@@ -424,35 +424,9 @@ impl PageVm {
self.stop_document_lifecycle()?;
Ok(RendererPageReply::Unit)
}
- RendererPageCommand::ResourceSearchSnapshot => Ok(RendererPageReply::Unit),
- RendererPageCommand::SearchTextByLines {
- text,
- query,
- case_sensitive,
- is_regex,
- } => Ok(RendererPageReply::ResourceTextSearchOutcome(
- RendererResourceTextSearchOutcome::Matches(self.vm_mut().search_text_by_lines(
- &text,
- &query,
- case_sensitive,
- is_regex,
- )?),
- )),
- RendererPageCommand::SearchChildFrameResourceByLines {
- frame_id,
- url,
- query,
- case_sensitive,
- is_regex,
- } => Ok(RendererPageReply::ResourceTextSearchOutcome(
- self.vm_mut().search_child_frame_resource_by_lines(
- &frame_id,
- &url,
- &query,
- case_sensitive,
- is_regex,
- )?,
- )),
+ RendererPageCommand::SearchResourceByLines(request) => Ok(
+ RendererPageReply::ResourceTextSearchOutcome(self.search_resource_by_lines(*request)?),
+ ),
RendererPageCommand::ComputedStyleProperties { reference } => {
Ok(RendererPageReply::ComputedStyleProperties(
self.computed_style_properties_for_node(reference)?,
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index 91a613203..be3919506 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -5116,20 +5116,7 @@ pub enum RendererPageCommand {
backend_node_ids: Vec<u32>,
},
DocumentStorageKeySnapshot,
- ResourceSearchSnapshot,
- SearchTextByLines {
- text: String,
- query: String,
- case_sensitive: bool,
- is_regex: bool,
- },
- SearchChildFrameResourceByLines {
- frame_id: String,
- url: String,
- query: String,
- case_sensitive: bool,
- is_regex: bool,
- },
+ SearchResourceByLines(Box<RendererResourceSearchRequest>),
ChildFrameTreeSnapshot,
ChildFrameOwnerNodeReference {
inspector_session_id: Option<String>,
@@ -5623,7 +5610,6 @@ impl RendererPageCommand {
| Self::LiveChildDefaultRuntimeRealmInventory
| Self::RuntimeConsoleMessagesWithContext
| Self::ChildFrameTreeSnapshot
- | Self::ResourceSearchSnapshot
| Self::PendingSubresourceRequestCount
)
}
@@ -5633,7 +5619,7 @@ impl RendererPageCommand {
Self::Native(command) => command.operation.command.cdp_nav_timing_label(),
Self::Inspector(envelope) => envelope.cdp_nav_timing_label(),
Self::DocumentStorageKeySnapshot => Some("DocumentStorageKeySnapshot"),
- Self::ResourceSearchSnapshot => Some("ResourceSearchSnapshot"),
+ Self::SearchResourceByLines(..) => Some("SearchResourceByLines"),
Self::CreateIsolatedWorldRuntimeActivity { .. } => {
Some("CreateIsolatedWorldRuntimeActivity")
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs
index 57c4acb2c..63eafe637 100644
--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs
@@ -137,6 +137,10 @@ mod page_rendering_update;
#[cfg(test)]
mod page_rendering_update_body_test_support;
mod page_resource_completion;
+mod resource_search;
+pub use resource_search::{
+ RendererMainDocumentResource, RendererResourceContentBody, RendererResourceSearchRequest,
+};
mod page_resource_completion_task_completion;
#[cfg(test)]
mod page_selected_task_test_harness;
diff --git a/moli-renderer-v8/src/runtime/page_vm/resource_search.rs b/moli-renderer-v8/src/runtime/page_vm/resource_search.rs
new file mode 100644
index 000000000..da6ac2084
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/resource_search.rs
@@ -0,0 +1,316 @@
+use std::{fmt::Debug, sync::Arc};
+
+use anyhow::Result;
+use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
+use moli_encoding::{
+ decode_classic_script_source, decode_html_document_with_fallback, decode_text_for_legacy_web,
+ encoding_from_response_headers,
+};
+use moli_page_types::{
+ SubresourceNetworkOutcome, SubresourceNetworkRecord, SubresourceResourceType,
+};
+use moli_web_mime::{
+ effective_response_mime_essence, is_dom_parser_xml_mime, is_html_document_mime,
+ is_javascript_mime_essence, is_json_mime, is_text_mime_essence,
+};
+use url::Url;
+
+use crate::runtime::RendererResourceTextSearchOutcome;
+
+use super::PageVm;
+
+#[derive(Debug, Clone)]
+pub struct RendererResourceSearchRequest {
+ pub root_frame_id: String,
+ pub frame_id: String,
+ pub url: String,
+ pub query: String,
+ pub case_sensitive: bool,
+ pub is_regex: bool,
+ pub materialize_limit: usize,
+ pub main_document: Option<RendererMainDocumentResource>,
+}
+
+#[derive(Debug, Clone)]
+pub struct RendererMainDocumentResource {
+ pub frame_id: String,
+ pub url: Url,
+ pub response_headers: Vec<(String, Vec<u8>)>,
+ pub from_cache: bool,
+ pub body: Option<Arc<dyn RendererResourceContentBody>>,
+}
+
+/// Immutable original response bytes retained by the browser network owner.
+/// Implementations must enforce the limit before materializing the body.
+pub trait RendererResourceContentBody: Debug + Send + Sync {
+ fn read_bytes(&self, materialize_limit: usize) -> Result<Vec<u8>>;
+}
+
+enum SelectedResource {
+ Text(String),
+ Unavailable,
+ Missing,
+}
+
+#[derive(Clone, Copy)]
+enum ResourceContentKind {
+ MainDocument,
+ Subresource(SubresourceResourceType),
+}
+
+impl PageVm {
+ pub(crate) fn search_resource_by_lines(
+ &mut self,
+ request: RendererResourceSearchRequest,
+ ) -> Result<RendererResourceTextSearchOutcome> {
+ // Resource completions may already be visible to native CDP commands
+ // before the protocol adapter has consumed their Page state snapshots.
+ self.drain_network_output_into_report();
+
+ let root_frame = request.frame_id == request.root_frame_id;
+ if !root_frame {
+ let outcome = self.vm_mut().search_child_frame_resource_by_lines(
+ &request.frame_id,
+ &request.url,
+ &request.query,
+ request.case_sensitive,
+ request.is_regex,
+ )?;
+ if !matches!(outcome, RendererResourceTextSearchOutcome::ResourceNotFound) {
+ return Ok(outcome);
+ }
+ }
+
+ let main_document = request.main_document.as_ref().filter(|resource| {
+ root_frame
+ && resource.frame_id == request.frame_id
+ && resource_urls_match(resource.url.as_str(), &request.url)
+ });
+ let selected = match main_document {
+ Some(resource) => select_main_document(resource, request.materialize_limit),
+ None => select_subresource(
+ self.report.subresource_network_records(),
+ &request.frame_id,
+ root_frame,
+ &request.url,
+ request.materialize_limit,
+ ),
+ };
+ let text = match selected {
+ SelectedResource::Text(text) => text,
+ SelectedResource::Unavailable => {
+ return Ok(RendererResourceTextSearchOutcome::ContentUnavailable);
+ }
+ SelectedResource::Missing => {
+ return Ok(RendererResourceTextSearchOutcome::ResourceNotFound);
+ }
+ };
+ Ok(RendererResourceTextSearchOutcome::Matches(
+ self.vm_mut().search_text_by_lines(
+ &text,
+ &request.query,
+ request.case_sensitive,
+ request.is_regex,
+ )?,
+ ))
+ }
+}
+
+fn select_main_document(
+ resource: &RendererMainDocumentResource,
+ materialize_limit: usize,
+) -> SelectedResource {
+ let Some(body) = resource.body.as_ref() else {
+ return SelectedResource::Unavailable;
+ };
+ let Ok(bytes) = body.read_bytes(materialize_limit) else {
+ return SelectedResource::Unavailable;
+ };
+ if bytes.len() > materialize_limit
+ || !resource_has_searchable_content(bytes.len(), resource.from_cache)
+ {
+ return SelectedResource::Unavailable;
+ }
+ SelectedResource::Text(decode_resource_content(
+ &bytes,
+ &resource.response_headers,
+ ResourceContentKind::MainDocument,
+ ))
+}
+
+fn select_subresource(
+ records: &[SubresourceNetworkRecord],
+ frame_id: &str,
+ root_frame: bool,
+ requested_url: &str,
+ materialize_limit: usize,
+) -> SelectedResource {
+ let record = records.iter().rev().find(|record| {
+ resource_belongs_to_frame(record, frame_id, root_frame)
+ && subresource_url_matches(record, requested_url)
+ });
+ let Some(record) = record else {
+ return SelectedResource::Missing;
+ };
+ let SubresourceNetworkOutcome::Success {
+ response_headers,
+ response_body,
+ ..
+ } = record.outcome()
+ else {
+ return SelectedResource::Unavailable;
+ };
+ if !resource_has_searchable_content(response_body.len(), record.from_cache())
+ || response_body.len() > materialize_limit
+ {
+ return SelectedResource::Unavailable;
+ }
+ let Ok(bytes) = response_body.materialize_bytes() else {
+ return SelectedResource::Unavailable;
+ };
+ SelectedResource::Text(decode_resource_content(
+ &bytes,
+ response_headers,
+ ResourceContentKind::Subresource(record.resource_type()),
+ ))
+}
+
+fn resource_has_searchable_content(body_len: usize, from_cache: bool) -> bool {
+ body_len != 0 || from_cache
+}
+
+fn resource_belongs_to_frame(
+ record: &SubresourceNetworkRecord,
+ frame_id: &str,
+ root_frame: bool,
+) -> bool {
+ record.frame_id() == Some(frame_id) || (root_frame && record.frame_id().is_none())
+}
+
+fn subresource_url_matches(record: &SubresourceNetworkRecord, requested_url: &str) -> bool {
+ if resource_urls_match(record.url().as_str(), requested_url) {
+ return true;
+ }
+ match record.outcome() {
+ SubresourceNetworkOutcome::Success { final_url, .. } => {
+ resource_urls_match(final_url.as_str(), requested_url)
+ }
+ SubresourceNetworkOutcome::Failure { .. } => false,
+ }
+}
+
+fn decode_resource_content(
+ bytes: &[u8],
+ headers: &[(String, Vec<u8>)],
+ kind: ResourceContentKind,
+) -> String {
+ let mime = effective_response_mime_essence(headers, None).unwrap_or_default();
+ if matches!(kind, ResourceContentKind::MainDocument)
+ && (mime.is_empty() || is_html_document_mime(&mime))
+ {
+ return decode_html_document_with_fallback(bytes, headers, Some("utf-8")).0;
+ }
+ if matches!(
+ kind,
+ ResourceContentKind::Subresource(SubresourceResourceType::Script)
+ ) || is_javascript_mime_essence(&mime)
+ {
+ return decode_classic_script_source(bytes, headers, None, None);
+ }
+ let response_charset = encoding_from_response_headers(headers).map(|encoding| encoding.name());
+ if matches!(
+ kind,
+ ResourceContentKind::Subresource(SubresourceResourceType::Stylesheet)
+ ) {
+ return decode_text_for_legacy_web(bytes, response_charset);
+ }
+ if is_dom_parser_xml_mime(&mime) || is_json_mime(&mime) {
+ return decode_text_for_legacy_web(bytes, response_charset);
+ }
+ if is_text_mime_essence(&mime) {
+ return decode_text_for_legacy_web(bytes, response_charset.or(Some("windows-1252")));
+ }
+ BASE64_STANDARD.encode(bytes)
+}
+
+fn resource_urls_match(left: &str, right: &str) -> bool {
+ match (url_without_fragment(left), url_without_fragment(right)) {
+ (Some(left), Some(right)) => left == right,
+ _ => left == right,
+ }
+}
+
+fn url_without_fragment(value: &str) -> Option<Url> {
+ Url::parse(value).ok().map(|mut url| {
+ url.set_fragment(None);
+ url
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resource_url_identity_ignores_fragments() {
+ assert!(resource_urls_match(
+ "https://example.test/page#one",
+ "https://example.test/page#two"
+ ));
+ assert!(!resource_urls_match(
+ "https://example.test/page",
+ "https://example.test/other"
+ ));
+ }
+
+ #[test]
+ fn html_resource_decoding_observes_declared_charset() {
+ let headers: Vec<(String, Vec<u8>)> = vec![(
+ "content-type".to_owned(),
+ b"text/html; charset=windows-1252".to_vec(),
+ )];
+ assert_eq!(
+ decode_resource_content(b"<p>\x80</p>", &headers, ResourceContentKind::MainDocument,),
+ "<p>\u{20ac}</p>"
+ );
+ }
+
+ #[test]
+ fn stylesheet_resource_rejects_invalid_response_charset_whitespace() {
+ let headers: Vec<(String, Vec<u8>)> = vec![(
+ "content-type".to_owned(),
+ b"text/css; charset=\nshift_jis".to_vec(),
+ )];
+
+ assert_eq!(
+ decode_resource_content(
+ "body::after { content: '目次'; }".as_bytes(),
+ &headers,
+ ResourceContentKind::Subresource(SubresourceResourceType::Stylesheet),
+ ),
+ "body::after { content: '目次'; }"
+ );
+ }
+
+ #[test]
+ fn binary_resource_searches_chromium_style_base64_content() {
+ assert_eq!(
+ decode_resource_content(
+ &[0, 255],
+ &[(
+ "content-type".to_owned(),
+ b"application/octet-stream".to_vec(),
+ )],
+ ResourceContentKind::Subresource(SubresourceResourceType::Image),
+ ),
+ "AP8="
+ );
+ }
+
+ #[test]
+ fn uncached_empty_resource_is_unavailable_but_cached_empty_resource_is_searchable() {
+ assert!(!resource_has_searchable_content(0, false));
+ assert!(resource_has_searchable_content(0, true));
+ assert!(resource_has_searchable_content(1, false));
+ }
+}