mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 00:02:21 +00:00
refactor(target): remove legacy attachment workflow wrappers
Commit Browser detach and auto-attach disable synchronously, preserving event ordering while supervising each native retirement independently. Remove the synthetic completion objects, test-only serial runner, and obsolete recovery. Batch script removal with SessionPageUpdates and retain the original disposal identity for completion. Enqueue target-owned Inspector initialization without claim/reply observers or a cancellable route. Share endpoint selection and borrow connection keys/bindings separately from navigation restore snapshots. Clarify session admission names and separate static policy from Page readiness selection while retaining the admission token through synchronous redispatch. Exercise the production Browser commit and supervisor paths in disposal tests.
This commit is contained in:
@@ -434,9 +434,8 @@ impl ParsedCdpCommand {
|
||||
self.renderer_policy
|
||||
}
|
||||
|
||||
/// Whether dispatch joins an already pending initial Page build. This is
|
||||
/// distinct from renderer thread access: Page.enable also needs installed
|
||||
/// agents, while dialog handling, close, and cancellation remain available.
|
||||
/// Whether Renderer work waits for Page adoption. Browser subscriptions,
|
||||
/// dialog handling, close, and cancellation have their own admission rules.
|
||||
pub fn requires_initial_document_adoption(&self) -> bool {
|
||||
// Before the first Page, disabling Runtime only retires Browser state.
|
||||
if matches!(
|
||||
@@ -446,9 +445,18 @@ impl ParsedCdpCommand {
|
||||
return false;
|
||||
}
|
||||
self.renderer_access() != CdpRendererCommandAccess::OwnerIndependent
|
||||
|| matches!(
|
||||
self.method(),
|
||||
"Page.getFrameTree" | "Page.getResourceTree" | "Page.navigate"
|
||||
|| matches!(self.method(), "Page.navigate")
|
||||
}
|
||||
|
||||
pub fn requires_session_command_admission(&self) -> bool {
|
||||
self.requires_initial_document_adoption() || self.method() == "Runtime.disable"
|
||||
}
|
||||
|
||||
pub fn can_use_prepared_inspector_endpoint(&self) -> bool {
|
||||
self.renderer_access() == CdpRendererCommandAccess::Io
|
||||
&& matches!(
|
||||
self.method().split('.').next(),
|
||||
Some("Runtime" | "Debugger")
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -101,8 +101,7 @@ mod resource_runtime_support;
|
||||
mod runtime_eval;
|
||||
mod session_cleanup;
|
||||
pub(crate) use session_cleanup::{
|
||||
CompletedSessionPageUpdates, CompletedSessionScriptCleanup, SessionPageUpdateResult,
|
||||
SessionPageUpdates, SessionScriptCleanup,
|
||||
CompletedSessionPageUpdates, SessionPageUpdateResult, SessionPageUpdates,
|
||||
};
|
||||
mod runtime_load;
|
||||
mod scheduler_hooks;
|
||||
@@ -666,12 +665,6 @@ impl CommandDispatchContext {
|
||||
.into_single_stream()
|
||||
}
|
||||
|
||||
/// Browser/Target commands explicitly compose independently owned renderer
|
||||
/// streams without moving their response out of the command lifecycle.
|
||||
pub(crate) fn add_renderer_output_dependency(&mut self, fence: moli_core::RendererOutputFence) {
|
||||
self.renderer_output_dependencies.add(fence);
|
||||
}
|
||||
|
||||
pub(crate) fn extend_renderer_output_dependencies(
|
||||
&mut self,
|
||||
dependencies: RendererOutputDependencies,
|
||||
|
||||
@@ -49,12 +49,12 @@ impl CdpCommandTaskStep {
|
||||
}
|
||||
}
|
||||
|
||||
enum PageCommandAdoptionWaiter {
|
||||
enum SessionCommandPageWaiter {
|
||||
Initial(InitialDocumentPageBuildWaiter),
|
||||
Navigation(crate::conn::CommandWaitLifetime),
|
||||
}
|
||||
|
||||
impl PageCommandAdoptionWaiter {
|
||||
impl SessionCommandPageWaiter {
|
||||
async fn wait(self) -> Result<()> {
|
||||
match self {
|
||||
Self::Initial(waiter) => waiter.wait().await.map_err(anyhow::Error::msg),
|
||||
@@ -66,15 +66,15 @@ impl PageCommandAdoptionWaiter {
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingInitialDocumentCommand {
|
||||
waiter: Option<PageCommandAdoptionWaiter>,
|
||||
struct PendingSessionCommandAdmission {
|
||||
waiter: Option<SessionCommandPageWaiter>,
|
||||
admission: crate::conn::session_command_admission::SessionCommandAdmission,
|
||||
command: ParsedCdpCommand,
|
||||
host: ProtocolPageHostScope,
|
||||
}
|
||||
|
||||
enum PendingCdpCommandDispatchKind {
|
||||
InitialDocument(PendingInitialDocumentCommand),
|
||||
SessionAdmission(PendingSessionCommandAdmission),
|
||||
Workflow(super::command_workflow::PendingCommandWorkflowRecovery),
|
||||
Native(crate::domains::native::PendingNativeCommand),
|
||||
Runtime(Box<crate::domains::runtime::PendingRuntimeCommandDispatch>),
|
||||
@@ -98,7 +98,7 @@ enum PendingCdpCommandDispatchKind {
|
||||
}
|
||||
|
||||
enum CompletedCdpCommandDispatchKind {
|
||||
InitialDocument {
|
||||
SessionAdmission {
|
||||
command: ParsedCdpCommand,
|
||||
host: ProtocolPageHostScope,
|
||||
result: Result<()>,
|
||||
@@ -129,7 +129,7 @@ enum CompletedCdpCommandDispatchKind {
|
||||
impl PendingCdpCommandDispatchKind {
|
||||
fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::InitialDocument { .. } => "InitialDocument",
|
||||
Self::SessionAdmission { .. } => "SessionAdmission",
|
||||
Self::Workflow(_) => "Workflow",
|
||||
Self::Native(_) => "Native",
|
||||
Self::Runtime(_) => "Runtime",
|
||||
@@ -157,7 +157,7 @@ impl PendingCdpCommandDispatchKind {
|
||||
impl CompletedCdpCommandDispatchKind {
|
||||
fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::InitialDocument { .. } => "InitialDocument",
|
||||
Self::SessionAdmission { .. } => "SessionAdmission",
|
||||
Self::Workflow(_) => "Workflow",
|
||||
Self::Native(_) => "Native",
|
||||
Self::Runtime(_) => "Runtime",
|
||||
@@ -219,7 +219,7 @@ impl PendingCdpCommandDispatch {
|
||||
|
||||
pub fn command_id(&self) -> Option<u64> {
|
||||
match &self.inner {
|
||||
PendingCdpCommandDispatchKind::InitialDocument(pending) => {
|
||||
PendingCdpCommandDispatchKind::SessionAdmission(pending) => {
|
||||
Some(pending.command.request().id())
|
||||
}
|
||||
PendingCdpCommandDispatchKind::Native(pending) => Some(pending.command_id()),
|
||||
@@ -230,7 +230,7 @@ impl PendingCdpCommandDispatch {
|
||||
|
||||
pub fn session_id(&self) -> Option<&str> {
|
||||
match &self.inner {
|
||||
PendingCdpCommandDispatchKind::InitialDocument(pending) => {
|
||||
PendingCdpCommandDispatchKind::SessionAdmission(pending) => {
|
||||
pending.command.request().session_id()
|
||||
}
|
||||
PendingCdpCommandDispatchKind::Native(pending) => pending.session_id(),
|
||||
@@ -333,8 +333,8 @@ impl PendingCdpCommandDispatch {
|
||||
);
|
||||
}
|
||||
let inner = match self.inner {
|
||||
PendingCdpCommandDispatchKind::InitialDocument(pending) => {
|
||||
let PendingInitialDocumentCommand {
|
||||
PendingCdpCommandDispatchKind::SessionAdmission(pending) => {
|
||||
let PendingSessionCommandAdmission {
|
||||
command,
|
||||
host,
|
||||
mut admission,
|
||||
@@ -350,7 +350,7 @@ impl PendingCdpCommandDispatch {
|
||||
} => result,
|
||||
_ = host.wait_for_binding_retirement() => Err(NoDocumentLoaded.into()),
|
||||
};
|
||||
CompletedCdpCommandDispatchKind::InitialDocument {
|
||||
CompletedCdpCommandDispatchKind::SessionAdmission {
|
||||
admission,
|
||||
command,
|
||||
host,
|
||||
@@ -775,6 +775,34 @@ impl CdpConnection {
|
||||
self.start_admitted_command_dispatch(command, command_context, None)
|
||||
}
|
||||
|
||||
fn session_command_page_waiter(
|
||||
&self,
|
||||
owner: &CommandOwnerScope,
|
||||
command: &ParsedCdpCommand,
|
||||
) -> Option<SessionCommandPageWaiter> {
|
||||
if !command.requires_initial_document_adoption() {
|
||||
return None;
|
||||
}
|
||||
let slot = self.runtime_session_owner_slot_for_owner(owner)?;
|
||||
if let Some(waiter) = slot.initial_document_page_build_waiter() {
|
||||
return Some(SessionCommandPageWaiter::Initial(waiter));
|
||||
}
|
||||
// Browser observers can subscribe before parsing finishes. Inspector
|
||||
// IO needs only the exact prepared endpoint; ordinary Main work waits
|
||||
// for the navigation's Page adoption.
|
||||
if command.renderer_access() == CdpRendererCommandAccess::OwnerIndependent
|
||||
|| (command.can_use_prepared_inspector_endpoint()
|
||||
&& slot
|
||||
.page_slot()
|
||||
.prepared_document_inspector_endpoint()
|
||||
.is_some())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
slot.navigation_page_adoption_waiter()
|
||||
.map(SessionCommandPageWaiter::Navigation)
|
||||
}
|
||||
|
||||
fn start_admitted_command_dispatch(
|
||||
&mut self,
|
||||
command: &ParsedCdpCommand,
|
||||
@@ -864,36 +892,9 @@ impl CdpConnection {
|
||||
// concrete per-session Main/IO receiver. A completed Page build must
|
||||
// not let a newer command overtake an older, still-waking waiter.
|
||||
let mut direct_admission = admitted;
|
||||
if command.requires_initial_document_adoption() || req.method() == "Runtime.disable" {
|
||||
if command.requires_session_command_admission() {
|
||||
let owner = CommandOwnerScope::capture(self, req.session_id());
|
||||
// Disable can retire Browser state without a Page, while still
|
||||
// following earlier Main commands waiting for Page adoption.
|
||||
let waiter = command
|
||||
.requires_initial_document_adoption()
|
||||
.then(|| {
|
||||
self.runtime_session_owner_slot_for_owner(&owner)
|
||||
.and_then(|slot| {
|
||||
slot.initial_document_page_build_waiter()
|
||||
.map(PageCommandAdoptionWaiter::Initial)
|
||||
.or_else(|| {
|
||||
// Browser Page observers can subscribe to a prepared
|
||||
// Document; they must not wait for parsing to finish.
|
||||
(command.renderer_access()
|
||||
!= CdpRendererCommandAccess::OwnerIndependent
|
||||
&& !(command.renderer_access()
|
||||
== CdpRendererCommandAccess::Io
|
||||
&& matches!(domain, "Runtime" | "Debugger")
|
||||
&& slot
|
||||
.page_slot()
|
||||
.prepared_document_inspector_endpoint()
|
||||
.is_some()))
|
||||
.then(|| slot.navigation_page_adoption_waiter())
|
||||
.flatten()
|
||||
.map(PageCommandAdoptionWaiter::Navigation)
|
||||
})
|
||||
})
|
||||
})
|
||||
.flatten();
|
||||
let waiter = self.session_command_page_waiter(&owner, command);
|
||||
if let Some(session) = self.target_devtools_session_state_for_owner(&owner) {
|
||||
let queue = if command.renderer_access() == CdpRendererCommandAccess::Io {
|
||||
&session.lifecycle.io_admission
|
||||
@@ -913,8 +914,8 @@ impl CdpConnection {
|
||||
{
|
||||
let command = ParsedCdpCommand::parse_str(command.json())
|
||||
.expect("already parsed command");
|
||||
return self.pending_step(PendingCdpCommandDispatchKind::InitialDocument(
|
||||
PendingInitialDocumentCommand {
|
||||
return self.pending_step(PendingCdpCommandDispatchKind::SessionAdmission(
|
||||
PendingSessionCommandAdmission {
|
||||
waiter,
|
||||
admission,
|
||||
command,
|
||||
@@ -1467,7 +1468,7 @@ impl CdpConnection {
|
||||
) -> CdpCommandTaskStep {
|
||||
let mut out = Vec::new();
|
||||
match *completed.inner {
|
||||
CompletedCdpCommandDispatchKind::InitialDocument {
|
||||
CompletedCdpCommandDispatchKind::SessionAdmission {
|
||||
command,
|
||||
host,
|
||||
result,
|
||||
|
||||
@@ -372,24 +372,13 @@ impl PageTargetHost {
|
||||
}
|
||||
|
||||
pub(crate) fn initialize_runtime_inspector_sessions(&self) {
|
||||
let Some(endpoint) = self
|
||||
.runtime_slot
|
||||
.page_slot()
|
||||
.prepared_document_inspector_endpoint()
|
||||
.or_else(|| self.loaded_page().map(|page| page.inspector_endpoint()))
|
||||
else {
|
||||
let Some(endpoint) = self.runtime_slot.current_inspector_endpoint() else {
|
||||
return;
|
||||
};
|
||||
// Endpoint membership includes empty sessions; configuration snapshots
|
||||
// alone cannot decide whether a first IO command has a receiver.
|
||||
for restore in self
|
||||
.devtools_sessions
|
||||
.runtime_inspector_connection_snapshots()
|
||||
{
|
||||
endpoint.connect(
|
||||
restore.inspector_session_id,
|
||||
&restore.protocol_configuration.runtime_bindings,
|
||||
);
|
||||
for (key, bindings) in self.devtools_sessions.runtime_inspector_connections() {
|
||||
endpoint.connect(key.wire_session_id().map(str::to_owned), bindings);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -177,11 +177,7 @@ impl CdpConnection {
|
||||
self.target_renderer_runtime_inspector_session_id_for_owner(owner);
|
||||
let endpoint = self
|
||||
.runtime_session_owner_slot_for_owner(owner)
|
||||
.and_then(|slot| {
|
||||
slot.page_slot()
|
||||
.prepared_document_inspector_endpoint()
|
||||
.or_else(|| slot.loaded_page().map(|page| page.inspector_endpoint()))
|
||||
});
|
||||
.and_then(|slot| slot.current_inspector_endpoint());
|
||||
let Some(endpoint) = endpoint else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -4,21 +4,11 @@ use moli_core::page::{CompletedPageCommand, Page, PendingPageCommand, RendererAg
|
||||
|
||||
use super::{CdpConnection, CommandOwnerScope, RendererPageResidenceIdentity};
|
||||
|
||||
pub(crate) struct SessionScriptCleanup {
|
||||
owner: CommandOwnerScope,
|
||||
removals: Vec<SessionPageUpdates>,
|
||||
}
|
||||
|
||||
pub(crate) struct CompletedSessionScriptCleanup {
|
||||
owner: CommandOwnerScope,
|
||||
removals: Vec<CompletedSessionPageUpdates>,
|
||||
}
|
||||
|
||||
impl CdpConnection {
|
||||
pub(crate) fn prepare_session_script_cleanup(
|
||||
&mut self,
|
||||
session_id: &str,
|
||||
) -> SessionScriptCleanup {
|
||||
) -> SessionPageUpdates {
|
||||
let owner = self
|
||||
.session_route(Some(session_id))
|
||||
.map(CommandOwnerScope::for_route)
|
||||
@@ -36,46 +26,17 @@ impl CdpConnection {
|
||||
let _ = self.with_target_owner_state_for_owner_mut(&owner, |state| {
|
||||
state.remove_document_start_scripts_for_session(&session)
|
||||
});
|
||||
let mut removals = Vec::with_capacity(keys.len());
|
||||
let mut updates = SessionPageUpdates::default();
|
||||
if let Some(page) = self.loaded_page_mut_for_owner(&owner) {
|
||||
for key in keys {
|
||||
let mut updates = SessionPageUpdates::default();
|
||||
updates.push(
|
||||
page,
|
||||
"detached-session document-start script cleanup",
|
||||
page.start_remove_document_start_script_by_registry_key(&key),
|
||||
);
|
||||
removals.push(updates.retain_session_cleanup_authority());
|
||||
}
|
||||
}
|
||||
SessionScriptCleanup { owner, removals }
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionScriptCleanup {
|
||||
pub(crate) async fn wait(self) -> CompletedSessionScriptCleanup {
|
||||
let mut removals = Vec::with_capacity(self.removals.len());
|
||||
for updates in self.removals {
|
||||
removals.push(updates.wait().await);
|
||||
}
|
||||
CompletedSessionScriptCleanup {
|
||||
owner: self.owner,
|
||||
removals,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CompletedSessionScriptCleanup {
|
||||
pub(crate) fn finish(self, mut conn: Option<&mut CdpConnection>) -> SessionPageUpdateResult {
|
||||
let mut result = SessionPageUpdateResult::default();
|
||||
for updates in self.removals {
|
||||
let completed = updates.finish(
|
||||
conn.as_deref_mut()
|
||||
.and_then(|conn| conn.loaded_page_mut_for_owner(&self.owner)),
|
||||
);
|
||||
result.extend(completed);
|
||||
}
|
||||
result
|
||||
updates.retain_session_cleanup_authority()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,14 +68,6 @@ pub(crate) struct SessionPageUpdateResult {
|
||||
}
|
||||
|
||||
impl SessionPageUpdateResult {
|
||||
pub(crate) fn extend(&mut self, other: Self) {
|
||||
if self.first_error.is_none() {
|
||||
self.first_error = other.first_error;
|
||||
}
|
||||
if let Some(predecessor) = other.predecessor {
|
||||
predecessor.merge_into_same_stream_tail(&mut self.predecessor);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) fn into_result(self) -> Result<()> {
|
||||
self.first_error.map_or(Ok(()), Err)
|
||||
|
||||
@@ -105,6 +105,16 @@ pub(crate) struct DevToolsSessionState {
|
||||
}
|
||||
|
||||
impl DevToolsSessionState {
|
||||
fn needs_runtime_inspector_restore(&self) -> bool {
|
||||
self.inspector_session_state.v8_state.is_some()
|
||||
|| self.runtime_session_state.runtime_frontend_enabled
|
||||
|| self.web_mcp_enabled
|
||||
|| !self.runtime_bindings.is_empty()
|
||||
|| self.console_output_session_state.console_enabled
|
||||
|| !self.dom_debugger_event_listener_breakpoints.is_empty()
|
||||
|| !self.dom_debugger_xhr_breakpoints.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn is_closing(&self) -> bool {
|
||||
self.lifecycle.is_closing()
|
||||
}
|
||||
@@ -597,29 +607,28 @@ impl DevToolsSessionRegistry {
|
||||
bindings
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_inspector_connections(
|
||||
&self,
|
||||
) -> impl Iterator<Item = (&DevToolsSessionKey, &[RuntimeBindingDefinition])> {
|
||||
self.states
|
||||
.iter()
|
||||
.filter(|(_, state)| {
|
||||
!state.is_closing()
|
||||
&& (state.lifecycle.is_registered() || state.needs_runtime_inspector_restore())
|
||||
})
|
||||
.map(|(key, state)| (key, state.runtime_bindings.as_slice()))
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_inspector_restore_snapshots(
|
||||
&self,
|
||||
) -> Vec<RendererInspectorSessionRestoreSnapshot> {
|
||||
self.runtime_inspector_session_snapshots(false)
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_inspector_connection_snapshots(
|
||||
&self,
|
||||
) -> Vec<RendererInspectorSessionRestoreSnapshot> {
|
||||
self.runtime_inspector_session_snapshots(true)
|
||||
}
|
||||
|
||||
fn runtime_inspector_session_snapshots(
|
||||
&self,
|
||||
include_empty_connections: bool,
|
||||
) -> Vec<RendererInspectorSessionRestoreSnapshot> {
|
||||
self.states
|
||||
.iter()
|
||||
.filter_map(|(key, state)| {
|
||||
if state.is_closing() {
|
||||
if state.is_closing() || !state.needs_runtime_inspector_restore() {
|
||||
return None;
|
||||
}
|
||||
let restore = RendererInspectorSessionRestoreSnapshot {
|
||||
Some(RendererInspectorSessionRestoreSnapshot {
|
||||
inspector_session_id: key.wire_session_id().map(str::to_owned),
|
||||
v8_attach: V8InspectorSessionAttach::from_optional_state(
|
||||
state.inspector_session_state.v8_state.clone(),
|
||||
@@ -638,14 +647,7 @@ impl DevToolsSessionRegistry {
|
||||
.clone(),
|
||||
dom_debugger_xhr_breakpoints: state.dom_debugger_xhr_breakpoints.clone(),
|
||||
},
|
||||
};
|
||||
// Configured internal/implicit sessions keep their existing
|
||||
// restore contract. Empty endpoints belong only to committed
|
||||
// Browser sessions, never to attachment preparation drafts.
|
||||
((include_empty_connections && state.lifecycle.is_registered())
|
||||
|| restore.protocol_configuration.requires_restore()
|
||||
|| state.inspector_session_state.v8_state.is_some())
|
||||
.then_some(restore)
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1515,21 +1517,18 @@ mod tests {
|
||||
let mut sessions = DevToolsSessionRegistry::default();
|
||||
sessions.ensure_attached("SID-preparing");
|
||||
sessions.ensure_attached("SID-committed");
|
||||
assert!(sessions.runtime_inspector_connection_snapshots().is_empty());
|
||||
assert!(sessions.runtime_inspector_connections().next().is_none());
|
||||
|
||||
let committed = sessions.ensure_attached("SID-committed").lifecycle.clone();
|
||||
committed.mark_registered();
|
||||
let snapshots = sessions.runtime_inspector_connection_snapshots();
|
||||
assert_eq!(snapshots.len(), 1);
|
||||
assert_eq!(
|
||||
snapshots[0].inspector_session_id.as_deref(),
|
||||
Some("SID-committed")
|
||||
);
|
||||
let connections = sessions.runtime_inspector_connections().collect::<Vec<_>>();
|
||||
assert_eq!(connections.len(), 1);
|
||||
assert_eq!(connections[0].0.wire_session_id(), Some("SID-committed"));
|
||||
assert!(sessions.runtime_inspector_restore_snapshots().is_empty());
|
||||
|
||||
committed.mark_closing();
|
||||
committed.mark_registered();
|
||||
assert!(sessions.runtime_inspector_connection_snapshots().is_empty());
|
||||
assert!(sessions.runtime_inspector_connections().next().is_none());
|
||||
|
||||
sessions
|
||||
.primary_mut()
|
||||
@@ -1538,6 +1537,10 @@ mod tests {
|
||||
let snapshots = sessions.runtime_inspector_restore_snapshots();
|
||||
assert_eq!(snapshots.len(), 1);
|
||||
assert_eq!(snapshots[0].inspector_session_id, None);
|
||||
let connections = sessions.runtime_inspector_connections().collect::<Vec<_>>();
|
||||
assert_eq!(connections.len(), 1);
|
||||
assert_eq!(connections[0].0, &DevToolsSessionKey::Primary);
|
||||
assert_eq!(connections[0].1, &[binding("internal")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -154,6 +154,14 @@ impl TargetRuntimeSlot {
|
||||
&mut self.page_slot
|
||||
}
|
||||
|
||||
pub(crate) fn current_inspector_endpoint(
|
||||
&self,
|
||||
) -> Option<moli_core::page::RendererPageInspectorEndpoint> {
|
||||
self.page_slot
|
||||
.prepared_document_inspector_endpoint()
|
||||
.or_else(|| self.loaded_page().map(Page::inspector_endpoint))
|
||||
}
|
||||
|
||||
pub(crate) fn loaded_page(&self) -> Option<&Page> {
|
||||
self.page_slot.loaded_page()
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
use super::ProtocolWorkflowState;
|
||||
use crate::conn::{AutoAttachPolicyIdentity, CommandDispatchContext};
|
||||
use crate::conn::AutoAttachPolicyIdentity;
|
||||
use crate::domains::command_output::CommandOutputPlan;
|
||||
use crate::domains::target::{
|
||||
AutoAttachSweepRollback, PreparedAutoAttachSweep, TargetDetachmentFailureCleanup,
|
||||
TargetDetachmentRecovery,
|
||||
};
|
||||
use crate::domains::target::{AutoAttachSweepRollback, PreparedAutoAttachSweep};
|
||||
|
||||
impl ProtocolWorkflowState<'_> {
|
||||
pub(crate) fn prepare_auto_attach_sweep(
|
||||
@@ -57,29 +54,6 @@ impl ProtocolWorkflowState<'_> {
|
||||
) -> CommandOutputPlan {
|
||||
sweep.finish(self.connection)
|
||||
}
|
||||
|
||||
pub(crate) fn commit_auto_attach_detachment(
|
||||
self,
|
||||
detachment: crate::domains::target::TargetDetachment,
|
||||
) -> CommandOutputPlan {
|
||||
detachment.commit_in_browser(self.connection)
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_auto_attach_detachment_recovery(
|
||||
self,
|
||||
cleanup: TargetDetachmentFailureCleanup,
|
||||
response: CommandOutputPlan,
|
||||
context: &mut CommandDispatchContext,
|
||||
) -> TargetDetachmentRecovery {
|
||||
cleanup.prepare(self.connection, context, response)
|
||||
}
|
||||
|
||||
pub(crate) fn finish_auto_attach_detachment_recovery(
|
||||
self,
|
||||
recovery: TargetDetachmentRecovery,
|
||||
) -> CommandOutputPlan {
|
||||
recovery.finish(self.connection)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -234,6 +234,35 @@ fn start(
|
||||
*pending
|
||||
}
|
||||
|
||||
fn disable(
|
||||
handle: &ProtocolStateHandle,
|
||||
id: u64,
|
||||
owner: &str,
|
||||
) -> (Vec<Value>, Vec<crate::conn::CdpSchedulerEvent>) {
|
||||
let command = ParsedCdpCommand::from_serializable(json!({
|
||||
"id":id,"sessionId":owner,"method":"Target.setAutoAttach",
|
||||
"params":{"autoAttach":false,"waitForDebuggerOnStart":false,"flatten":true},
|
||||
}))
|
||||
.unwrap();
|
||||
let CdpCommandTaskStep::Complete(outcome) = handle
|
||||
.with_state(|state| {
|
||||
state.start_parsed_command_dispatch_with_context(&command, &mut Default::default())
|
||||
})
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("Browser disable has no asynchronous commit window");
|
||||
};
|
||||
let (events, scheduler, predecessors) = outcome.into_protocol_event_parts();
|
||||
assert!(predecessors.is_empty());
|
||||
(
|
||||
events
|
||||
.into_iter()
|
||||
.map(|event| event.into_protocol_message())
|
||||
.collect(),
|
||||
scheduler,
|
||||
)
|
||||
}
|
||||
|
||||
fn recover(
|
||||
handle: &ProtocolStateHandle,
|
||||
id: u64,
|
||||
@@ -352,14 +381,7 @@ async fn auto_attach_enable_owns_browser_commit_and_rejects_retired_policy_after
|
||||
let mut replacement = None;
|
||||
let mut replacement_context = CommandDispatchContext::default();
|
||||
if phase == 3 || phase == 4 {
|
||||
let mut disabled_context = CommandDispatchContext::default();
|
||||
let disabled = start(&handle, 1902, &owner_session, false, &mut disabled_context)
|
||||
.wait()
|
||||
.await;
|
||||
success(
|
||||
&finish(&handle, disabled, &mut disabled_context).await,
|
||||
1902,
|
||||
);
|
||||
success(&disable(&handle, 1902, &owner_session).0, 1902);
|
||||
if phase == 4 {
|
||||
let reenabled = Box::pin(
|
||||
start(
|
||||
@@ -445,142 +467,42 @@ async fn auto_attach_enable_owns_browser_commit_and_rejects_retired_policy_after
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auto_attach_disable_revokes_browser_route_before_native_cleanup_and_preserves_successor() {
|
||||
for phase in 0..4 {
|
||||
let (fixture, owner_session) = fixture().await;
|
||||
let owner = fixture.state;
|
||||
let handle = owner.handle();
|
||||
let mut enabled_context = CommandDispatchContext::default();
|
||||
let enabled = start(&handle, 1910, &owner_session, true, &mut enabled_context)
|
||||
.wait()
|
||||
.await;
|
||||
let enabled = finish(&handle, enabled, &mut enabled_context).await;
|
||||
let old_session = attached(&enabled).pop().unwrap();
|
||||
// Install a real session-owned Native script. Empty session disposal
|
||||
// can finish synchronously and would not exercise the cleanup wait.
|
||||
let preload = ParsedCdpCommand::parse_str(
|
||||
json!({
|
||||
"id":1915,"sessionId":old_session,"method":"Page.addScriptToEvaluateOnNewDocument",
|
||||
"params":{"source":"globalThis.autoAttachCleanup = true"},
|
||||
})
|
||||
.to_string(),
|
||||
async fn auto_attach_disable_commits_synchronously_while_native_cleanup_waits() {
|
||||
let (mut fixture, owner_session) = fixture().await;
|
||||
fixture
|
||||
.process_async(
|
||||
json!({"id":1910,"sessionId":owner_session,"method":"Target.setAutoAttach",
|
||||
"params":{"autoAttach":true,"waitForDebuggerOnStart":false,"flatten":true,
|
||||
"filter":[{"type":"page"},{"exclude":true}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let mut preload_context = CommandDispatchContext::default();
|
||||
let preload = handle
|
||||
.with_state(|state| {
|
||||
state.start_parsed_command_dispatch_with_context(&preload, &mut preload_context)
|
||||
})
|
||||
.unwrap();
|
||||
if let CdpCommandTaskStep::Pending(preload) = preload {
|
||||
finish(&handle, preload.wait().await, &mut preload_context).await;
|
||||
}
|
||||
let (gate, guard, entered, release) = handle
|
||||
.with_state(|state| {
|
||||
// The test-only setup owns no state borrow while the Native gate waits.
|
||||
let page = state
|
||||
.connection
|
||||
.loaded_page_mut_for_protocol_access(Some("SID-auto-owned"))
|
||||
.unwrap();
|
||||
let (entered, waiting) = tokio::sync::oneshot::channel();
|
||||
let (release, held) = std::sync::mpsc::channel();
|
||||
let (gate, guard) = page
|
||||
.start_cdp_call(
|
||||
1999,
|
||||
None,
|
||||
moli_core::RendererNativeOperation::then(
|
||||
moli_core::RendererPageCommand::ChildFrameTreeSnapshot,
|
||||
move |_| {
|
||||
let _ = entered.send(());
|
||||
let _ = held.recv();
|
||||
moli_core::RendererNativeOperationStep::Complete(
|
||||
moli_core::RendererNativeProtocolResponse::success(json!({})),
|
||||
)
|
||||
},
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
(gate, guard, waiting, ReleaseOnDrop(Some(release)))
|
||||
})
|
||||
.unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), entered)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut context = CommandDispatchContext::default();
|
||||
let mut waiting =
|
||||
Box::pin(start(&handle, 1911, &owner_session, false, &mut context).wait());
|
||||
peer(&handle);
|
||||
if phase == 1 {
|
||||
drop(waiting);
|
||||
waiting = Box::pin(recover(&handle, 1911, &owner_session, &mut context).wait());
|
||||
}
|
||||
let mut replacement_context = CommandDispatchContext::default();
|
||||
let completed = tokio::time::timeout(std::time::Duration::from_secs(5), waiting)
|
||||
.await
|
||||
.unwrap();
|
||||
let replacement = if phase == 3 {
|
||||
let pending = Box::pin(
|
||||
start(
|
||||
&handle,
|
||||
1912,
|
||||
&owner_session,
|
||||
true,
|
||||
&mut replacement_context,
|
||||
)
|
||||
.wait(),
|
||||
);
|
||||
Some(pending)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
drop(release);
|
||||
gate.wait().await.unwrap();
|
||||
drop(guard);
|
||||
let completed = if phase == 2 {
|
||||
drop(completed);
|
||||
recover(&handle, 1911, &owner_session, &mut context)
|
||||
.wait()
|
||||
.await
|
||||
} else {
|
||||
completed
|
||||
};
|
||||
let messages = finish(&handle, completed, &mut context).await;
|
||||
success(&messages, 1911);
|
||||
assert_eq!(
|
||||
messages
|
||||
.iter()
|
||||
.filter(|message| message["method"] == "Target.detachedFromTarget"
|
||||
&& message["params"]["sessionId"] == old_session)
|
||||
.count(),
|
||||
1,
|
||||
"{messages:?}"
|
||||
);
|
||||
let expected = if let Some(replacement) = replacement {
|
||||
let ready = tokio::time::timeout(std::time::Duration::from_secs(5), replacement)
|
||||
.await
|
||||
.unwrap();
|
||||
let messages = finish(&handle, ready, &mut replacement_context).await;
|
||||
success(&messages, 1912);
|
||||
let sessions = attached(&messages);
|
||||
assert_eq!(sessions.len(), 1);
|
||||
assert_ne!(sessions[0], old_session);
|
||||
sessions
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
handle
|
||||
.with_state(|state| {
|
||||
assert!(!state.connection.has_attached_devtools_session(&old_session));
|
||||
assert_eq!(
|
||||
state
|
||||
.connection
|
||||
.auto_attached_sessions_for_owner(Some(&owner_session)),
|
||||
expected
|
||||
);
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
.await;
|
||||
let old_session = attached(&fixture.take_all()).pop().unwrap();
|
||||
fixture
|
||||
.process_async(json!({"id":1915,"sessionId":old_session,
|
||||
"method":"Page.addScriptToEvaluateOnNewDocument",
|
||||
"params":{"source":"globalThis.autoAttachCleanup = true"}}))
|
||||
.await;
|
||||
let (gate, guard, release) = hold_renderer(&mut fixture).await;
|
||||
let (messages, work) = disable(&fixture.handle(), 1911, &owner_session);
|
||||
success(&messages, 1911);
|
||||
assert_eq!(
|
||||
messages
|
||||
.iter()
|
||||
.filter(|message| message["method"] == "Target.detachedFromTarget"
|
||||
&& message["params"]["sessionId"] == old_session)
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
fixture.with_fixture(|conn| assert!(conn.session_route(Some(&old_session)).is_none()));
|
||||
fixture
|
||||
.route_direct_command_output_for_test(Vec::new(), work)
|
||||
.await;
|
||||
drop(release);
|
||||
gate.wait().await.unwrap();
|
||||
drop(guard);
|
||||
fixture
|
||||
.wait_for_direct_command_work_completion_for_test("disabled auto-attach native work")
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -915,6 +915,9 @@ mod tests {
|
||||
}))
|
||||
.await;
|
||||
context.expect_result(1, json!({"identifier": "1"}), Some("SID-direct-state"));
|
||||
let script_owner = context.with_fixture(|conn| {
|
||||
crate::conn::CommandOwnerScope::capture(conn, Some("SID-direct-state"))
|
||||
});
|
||||
let owner = context.state;
|
||||
let handle = owner.handle();
|
||||
let pending = handle
|
||||
@@ -931,7 +934,9 @@ mod tests {
|
||||
let completed = pending.wait().await;
|
||||
ready.send(()).unwrap();
|
||||
released.await.unwrap();
|
||||
task_handle.with_state(|state| completed.finish(Some(state.connection)))
|
||||
task_handle.with_state(|state| {
|
||||
completed.finish(state.connection.loaded_page_mut_for_owner(&script_owner))
|
||||
})
|
||||
};
|
||||
tokio::pin!(workflow);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(30), async {
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
use anyhow::Result;
|
||||
|
||||
use super::ProtocolWorkflowState;
|
||||
use crate::conn::{
|
||||
BackgroundProtocolEvent, CompletedSessionPageUpdates, CompletedSessionScriptCleanup,
|
||||
SessionPageUpdateResult,
|
||||
};
|
||||
use crate::conn::{BackgroundProtocolEvent, CompletedSessionPageUpdates, SessionPageUpdateResult};
|
||||
use crate::domains::target::session_disposal::{
|
||||
FailedSessionPageRetirement, SessionDisposalIdentity,
|
||||
};
|
||||
@@ -191,13 +188,4 @@ impl ProtocolWorkflowState<'_> {
|
||||
};
|
||||
completed.finish(page)
|
||||
}
|
||||
|
||||
pub(crate) fn finish_session_script_cleanup(
|
||||
self,
|
||||
identity: &SessionDisposalIdentity,
|
||||
completed: CompletedSessionScriptCleanup,
|
||||
) -> SessionPageUpdateResult {
|
||||
let current = identity.cleanup_binding_was_not_replaced(self.connection);
|
||||
completed.finish(current.then_some(self.connection))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,11 +415,7 @@ impl CdpConnection {
|
||||
session_key: moli_page_types::DevToolsSessionKey::Primary,
|
||||
});
|
||||
if let Some(slot) = self.runtime_session_owner_slot_for_owner(&owner)
|
||||
&& (slot.has_loaded_page()
|
||||
|| slot
|
||||
.page_slot()
|
||||
.prepared_document_inspector_endpoint()
|
||||
.is_some())
|
||||
&& slot.current_inspector_endpoint().is_some()
|
||||
{
|
||||
// Existing sessions keep their own ordered configuration; a new
|
||||
// attachment initializes only its own backend connection.
|
||||
|
||||
@@ -342,7 +342,7 @@ pub(crate) enum PreparedSessionHandlerDisposal {
|
||||
protocol: Vec<BackgroundProtocolEvent>,
|
||||
},
|
||||
Page {
|
||||
scripts: crate::conn::SessionScriptCleanup,
|
||||
scripts: crate::conn::SessionPageUpdates,
|
||||
events: Vec<BackgroundProtocolEvent>,
|
||||
},
|
||||
PageUpdates(crate::conn::SessionPageUpdates),
|
||||
@@ -472,7 +472,7 @@ impl PreparedSessionHandlerDisposal {
|
||||
let removed_scripts = scripts.wait().await;
|
||||
let identity = identity.clone();
|
||||
driver.with_state(move |state| {
|
||||
state.finish_session_script_cleanup(&identity, removed_scripts)
|
||||
state.finish_session_page_updates(&identity, removed_scripts)
|
||||
})
|
||||
}
|
||||
Self::PageUpdates(updates) => {
|
||||
|
||||
@@ -17,7 +17,6 @@ pub(crate) mod activation;
|
||||
mod automation;
|
||||
pub(crate) use automation::{PreparedAutomationTargetCreation, start_automation_lifecycle_command};
|
||||
mod attachment;
|
||||
pub(crate) use attachment::{TargetDetachmentFailureCleanup, TargetDetachmentRecovery};
|
||||
mod auto_attach;
|
||||
mod browser_context;
|
||||
mod browser_context_disposal;
|
||||
@@ -27,7 +26,6 @@ mod events;
|
||||
pub(crate) use events::target_created_automation_event;
|
||||
mod info;
|
||||
mod opening;
|
||||
pub(crate) use attachment::TargetDetachment;
|
||||
pub(crate) use auto_attach::{AutoAttachSweepRollback, PreparedAutoAttachSweep};
|
||||
pub(crate) use browser_context_disposal::{
|
||||
BrowserContextDisposalIdentity, PreparedBrowserContextDisposal,
|
||||
|
||||
@@ -50,42 +50,6 @@ fn attach_session_events_then_result_step(
|
||||
TargetCommandTaskStep::Complete(plan)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TargetCommandOutput {
|
||||
plan: CommandOutputPlan,
|
||||
side_effects: events::TargetProtocolSideEffects,
|
||||
}
|
||||
|
||||
impl TargetCommandOutput {
|
||||
fn background_events_mut(&mut self) -> &mut Vec<BackgroundProtocolEvent> {
|
||||
self.side_effects.background_events_mut()
|
||||
}
|
||||
|
||||
fn target_events_mut(&mut self) -> &mut events::TargetProtocolSideEffects {
|
||||
&mut self.side_effects
|
||||
}
|
||||
|
||||
fn push_success(&mut self) {
|
||||
self.flush_side_effects();
|
||||
self.plan.push_success();
|
||||
}
|
||||
|
||||
fn push_error(&mut self, code: i32, message: impl std::fmt::Display) {
|
||||
self.flush_side_effects();
|
||||
self.plan
|
||||
.push_error_without_session(code, format!("{message:#}"));
|
||||
}
|
||||
|
||||
fn into_plan(mut self) -> CommandOutputPlan {
|
||||
self.flush_side_effects();
|
||||
self.plan
|
||||
}
|
||||
|
||||
fn flush_side_effects(&mut self) {
|
||||
self.plan.extend(self.side_effects.drain_into_plan());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn start_attach_to_target_command(
|
||||
conn: &mut CdpConnection,
|
||||
cmd: &Cmd<'_>,
|
||||
@@ -455,7 +419,6 @@ struct DetachParams {
|
||||
|
||||
mod detachment;
|
||||
pub(crate) use detachment::TargetDetachment;
|
||||
pub(crate) use detachment::{TargetDetachmentFailureCleanup, TargetDetachmentRecovery};
|
||||
|
||||
pub(super) fn start_detach_from_target_command(
|
||||
conn: &mut CdpConnection,
|
||||
|
||||
@@ -2,8 +2,8 @@ use anyhow::Result;
|
||||
|
||||
use super::*;
|
||||
use crate::conn::{
|
||||
CdpSessionRoute, CommandDispatchContext, ProtocolWorkflowDriver, SessionDisposalPlan,
|
||||
SessionDisposalTarget, TargetSessionDetachCleanupPlan,
|
||||
CdpSessionRoute, ProtocolWorkflowDriver, SessionDisposalPlan, SessionDisposalTarget,
|
||||
TargetSessionDetachCleanupPlan,
|
||||
};
|
||||
use crate::domains::target::session_disposal::{
|
||||
PreparedSessionDisposal, SessionDisposalError, SessionDisposalIdentity,
|
||||
@@ -21,29 +21,11 @@ struct SessionDetachment {
|
||||
response_before_event: bool,
|
||||
}
|
||||
|
||||
mod recovery;
|
||||
pub(crate) use recovery::{TargetDetachmentFailureCleanup, TargetDetachmentRecovery};
|
||||
|
||||
#[derive(Clone)]
|
||||
enum SessionDetachmentCommit {
|
||||
Browser { emit_event: bool },
|
||||
Target(TargetSessionDetachCleanupPlan),
|
||||
}
|
||||
|
||||
pub(crate) struct TargetDetachmentOutput {
|
||||
sessions: Vec<SessionDetachmentOutput>,
|
||||
}
|
||||
|
||||
struct SessionDetachmentOutput {
|
||||
identity: SessionDisposalIdentity,
|
||||
commit: SessionDetachmentCommit,
|
||||
child: bool,
|
||||
response_before_event: bool,
|
||||
background_events: Vec<BackgroundProtocolEvent>,
|
||||
protocol_events: Vec<BackgroundProtocolEvent>,
|
||||
result: Result<Option<moli_core::RendererOutputFence>>,
|
||||
}
|
||||
|
||||
impl TargetDetachment {
|
||||
pub(in crate::domains::target) fn prepare_auto_attached_sessions(
|
||||
conn: &mut CdpConnection,
|
||||
@@ -79,10 +61,6 @@ impl TargetDetachment {
|
||||
Self { sessions }
|
||||
}
|
||||
|
||||
pub(in crate::domains::target) fn failure_cleanup(&self) -> TargetDetachmentFailureCleanup {
|
||||
TargetDetachmentFailureCleanup::new(&self.sessions)
|
||||
}
|
||||
|
||||
pub(super) fn prepare(
|
||||
conn: &mut CdpConnection,
|
||||
command_session_id: Option<&str>,
|
||||
@@ -200,27 +178,44 @@ impl TargetDetachment {
|
||||
}
|
||||
|
||||
pub(crate) fn commit_in_browser(self, conn: &mut CdpConnection) -> CommandOutputPlan {
|
||||
let mut native = Vec::new();
|
||||
let mut sessions = Vec::new();
|
||||
let mut native = Vec::with_capacity(self.sessions.len());
|
||||
let mut prefix = CommandOutputPlan::default();
|
||||
let mut output = CommandOutputPlan::default();
|
||||
let mut replied = false;
|
||||
for mut session in self.sessions {
|
||||
prefix.extend_background_events(session.disposal.take_browser_events());
|
||||
native.push((session.identity.clone(), session.disposal));
|
||||
sessions.push(SessionDetachmentOutput {
|
||||
identity: session.identity,
|
||||
commit: session.commit,
|
||||
child: session.child,
|
||||
response_before_event: session.response_before_event,
|
||||
background_events: Vec::new(),
|
||||
protocol_events: Vec::new(),
|
||||
result: Ok(None),
|
||||
});
|
||||
let (events, error) =
|
||||
commit_session_detachment(conn, &session.identity, session.commit);
|
||||
if let Some(error) = error {
|
||||
output.extend_background_events(events);
|
||||
if session.child {
|
||||
tracing::warn!(session_id = session.identity.plan().session_id(), %error,
|
||||
"failed to dispose child session");
|
||||
} else if !replied {
|
||||
let code = if matches!(
|
||||
session.identity.plan().target(),
|
||||
SessionDisposalTarget::Browser
|
||||
) {
|
||||
-31998
|
||||
} else {
|
||||
-32000
|
||||
};
|
||||
output.push_error_without_session(code, format!("{error:#}"));
|
||||
replied = true;
|
||||
}
|
||||
} else {
|
||||
if !session.child && session.response_before_event && !replied {
|
||||
output.push_success();
|
||||
replied = true;
|
||||
}
|
||||
output.extend_background_events(events);
|
||||
}
|
||||
native.push((session.identity, session.disposal));
|
||||
}
|
||||
// No Renderer receipt/fence belongs to the Browser detach response.
|
||||
prefix.extend(
|
||||
TargetDetachmentOutput { sessions }
|
||||
.finish(conn, &mut CommandDispatchContext::default()),
|
||||
);
|
||||
if !replied {
|
||||
output.push_success();
|
||||
}
|
||||
prefix.extend(output);
|
||||
// Each retirement owns its native barrier. A busy target must not
|
||||
// delay another target's finalizer or its successor session.
|
||||
for (identity, disposal) in native {
|
||||
@@ -244,100 +239,6 @@ impl TargetDetachment {
|
||||
}
|
||||
prefix
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(in crate::domains::target) async fn run(
|
||||
self,
|
||||
driver: &mut ProtocolWorkflowDriver,
|
||||
) -> TargetDetachmentOutput {
|
||||
let mut sessions = Vec::with_capacity(self.sessions.len());
|
||||
for session in self.sessions {
|
||||
let mut background_events = Vec::new();
|
||||
let mut protocol_events = Vec::new();
|
||||
let result = session
|
||||
.disposal
|
||||
.run(driver, &mut background_events, &mut protocol_events)
|
||||
.await;
|
||||
sessions.push(SessionDetachmentOutput {
|
||||
identity: session.identity,
|
||||
commit: session.commit,
|
||||
child: session.child,
|
||||
response_before_event: session.response_before_event,
|
||||
background_events,
|
||||
protocol_events,
|
||||
result,
|
||||
});
|
||||
}
|
||||
TargetDetachmentOutput { sessions }
|
||||
}
|
||||
}
|
||||
|
||||
impl TargetDetachmentOutput {
|
||||
pub(crate) fn finish(
|
||||
self,
|
||||
conn: &mut CdpConnection,
|
||||
command_context: &mut CommandDispatchContext,
|
||||
) -> CommandOutputPlan {
|
||||
let mut output = TargetCommandOutput::default();
|
||||
let mut replied = false;
|
||||
for session in self.sessions {
|
||||
command_context
|
||||
.protocol_events_mut()
|
||||
.extend(session.protocol_events);
|
||||
output
|
||||
.background_events_mut()
|
||||
.extend(session.background_events);
|
||||
let cleanup_error = match session.result {
|
||||
Ok(predecessor) => {
|
||||
if let Some(predecessor) = predecessor {
|
||||
command_context.add_renderer_output_dependency(predecessor);
|
||||
}
|
||||
None
|
||||
}
|
||||
Err(error) => Some(error),
|
||||
};
|
||||
let (events, commit_error) =
|
||||
commit_session_detachment(conn, &session.identity, session.commit);
|
||||
let result = match cleanup_error.or(commit_error) {
|
||||
Some(error) => {
|
||||
output.target_events_mut().extend_background_events(events);
|
||||
Err(error)
|
||||
}
|
||||
None => Ok(events),
|
||||
};
|
||||
match result {
|
||||
Ok(events) => {
|
||||
if !session.child && session.response_before_event && !replied {
|
||||
output.push_success();
|
||||
replied = true;
|
||||
}
|
||||
output.target_events_mut().extend_background_events(events);
|
||||
}
|
||||
Err(error) if session.child => {
|
||||
tracing::warn!(session_id = session.identity.plan().session_id(), %error,
|
||||
"failed to dispose child session");
|
||||
}
|
||||
Err(error) => {
|
||||
if !replied {
|
||||
let code = if matches!(
|
||||
session.identity.plan().target(),
|
||||
SessionDisposalTarget::Browser
|
||||
) {
|
||||
-31998
|
||||
} else {
|
||||
-32000
|
||||
};
|
||||
output.push_error(code, error);
|
||||
replied = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !replied {
|
||||
output.push_success();
|
||||
}
|
||||
output.into_plan()
|
||||
}
|
||||
}
|
||||
|
||||
fn commit_session_detachment(
|
||||
@@ -382,18 +283,11 @@ fn route_target_id(route: &CdpSessionRoute) -> Option<&str> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::conn::{BrowserContext, RendererPageResidenceIdentity};
|
||||
use crate::conn::BrowserContext;
|
||||
use crate::testing::TestContext;
|
||||
|
||||
#[tokio::test]
|
||||
async fn multi_page_detachment_waits_for_every_original_output_prefix() {
|
||||
use moli_core::{
|
||||
PageId, RendererOutputCursor, RendererOutputFence, RendererOutputItem,
|
||||
RendererOutputPublication, RendererOutputRecord, RendererOutputStreamControl,
|
||||
RendererOutputStreamIdentity, RendererOutputTransportMessage,
|
||||
RendererProtocolObservation,
|
||||
};
|
||||
|
||||
async fn browser_commit_preserves_cascade_order_and_supervises_native_cleanup() {
|
||||
let mut browser = BrowserContext::new("BID-detach-prefixes".into());
|
||||
browser.set_active_target_id("TID-first");
|
||||
browser.attach_active_session("SID-first");
|
||||
@@ -406,286 +300,185 @@ mod tests {
|
||||
);
|
||||
let mut context = TestContext::new();
|
||||
context.with_fixture(|conn| conn.install_browser_context_fixture_for_test(browser));
|
||||
let prefixes = [
|
||||
("TID-first", "SID-first", 71, 3),
|
||||
("TID-second", "SID-second", 72, 1),
|
||||
]
|
||||
.map(|(target, session, page, sequence)| {
|
||||
let stream = RendererOutputStreamIdentity::new_page_for_protocol_test(
|
||||
PageId::new_for_testing(page),
|
||||
);
|
||||
context.with_fixture(|conn| {
|
||||
let residence =
|
||||
RendererPageResidenceIdentity::from_residence(stream.residence()).unwrap();
|
||||
conn.bind_renderer_page_output_owner(
|
||||
residence,
|
||||
crate::conn::TargetPageResidenceIdentity::new_for_test(
|
||||
"BID-detach-prefixes".into(),
|
||||
Some(target.into()),
|
||||
page,
|
||||
),
|
||||
);
|
||||
conn.apply_renderer_output_stream_control(RendererOutputStreamControl::Opened {
|
||||
stream,
|
||||
});
|
||||
});
|
||||
(target, session, stream, sequence)
|
||||
});
|
||||
let (output, dependencies) = context.with_fixture(|conn| {
|
||||
let sessions = prefixes
|
||||
.iter()
|
||||
.map(|&(target, session, stream, sequence)| {
|
||||
let (output, work) = context.with_fixture(|conn| {
|
||||
let sessions = [("TID-first", "SID-first"), ("TID-second", "SID-second")]
|
||||
.into_iter()
|
||||
.map(|(target, session)| {
|
||||
let route = conn.session_route(Some(session)).unwrap();
|
||||
let plan = SessionDisposalPlan::for_session_route(session, &route).unwrap();
|
||||
let identity = SessionDisposalIdentity::capture(conn, plan.clone());
|
||||
conn.mark_session_closing(&plan);
|
||||
SessionDetachmentOutput {
|
||||
identity,
|
||||
let disposal = PreparedSessionDisposal::prepare(conn, plan);
|
||||
SessionDetachment {
|
||||
identity: disposal.identity(),
|
||||
disposal,
|
||||
commit: SessionDetachmentCommit::Target(
|
||||
TargetSessionDetachCleanupPlan::new(target, session, None, None),
|
||||
),
|
||||
child: true,
|
||||
response_before_event: false,
|
||||
background_events: Vec::new(),
|
||||
protocol_events: Vec::new(),
|
||||
result: Ok(Some(RendererOutputFence::new_for_test(
|
||||
RendererOutputCursor::new_for_test(stream, sequence),
|
||||
))),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mut command_context = CommandDispatchContext::default();
|
||||
let output = TargetDetachmentOutput { sessions }.finish(conn, &mut command_context);
|
||||
assert!(
|
||||
!output.is_empty(),
|
||||
"the original response must remain in the command output plan"
|
||||
);
|
||||
assert!(command_context.take_protocol_events().is_empty());
|
||||
assert!(
|
||||
conn.take_published_protocol_work().is_empty(),
|
||||
"Target cleanup must not publish the command response as background work"
|
||||
);
|
||||
(output, command_context.take_renderer_output_dependencies())
|
||||
});
|
||||
assert_eq!(dependencies.iter().count(), 2);
|
||||
for (index, &(_, _, stream, sequence)) in prefixes.iter().enumerate() {
|
||||
context.with_fixture(|conn| {
|
||||
assert!(
|
||||
!dependencies
|
||||
.iter()
|
||||
.all(|fence| conn.renderer_output_cursor_is_projected(fence.cursor()))
|
||||
)
|
||||
});
|
||||
for sequence in 1..=sequence {
|
||||
let outcome = context
|
||||
.handle()
|
||||
.with_state(|state| {
|
||||
state.admit_renderer_output(RendererOutputTransportMessage::Publication(
|
||||
RendererOutputPublication::new_for_test(
|
||||
RendererOutputCursor::new_for_test(stream, sequence),
|
||||
vec![RendererOutputRecord::new_for_test(
|
||||
RendererOutputItem::Observation(
|
||||
RendererProtocolObservation::RuntimeLifecycleError {
|
||||
text: "historical renderer output".into(),
|
||||
execution_context_id: None,
|
||||
},
|
||||
),
|
||||
)],
|
||||
),
|
||||
))
|
||||
})
|
||||
.unwrap();
|
||||
let (events, scheduler) = outcome.into_protocol_event_parts();
|
||||
assert!(events.is_empty());
|
||||
for event in scheduler {
|
||||
let crate::conn::CdpSchedulerEvent::ProtocolTaskPrepared { pending } = event
|
||||
else {
|
||||
panic!("expected the exact renderer projection");
|
||||
};
|
||||
let completed = context.drive_owned_wait(pending.wait()).await;
|
||||
let outcome = context
|
||||
.handle()
|
||||
.with_state(|state| state.complete_owned_protocol_scheduler_work(completed))
|
||||
.unwrap();
|
||||
assert!(outcome.into_protocol_event_parts().0.is_empty());
|
||||
}
|
||||
let output = TargetDetachment { sessions }.commit_in_browser(conn);
|
||||
for session in ["SID-first", "SID-second"] {
|
||||
assert!(conn.session_route(Some(session)).is_none());
|
||||
}
|
||||
context.with_fixture(|conn| {
|
||||
assert_eq!(
|
||||
dependencies
|
||||
.iter()
|
||||
.all(|fence| conn.renderer_output_cursor_is_projected(fence.cursor())),
|
||||
index == 1
|
||||
);
|
||||
});
|
||||
}
|
||||
let events = output
|
||||
let work = conn.take_scheduler_events();
|
||||
assert_eq!(
|
||||
work.iter()
|
||||
.filter(|event| matches!(
|
||||
event,
|
||||
crate::conn::CdpSchedulerEvent::ProtocolTaskPrepared { .. }
|
||||
))
|
||||
.count(),
|
||||
2,
|
||||
"each session has independent supervised native work"
|
||||
);
|
||||
(output, work)
|
||||
});
|
||||
let messages = output
|
||||
.into_background_events(Some(91), Some("SID-browser-command"))
|
||||
.into_iter()
|
||||
.map(BackgroundProtocolEvent::into_protocol_message)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(messages.len(), 3, "{messages:?}");
|
||||
for (message, session) in messages.iter().zip(["SID-first", "SID-second"]) {
|
||||
assert_eq!(message["method"], "Target.detachedFromTarget");
|
||||
assert_eq!(message["params"]["sessionId"], session);
|
||||
}
|
||||
assert_eq!(
|
||||
events.len(),
|
||||
3,
|
||||
"each detach and the response appear once: {events:?}"
|
||||
messages[2],
|
||||
json!({"id":91,"sessionId":"SID-browser-command","result":{}})
|
||||
);
|
||||
|
||||
context
|
||||
.route_direct_command_output_for_test(Vec::new(), work)
|
||||
.await;
|
||||
context
|
||||
.wait_for_direct_command_work_completion_for_test("cascade native cleanup")
|
||||
.await;
|
||||
assert!(
|
||||
events[..2]
|
||||
.iter()
|
||||
.all(|event| event["method"] == "Target.detachedFromTarget")
|
||||
);
|
||||
assert_eq!(
|
||||
events[2],
|
||||
json!({"id": 91, "sessionId": "SID-browser-command", "result": {}})
|
||||
context.take_all().is_empty(),
|
||||
"native cleanup cannot publish a second Browser response"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rebound_session_keeps_new_scripts_and_binding_after_old_cleanup_or_recovery() {
|
||||
for cancelled in [false, true] {
|
||||
let mut context = TestContext::new();
|
||||
let mut browser = BrowserContext::new("BID-rebound-disposal".into());
|
||||
browser.set_active_target_id("TID-rebound-disposal");
|
||||
browser.attach_active_session("SID-rebound-disposal");
|
||||
context.with_fixture(|conn| conn.install_browser_context_fixture_for_test(browser));
|
||||
context
|
||||
.install_navigation_fixture_for_session_owner(
|
||||
"about:blank",
|
||||
Some("SID-rebound-disposal"),
|
||||
)
|
||||
.await;
|
||||
context
|
||||
.process_async(json!({"id":1,"sessionId":"SID-rebound-disposal",
|
||||
async fn rebound_session_keeps_new_scripts_and_binding_after_old_cleanup() {
|
||||
let mut context = TestContext::new();
|
||||
let mut browser = BrowserContext::new("BID-rebound-disposal".into());
|
||||
browser.set_active_target_id("TID-rebound-disposal");
|
||||
browser.attach_active_session("SID-rebound-disposal");
|
||||
context.with_fixture(|conn| conn.install_browser_context_fixture_for_test(browser));
|
||||
context
|
||||
.install_navigation_fixture_for_session_owner(
|
||||
"about:blank",
|
||||
Some("SID-rebound-disposal"),
|
||||
)
|
||||
.await;
|
||||
context
|
||||
.process_async(json!({"id":1,"sessionId":"SID-rebound-disposal",
|
||||
"method":"Page.addScriptToEvaluateOnNewDocument",
|
||||
"params":{"source":"globalThis.originalBinding = true;"}}))
|
||||
.await;
|
||||
assert!(context.take_response_by_id(1).get("result").is_some());
|
||||
let state_owner = context.handle();
|
||||
let (prepared, recovery, route, page, successor) = state_owner
|
||||
.with_state(|state| {
|
||||
state.fixture(|connection| {
|
||||
let prepared = TargetDetachment::prepare(
|
||||
connection,
|
||||
None,
|
||||
DetachParams {
|
||||
session_id: Some("SID-rebound-disposal".into()),
|
||||
target_id: None,
|
||||
},
|
||||
.await;
|
||||
assert!(context.take_response_by_id(1).get("result").is_some());
|
||||
let state_owner = context.handle();
|
||||
let (prepared, route, page, successor) = state_owner
|
||||
.with_state(|state| {
|
||||
state.fixture(|connection| {
|
||||
let prepared = TargetDetachment::prepare(
|
||||
connection,
|
||||
None,
|
||||
DetachParams {
|
||||
session_id: Some("SID-rebound-disposal".into()),
|
||||
target_id: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let original = prepared.sessions[0].identity.clone();
|
||||
let route = connection
|
||||
.session_route(Some("SID-rebound-disposal"))
|
||||
.unwrap();
|
||||
let page = connection.renderer_page_residence_identity_for_owner(
|
||||
&CommandOwnerScope::for_session("SID-rebound-disposal"),
|
||||
);
|
||||
// Reuse the route and Page while replacing only the binding lifetime.
|
||||
connection
|
||||
.with_target_devtools_session_state_for_owner_mut(
|
||||
&CommandOwnerScope::for_session("SID-rebound-disposal"),
|
||||
|state| state.lifecycle = Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let original = prepared.sessions[0].identity.clone();
|
||||
let recovery = cancelled.then(|| prepared.failure_cleanup());
|
||||
let route = connection
|
||||
.session_route(Some("SID-rebound-disposal"))
|
||||
.unwrap();
|
||||
let page = connection.renderer_page_residence_identity_for_owner(
|
||||
&CommandOwnerScope::for_session("SID-rebound-disposal"),
|
||||
);
|
||||
// Reuse the route and Page while replacing only the binding lifetime.
|
||||
connection
|
||||
.with_target_devtools_session_state_for_owner_mut(
|
||||
&CommandOwnerScope::for_session("SID-rebound-disposal"),
|
||||
|state| state.lifecycle = Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
connection
|
||||
.register_session_route_for_test("SID-rebound-disposal", route.clone());
|
||||
let successor = connection
|
||||
.session_binding_lifetime("SID-rebound-disposal")
|
||||
.unwrap();
|
||||
assert!(!original.binding_is_current(connection));
|
||||
(prepared, recovery, route, page, successor)
|
||||
})
|
||||
connection
|
||||
.register_session_route_for_test("SID-rebound-disposal", route.clone());
|
||||
let successor = connection
|
||||
.session_binding_lifetime("SID-rebound-disposal")
|
||||
.unwrap();
|
||||
assert!(!original.binding_is_current(connection));
|
||||
(prepared, route, page, successor)
|
||||
})
|
||||
.unwrap();
|
||||
let add_successor_script = context.process_and_wait_for_response_async(json!({
|
||||
})
|
||||
.unwrap();
|
||||
let (events, work) = context.with_fixture(|connection| {
|
||||
let output = prepared.commit_in_browser(connection);
|
||||
(
|
||||
output.into_background_events(None, None),
|
||||
connection.take_scheduler_events(),
|
||||
)
|
||||
});
|
||||
context
|
||||
.route_direct_command_output_for_test(events, work)
|
||||
.await;
|
||||
context
|
||||
.process_and_wait_for_response_async(json!({
|
||||
"id":2,"sessionId":"SID-rebound-disposal",
|
||||
"method":"Page.addScriptToEvaluateOnNewDocument",
|
||||
"params":{"source":"globalThis.successorBinding = true;"}
|
||||
}));
|
||||
let settle_original = async {
|
||||
if let Some(recovery) = recovery {
|
||||
drop(prepared);
|
||||
let pending = state_owner
|
||||
.with_state(|state| {
|
||||
state.fixture(|connection| {
|
||||
recovery.prepare(
|
||||
connection,
|
||||
&mut CommandDispatchContext::default(),
|
||||
CommandOutputPlan::default(),
|
||||
)
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
let completed = pending.wait().await;
|
||||
state_owner
|
||||
.with_state(|state| {
|
||||
state.fixture(|connection| completed.finish(connection))
|
||||
})
|
||||
.unwrap();
|
||||
} else {
|
||||
let output = prepared
|
||||
.run(&mut ProtocolWorkflowDriver::new(state_owner.clone()))
|
||||
.await;
|
||||
state_owner
|
||||
.with_state(|state| {
|
||||
state.fixture(|connection| {
|
||||
output.finish(connection, &mut CommandDispatchContext::default())
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
};
|
||||
// A successor may enqueue Main work immediately, but its native
|
||||
// execution stays behind the original session's retirement.
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
tokio::join!(add_successor_script, settle_original);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let added = context.take_response_by_id(2);
|
||||
let identifier = added["result"]["identifier"].as_str().unwrap().to_owned();
|
||||
state_owner
|
||||
.with_state(|state| {
|
||||
state.fixture(|connection| {
|
||||
assert_eq!(
|
||||
connection.session_route(Some("SID-rebound-disposal")),
|
||||
Some(route)
|
||||
);
|
||||
assert_eq!(
|
||||
connection
|
||||
.session_binding_lifetime("SID-rebound-disposal"),
|
||||
Some(successor)
|
||||
);
|
||||
assert_eq!(
|
||||
connection.renderer_page_residence_identity_for_owner(
|
||||
&CommandOwnerScope::for_session("SID-rebound-disposal")
|
||||
),
|
||||
page
|
||||
);
|
||||
assert!(
|
||||
connection
|
||||
.target_owner_state_for_session(Some("SID-rebound-disposal"))
|
||||
.unwrap()
|
||||
.document_start_scripts
|
||||
.iter()
|
||||
.any(|(id, _)| id == &identifier),
|
||||
"old cleanup cannot remove the successor's script (cancelled: {cancelled})"
|
||||
);
|
||||
})
|
||||
}))
|
||||
.await;
|
||||
context
|
||||
.wait_for_direct_command_work_completion_for_test("old binding native cleanup")
|
||||
.await;
|
||||
let added = context.take_response_by_id(2);
|
||||
let identifier = added["result"]["identifier"].as_str().unwrap().to_owned();
|
||||
state_owner
|
||||
.with_state(|state| {
|
||||
state.fixture(|connection| {
|
||||
assert_eq!(
|
||||
connection.session_route(Some("SID-rebound-disposal")),
|
||||
Some(route)
|
||||
);
|
||||
assert_eq!(
|
||||
connection.session_binding_lifetime("SID-rebound-disposal"),
|
||||
Some(successor)
|
||||
);
|
||||
assert_eq!(
|
||||
connection.renderer_page_residence_identity_for_owner(
|
||||
&CommandOwnerScope::for_session("SID-rebound-disposal")
|
||||
),
|
||||
page
|
||||
);
|
||||
assert!(
|
||||
connection
|
||||
.target_owner_state_for_session(Some("SID-rebound-disposal"))
|
||||
.unwrap()
|
||||
.document_start_scripts
|
||||
.iter()
|
||||
.any(|(id, _)| id == &identifier),
|
||||
"old cleanup cannot remove the successor's script"
|
||||
);
|
||||
})
|
||||
.unwrap();
|
||||
context
|
||||
.process_and_wait_for_response_async(json!({
|
||||
"id":3,"sessionId":"SID-rebound-disposal",
|
||||
"method":"Runtime.evaluate","params":{"expression":"6 * 7","returnByValue":true}
|
||||
}))
|
||||
.await;
|
||||
let evaluated = context.take_response_by_id(3);
|
||||
assert_eq!(
|
||||
evaluated["result"]["result"]["value"], 42,
|
||||
"old cleanup cannot detach the successor Inspector: {evaluated:?}"
|
||||
);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
context
|
||||
.process_and_wait_for_response_async(json!({
|
||||
"id":3,"sessionId":"SID-rebound-disposal",
|
||||
"method":"Runtime.evaluate","params":{"expression":"6 * 7","returnByValue":true}
|
||||
}))
|
||||
.await;
|
||||
let evaluated = context.take_response_by_id(3);
|
||||
assert_eq!(
|
||||
evaluated["result"]["result"]["value"], 42,
|
||||
"old cleanup cannot detach the successor Inspector: {evaluated:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
use super::*;
|
||||
use crate::domains::target::session_disposal::{
|
||||
FailedSessionPageRetirement, SessionDisposalIdentity,
|
||||
};
|
||||
|
||||
/// Retained by the original command context, including while its supervised
|
||||
/// task is cancelled or unwinds. It owns only exact cleanup authority.
|
||||
pub(crate) struct TargetDetachmentFailureCleanup {
|
||||
sessions: Vec<SessionFailureCleanup>,
|
||||
}
|
||||
|
||||
struct SessionFailureCleanup {
|
||||
identity: SessionDisposalIdentity,
|
||||
commit: SessionDetachmentCommit,
|
||||
}
|
||||
|
||||
pub(crate) struct TargetDetachmentRecovery {
|
||||
sessions: Vec<(SessionFailureCleanup, FailedSessionPageRetirement)>,
|
||||
pages: Vec<moli_core::page::Page>,
|
||||
background_events: Vec<BackgroundProtocolEvent>,
|
||||
response: CommandOutputPlan,
|
||||
}
|
||||
|
||||
impl TargetDetachmentFailureCleanup {
|
||||
pub(super) fn new(sessions: &[SessionDetachment]) -> Self {
|
||||
Self {
|
||||
sessions: sessions
|
||||
.iter()
|
||||
.filter_map(|session| {
|
||||
if !session.disposal.owns_cleanup() {
|
||||
return None;
|
||||
}
|
||||
Some(SessionFailureCleanup {
|
||||
identity: session.identity.clone(),
|
||||
commit: session.commit.clone(),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(
|
||||
self,
|
||||
conn: &mut CdpConnection,
|
||||
context: &mut CommandDispatchContext,
|
||||
response: CommandOutputPlan,
|
||||
) -> TargetDetachmentRecovery {
|
||||
let mut sessions = Vec::new();
|
||||
let mut pages = Vec::new();
|
||||
let mut background_events = Vec::new();
|
||||
for session in self.sessions {
|
||||
if !session.identity.is_current(conn) {
|
||||
continue;
|
||||
}
|
||||
crate::domains::runtime::fail_pending_session_calls(
|
||||
conn,
|
||||
&mut background_events,
|
||||
context.protocol_events_mut(),
|
||||
session.identity.plan().session_id(),
|
||||
);
|
||||
let mut retired = session.identity.prepare_failed_page_retirement(conn);
|
||||
// Exact Page retirement owns Inspector destruction at close ACK.
|
||||
// Do not detach its primary Inspector through a live target route
|
||||
// while that target is already free to install a successor.
|
||||
let _ = session.identity.detach_inspector(conn);
|
||||
if let Some(page) = retired.take_page() {
|
||||
pages.push(page);
|
||||
}
|
||||
sessions.push((session, retired));
|
||||
}
|
||||
TargetDetachmentRecovery {
|
||||
sessions,
|
||||
pages,
|
||||
background_events,
|
||||
response,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TargetDetachmentRecovery {
|
||||
pub(crate) async fn wait(mut self) -> Self {
|
||||
for page in std::mem::take(&mut self.pages) {
|
||||
// Failure recovery belongs to the same command supervision entry.
|
||||
// Observe close before removing a binding, just as normal disposal.
|
||||
let _ = page.close_async().await;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn finish(self, conn: &mut CdpConnection) -> CommandOutputPlan {
|
||||
let mut output = CommandOutputPlan::default();
|
||||
for event in self.background_events {
|
||||
output.push_background_event(event);
|
||||
}
|
||||
for (session, retired) in self.sessions {
|
||||
if !session.identity.is_current(conn) {
|
||||
continue;
|
||||
}
|
||||
for event in session
|
||||
.identity
|
||||
.finish_failed_page_retirement(conn, retired)
|
||||
{
|
||||
output.push_background_event(event);
|
||||
}
|
||||
let (events, error) =
|
||||
commit_session_detachment(conn, &session.identity, session.commit);
|
||||
for event in events {
|
||||
output.push_background_event(event);
|
||||
}
|
||||
if let Some(error) = error {
|
||||
tracing::warn!(session_id = session.identity.plan().session_id(), %error,
|
||||
"failed to remove retired session domain state");
|
||||
}
|
||||
}
|
||||
output.extend(self.response);
|
||||
output
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use super::*;
|
||||
|
||||
mod workflow;
|
||||
pub(crate) use workflow::{
|
||||
AutoAttachSweepRollback, PreparedAutoAttachCommand, PreparedAutoAttachSweep,
|
||||
AutoAttachSweepRollback, PreparedAutoAttachEnable, PreparedAutoAttachSweep,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -373,7 +373,14 @@ pub(super) fn start_set_auto_attach_command(
|
||||
cmd.session_id,
|
||||
pause_dedicated_workers_on_start,
|
||||
);
|
||||
let command = PreparedAutoAttachCommand::prepare(conn, params.auto_attach, cmd.session_id);
|
||||
if !params.auto_attach {
|
||||
let detach = super::attachment::TargetDetachment::prepare_auto_attached_sessions(
|
||||
conn,
|
||||
cmd.session_id,
|
||||
);
|
||||
return TargetCommandTaskStep::Complete(detach.commit_in_browser(conn));
|
||||
}
|
||||
let command = PreparedAutoAttachEnable::prepare(conn, cmd.session_id);
|
||||
{
|
||||
let access = conn.protocol_state_access();
|
||||
TargetCommandTaskStep::Workflow(command.into_workflow(access))
|
||||
|
||||
@@ -24,7 +24,7 @@ impl AutoAttachSweepRollback {
|
||||
.retain(|session| session.session_id() != session_id);
|
||||
}
|
||||
|
||||
pub(in crate::domains::target) async fn run(self, driver: &mut ProtocolWorkflowDriver) {
|
||||
async fn run(self, driver: &mut ProtocolWorkflowDriver) {
|
||||
let sessions = std::mem::take(&mut *self.0.borrow_mut());
|
||||
for session in sessions {
|
||||
if let Err(error) = super::super::opening::rollback_attachment(driver, session).await {
|
||||
@@ -45,10 +45,9 @@ impl AutoAttachSweepRollback {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct PreparedAutoAttachCommand {
|
||||
pub(crate) struct PreparedAutoAttachEnable {
|
||||
owner_session_id: Option<String>,
|
||||
policy: Option<AutoAttachPolicyIdentity>,
|
||||
detach: Option<super::super::attachment::TargetDetachment>,
|
||||
policy: AutoAttachPolicyIdentity,
|
||||
rollback: AutoAttachSweepRollback,
|
||||
}
|
||||
|
||||
@@ -65,23 +64,14 @@ pub(crate) struct PreparedAutoAttachSweep {
|
||||
rollback: AutoAttachSweepRollback,
|
||||
}
|
||||
|
||||
impl PreparedAutoAttachCommand {
|
||||
impl PreparedAutoAttachEnable {
|
||||
pub(in crate::domains::target) fn prepare(
|
||||
conn: &mut CdpConnection,
|
||||
enabled: bool,
|
||||
owner_session_id: Option<&str>,
|
||||
) -> Self {
|
||||
Self {
|
||||
policy: enabled.then(|| {
|
||||
AutoAttachPolicyIdentity::capture(conn, owner_session_id)
|
||||
.expect("an enabled auto-attach command retains its installed policy")
|
||||
}),
|
||||
detach: (!enabled).then(|| {
|
||||
super::super::attachment::TargetDetachment::prepare_auto_attached_sessions(
|
||||
conn,
|
||||
owner_session_id,
|
||||
)
|
||||
}),
|
||||
policy: AutoAttachPolicyIdentity::capture(conn, owner_session_id)
|
||||
.expect("an enabling command retains its installed policy"),
|
||||
owner_session_id: owner_session_id.map(str::to_owned),
|
||||
rollback: AutoAttachSweepRollback::default(),
|
||||
}
|
||||
@@ -91,57 +81,23 @@ impl PreparedAutoAttachCommand {
|
||||
self,
|
||||
access: ProtocolStateHandle,
|
||||
) -> PreparedCommandWorkflow {
|
||||
let detached_cleanup = self.detach.as_ref().map(|detach| detach.failure_cleanup());
|
||||
let rollback = self.rollback.clone();
|
||||
let recovery_access = access.clone();
|
||||
PreparedCommandWorkflow::new(move |mut context| async move {
|
||||
match Box::pin(self.run(&mut ProtocolWorkflowDriver::new(access), &mut context)).await {
|
||||
match self.run(&mut ProtocolWorkflowDriver::new(access), &mut context) {
|
||||
Ok(()) => context.complete(CommandOutputPlan::default()),
|
||||
Err(error) => context.fail(CommandOutputPlan::error(-32000, error)),
|
||||
}
|
||||
})
|
||||
.with_failure_cleanup(move |response| {
|
||||
let Some(cleanup) = detached_cleanup else {
|
||||
return rollback.into_recovery(recovery_access, response);
|
||||
};
|
||||
PreparedCommandWorkflow::new(move |mut context| async move {
|
||||
let mut driver = ProtocolWorkflowDriver::new(recovery_access);
|
||||
let recovery = context.with_state(&mut driver, move |state, context| {
|
||||
state.prepare_auto_attach_detachment_recovery(
|
||||
cleanup,
|
||||
response,
|
||||
context.context_mut(),
|
||||
)
|
||||
});
|
||||
match recovery {
|
||||
Ok(recovery) => {
|
||||
let recovery = recovery.wait().await;
|
||||
context.complete_in_owner_turn(
|
||||
CommandOutputPlan::default(),
|
||||
move |state, _| state.finish_auto_attach_detachment_recovery(recovery),
|
||||
)
|
||||
}
|
||||
Err(error) => context.fail(CommandOutputPlan::error(-32000, error)),
|
||||
}
|
||||
})
|
||||
})
|
||||
.with_failure_cleanup(move |response| rollback.into_recovery(recovery_access, response))
|
||||
}
|
||||
|
||||
pub(in crate::domains::target) async fn run(
|
||||
fn run(
|
||||
self,
|
||||
driver: &mut ProtocolWorkflowDriver,
|
||||
context: &mut CommandWorkflowContext,
|
||||
) -> Result<()> {
|
||||
// Browser policy/registration never waits for an initial Page.
|
||||
if let Some(detach) = self.detach {
|
||||
context.defer_owner_turn_completion(move |state, _| {
|
||||
state.commit_auto_attach_detachment(detach)
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
let policy = self
|
||||
.policy
|
||||
.expect("an enabling command retains its policy identity");
|
||||
let policy = self.policy;
|
||||
let rollback = self.rollback;
|
||||
let prepared_rollback = rollback.clone();
|
||||
let mut sweep = driver.with_state(move |state| {
|
||||
|
||||
@@ -4,7 +4,6 @@ use serde_json::Value;
|
||||
use crate::automation::{AutomationEvent, DevToolsTargetId, DevToolsTargetInfo};
|
||||
#[cfg(test)]
|
||||
use crate::automation::{DevToolsSessionId, TargetAttachmentEvent, TargetDetachmentEvent};
|
||||
use crate::domains::command_output::CommandOutputPlan;
|
||||
|
||||
pub(super) trait CdpTargetAutomationEventSink {
|
||||
fn push_target_background_event(&mut self, event: crate::conn::BackgroundProtocolEvent);
|
||||
@@ -22,12 +21,6 @@ pub(super) struct TargetProtocolSideEffects {
|
||||
}
|
||||
|
||||
impl TargetProtocolSideEffects {
|
||||
pub(super) fn background_events_mut(
|
||||
&mut self,
|
||||
) -> &mut Vec<crate::conn::BackgroundProtocolEvent> {
|
||||
&mut self.events
|
||||
}
|
||||
|
||||
pub(super) fn into_background_events(self) -> Vec<crate::conn::BackgroundProtocolEvent> {
|
||||
self.events
|
||||
}
|
||||
@@ -38,14 +31,6 @@ impl TargetProtocolSideEffects {
|
||||
) {
|
||||
self.events.extend(events);
|
||||
}
|
||||
|
||||
pub(super) fn drain_into_plan(&mut self) -> CommandOutputPlan {
|
||||
let mut plan = CommandOutputPlan::default();
|
||||
for event in std::mem::take(&mut self.events) {
|
||||
plan.push_background_event(event);
|
||||
}
|
||||
plan
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn inspector_detached_event(
|
||||
@@ -569,19 +554,18 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_protocol_side_effects_keep_event_order_before_background_event_mutation() {
|
||||
fn target_protocol_side_effects_keep_event_order_when_extending_events() {
|
||||
let mut out = super::TargetProtocolSideEffects::default();
|
||||
super::emit_target_destroyed(&mut out, "TID-before-background");
|
||||
|
||||
out.background_events_mut()
|
||||
.push(crate::conn::BackgroundProtocolEvent::target_detached(
|
||||
TargetDetachmentEvent {
|
||||
target_id: DevToolsTargetId::from("TID-after-background"),
|
||||
session_id: DevToolsSessionId::from("SID-after-background"),
|
||||
parent_session_id: None,
|
||||
reason: None,
|
||||
},
|
||||
));
|
||||
out.extend_background_events([crate::conn::BackgroundProtocolEvent::target_detached(
|
||||
TargetDetachmentEvent {
|
||||
target_id: DevToolsTargetId::from("TID-after-background"),
|
||||
session_id: DevToolsSessionId::from("SID-after-background"),
|
||||
parent_session_id: None,
|
||||
reason: None,
|
||||
},
|
||||
)]);
|
||||
|
||||
let mut events = out.into_background_events();
|
||||
assert_eq!(events.len(), 2);
|
||||
|
||||
@@ -80,10 +80,6 @@ impl PreparedSessionDisposal {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn owns_cleanup(&self) -> bool {
|
||||
matches!(self, Self::Own(_))
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
self,
|
||||
driver: &mut ProtocolWorkflowDriver,
|
||||
|
||||
@@ -173,7 +173,6 @@ pub struct RendererRuntimeInspectorMainCommandRoute {
|
||||
session_response_settlement_rx:
|
||||
Option<tokio::sync::oneshot::Receiver<RendererRuntimeInspectorSessionResponseSettlement>>,
|
||||
ingress: RendererInspectorMainIngress,
|
||||
cancel_on_drop: bool,
|
||||
}
|
||||
|
||||
impl RendererRuntimeInspectorMainCommandRoute {
|
||||
@@ -321,12 +320,10 @@ impl RendererRuntimeInspectorMainCommandRoute {
|
||||
|
||||
impl Drop for RendererRuntimeInspectorMainCommandRoute {
|
||||
fn drop(&mut self) {
|
||||
if self.cancel_on_drop {
|
||||
self.ingress.cancel_queued_command(
|
||||
self.command_id,
|
||||
"Runtime inspector Main route was canceled before dispatch",
|
||||
);
|
||||
}
|
||||
self.ingress.cancel_queued_command(
|
||||
self.command_id,
|
||||
"Runtime inspector Main route was canceled before dispatch",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -500,7 +497,6 @@ impl RendererInspectorMainIngress {
|
||||
RendererPageCommand::DevTools(RendererDevToolsPageCommand::Inspector(envelope)),
|
||||
),
|
||||
RendererPageStateCapturePolicy::ProtocolTurn,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -518,7 +514,6 @@ impl RendererInspectorMainIngress {
|
||||
RendererPageCommand::DevTools(RendererDevToolsPageCommand::Inspector(envelope)),
|
||||
),
|
||||
capture_policy,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -538,7 +533,6 @@ impl RendererInspectorMainIngress {
|
||||
inspector_session_id,
|
||||
),
|
||||
capture_policy,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -549,9 +543,8 @@ impl RendererInspectorMainIngress {
|
||||
command: RendererPageCommand,
|
||||
inspector_session_id: Option<String>,
|
||||
) {
|
||||
// Only the target's initialization path admits an unobserved command.
|
||||
// The existing owner scheduler retains unobserved work through parking.
|
||||
drop(self.enqueue_with_policy(
|
||||
// Target-owned work has no claim/reply observer, including while parked.
|
||||
self.admit_command(
|
||||
page_token,
|
||||
agent_token,
|
||||
RendererDevToolsMainCommandEnvelope::from_protocol_command_in_session(
|
||||
@@ -559,8 +552,9 @@ impl RendererInspectorMainIngress {
|
||||
inspector_session_id,
|
||||
),
|
||||
RendererPageStateCapturePolicy::BackgroundInitialization,
|
||||
true,
|
||||
));
|
||||
None,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
fn enqueue_with_policy(
|
||||
@@ -569,33 +563,57 @@ impl RendererInspectorMainIngress {
|
||||
agent_token: RendererDevToolsAgentToken,
|
||||
envelope: RendererDevToolsMainCommandEnvelope,
|
||||
capture_policy: RendererPageStateCapturePolicy,
|
||||
detached: bool,
|
||||
) -> RendererRuntimeInspectorMainCommandRoute {
|
||||
assert_eq!(
|
||||
envelope.ticket().route(),
|
||||
RendererInspectorCommandRoute::MainThread,
|
||||
"only MainThread DevTools commands may enter RendererInspectorMainIngress"
|
||||
);
|
||||
let (claim_tx, claim_rx) = tokio::sync::oneshot::channel();
|
||||
let (owner_reply_tx, owner_reply_rx) = tokio::sync::oneshot::channel();
|
||||
let session_response_settlement_rx = envelope.response().and_then(
|
||||
RendererRuntimeInspectorResponseSender::take_session_response_settlement_receiver,
|
||||
);
|
||||
let ticket = envelope.ticket().clone();
|
||||
let command_id = ticket.sequence();
|
||||
self.admit_command(
|
||||
page_token,
|
||||
agent_token,
|
||||
envelope,
|
||||
capture_policy,
|
||||
Some(claim_tx),
|
||||
Some(owner_reply_tx),
|
||||
);
|
||||
RendererRuntimeInspectorMainCommandRoute {
|
||||
command_id,
|
||||
ticket,
|
||||
claim_rx: Some(claim_rx),
|
||||
owner_reply_rx: Some(owner_reply_rx),
|
||||
session_response_settlement_rx,
|
||||
ingress: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn admit_command(
|
||||
&self,
|
||||
page_token: RendererPageToken,
|
||||
agent_token: RendererDevToolsAgentToken,
|
||||
envelope: RendererDevToolsMainCommandEnvelope,
|
||||
capture_policy: RendererPageStateCapturePolicy,
|
||||
claim_tx: Option<tokio::sync::oneshot::Sender<RendererInspectorMainCommandClaim>>,
|
||||
owner_reply_tx: Option<tokio::sync::oneshot::Sender<anyhow::Result<RendererOwnerReply>>>,
|
||||
) {
|
||||
assert_eq!(
|
||||
envelope.ticket().route(),
|
||||
RendererInspectorCommandRoute::MainThread,
|
||||
"only MainThread DevTools commands may enter RendererInspectorMainIngress"
|
||||
);
|
||||
let mut state = self.shared.state.lock();
|
||||
let lane_key =
|
||||
RendererDevToolsSessionLaneKey::new(agent_token, envelope.ticket().session().clone());
|
||||
let ticket = envelope.ticket().clone();
|
||||
let command_id = ticket.sequence();
|
||||
let command = RendererInspectorMainCommand {
|
||||
command_id,
|
||||
command_id: envelope.ticket().sequence(),
|
||||
page_token,
|
||||
agent_token,
|
||||
capture_policy,
|
||||
envelope,
|
||||
claim_tx: Some(claim_tx),
|
||||
// A target-owned initialization has no Browser observer. The
|
||||
// existing owner scheduler's absent reply slot survives parking.
|
||||
owner_reply_tx: (!detached).then_some(owner_reply_tx),
|
||||
claim_tx,
|
||||
owner_reply_tx,
|
||||
claimed_by: None,
|
||||
cleanup_authority: false,
|
||||
connection: state.connections.admission(&lane_key),
|
||||
@@ -605,22 +623,12 @@ impl RendererInspectorMainIngress {
|
||||
} else {
|
||||
Err(command)
|
||||
};
|
||||
drop(state);
|
||||
if let Err(command) = admitted {
|
||||
drop(state);
|
||||
fail_main_command(command, "Inspector Main session or target is closed");
|
||||
} else {
|
||||
drop(state);
|
||||
self.notify_execution_opportunities();
|
||||
}
|
||||
RendererRuntimeInspectorMainCommandRoute {
|
||||
command_id,
|
||||
ticket,
|
||||
claim_rx: Some(claim_rx),
|
||||
owner_reply_rx: (!detached).then_some(owner_reply_rx),
|
||||
session_response_settlement_rx,
|
||||
ingress: self.clone(),
|
||||
cancel_on_drop: !detached,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn claim_for_owner(&self) -> Option<RendererInspectorMainCommand> {
|
||||
|
||||
Reference in New Issue
Block a user