1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! Per-`BrowserContext` lifecycle on top of CDP `Target.createBrowserContext`.
use std::sync::Arc;
use std::time::Duration;
use serde_json::json;
use crate::browser::BrowserInner;
use crate::error::ZendriverError;
use crate::tab::Tab;
pub struct BrowserContext {
pub(crate) browser: Arc<BrowserInner>,
pub(crate) id: String,
}
impl BrowserContext {
pub fn id(&self) -> &str {
&self.id
}
/// Open a new tab navigated to `about:blank` **inside this context**.
///
/// Convenience wrapper over [`BrowserContext::new_tab_at`] with
/// `"about:blank"`.
///
/// # Errors
///
/// Same as [`BrowserContext::new_tab_at`].
pub async fn new_tab(&self) -> Result<Tab, ZendriverError> {
self.new_tab_at("about:blank").await
}
/// Open a new tab navigated to `url` **inside this context**.
///
/// Mirrors [`crate::Browser::new_tab_at`] but threads
/// `browserContextId` into the `Target.createTarget` params so the new
/// target lands in this context rather than the default one. Without
/// that field the per-context isolation (proxy, storage) the
/// `BrowserContext` was created for would not apply to the tab.
///
/// # Errors
///
/// Returns [`ZendriverError::Navigation`] if the CDP response is
/// missing `targetId`, and [`ZendriverError::TabNotFound`] if the
/// internal tab registrar fails to register the new tab within 5s.
pub async fn new_tab_at(&self, url: impl Into<String>) -> Result<Tab, ZendriverError> {
let url = url.into();
let res = self
.browser
.conn
.call_raw(
"Target.createTarget",
json!({ "url": url, "browserContextId": self.id }),
None,
)
.await?;
let target_id = res
.get("targetId")
.and_then(|v| v.as_str())
.ok_or_else(|| {
ZendriverError::Navigation("Target.createTarget returned no targetId".into())
})?
.to_string();
// Mirror the wait pattern used by `Browser::new_tab_at`: enable a
// `Notify` subscription before reading the tabs map so a notify
// that lands between the read and the wait is still delivered.
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
let notif = self.browser.tabs_changed.notified();
tokio::pin!(notif);
notif.as_mut().enable();
{
let tabs = self.browser.tabs.read().await;
if let Some(tab) = tabs.values().find(|t| t.target_id() == target_id) {
return Ok(tab.clone());
}
}
if tokio::time::Instant::now() >= deadline {
return Err(ZendriverError::TabNotFound(target_id));
}
tokio::select! {
() = notif => {}
() = tokio::time::sleep_until(deadline) => {}
}
}
}
}
impl Drop for BrowserContext {
fn drop(&mut self) {
let browser = self.browser.clone();
let id = std::mem::take(&mut self.id);
if id.is_empty() {
return; // already disposed (explicit dispose() will exist in a later task)
}
tokio::spawn(async move {
if let Err(e) = browser.dispose_browser_context(&id).await {
tracing::warn!(context_id = %id, error = %e, "BrowserContext dispose failed");
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn browser_context_exposes_id() {
fn _accept(_: &BrowserContext) {}
}
}
#[cfg(test)]
mod drop_tests {
use super::*;
use zendriver_transport::testing::MockConnection;
/// Asserts that dropping a [`BrowserContext`] spawns a background task
/// which issues `Target.disposeBrowserContext` carrying the context's
/// id. Models the lifecycle parity guarantee: a `BrowserContext` handle
/// owns its CDP context for the duration of its scope.
#[tokio::test]
async fn drop_schedules_dispose_call() {
let (mut mock, conn) = MockConnection::pair();
let inner = crate::browser::test_only_inner_from_conn(conn.clone());
{
let _ctx = BrowserContext {
browser: inner.clone(),
id: "ctx-drop-test".into(),
};
}
// Drop has spawned a task — wait for it to land on the mock.
let id = tokio::time::timeout(
std::time::Duration::from_secs(2),
mock.expect_cmd("Target.disposeBrowserContext"),
)
.await
.expect("dispose did not fire within 2s");
let sent = mock.last_sent();
assert_eq!(sent["params"]["browserContextId"], "ctx-drop-test");
mock.reply(id, serde_json::json!({})).await;
conn.shutdown();
}
}
#[cfg(test)]
mod new_tab_tests {
use super::*;
use zendriver_transport::testing::MockConnection;
/// Asserts `BrowserContext::new_tab_at` issues a
/// `Target.createTarget` whose params include the context's id as
/// `browserContextId`. Without that field the new tab lands in the
/// default context — defeating the isolation guarantee.
///
/// The test only verifies the outbound CDP shape; the registrar wait
/// inside `new_tab_at` blocks on a `Target.attachedToTarget` event the
/// mock doesn't dispatch, so the future is bounded by a short timeout.
#[tokio::test]
async fn new_tab_at_passes_browser_context_id() {
let (mut mock, conn) = MockConnection::pair();
let inner = crate::browser::test_only_inner_from_conn(conn.clone());
let ctx = BrowserContext {
browser: inner,
id: "ctx-tab-test".into(),
};
let fut = tokio::spawn(async move { ctx.new_tab_at("about:blank").await });
let id = mock.expect_cmd("Target.createTarget").await;
let sent = mock.last_sent();
assert_eq!(sent["params"]["url"], "about:blank");
assert_eq!(sent["params"]["browserContextId"], "ctx-tab-test");
mock.reply(id, serde_json::json!({ "targetId": "target-1" }))
.await;
// Registrar wait blocks on a `Target.attachedToTarget` event the
// mock won't fire; bound the test with a short timeout.
let _ = tokio::time::timeout(std::time::Duration::from_millis(200), fut).await;
conn.shutdown();
}
}