Skip to content

Commit 49db81e

Browse files
committed
Merge branch 'fix/markdown-raw-text-base-graphic' into fix/one-raw-text-definition
Bring in main through #211 as the parent branch now carries it: the browser fetch fixes and the header gate change. The merge is clean.
2 parents 0915ae4 + c821f58 commit 49db81e

12 files changed

Lines changed: 1076 additions & 444 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,65 @@ All notable changes to crawlberg are documented here.
2929

3030
### Fixed
3131

32+
- **The vendored C header gate failed for lag rather than for a defect.** It required each
33+
prebuilt platform bundle's `crawlberg.h` to declare exactly the same C API as the canonical
34+
header, but a vendored copy ships beside a dylib from the last release, so it legitimately
35+
lacks whatever the canonical header has gained since — adding two `CrawlPageResult` getters
36+
for #135 turned `main` red for that reason alone. The comparison is now one-directional: a
37+
declaration the vendored copy has and the canonical header does not still fails, because that
38+
means a prebuilt bundle promising a symbol HEAD removed or re-signed, while declarations the
39+
copy is merely missing are reported as lag. (#162)
40+
41+
- **A browser fetch reported no response headers at all on the crawl path.**
42+
`browser_http_to_crawl` built an empty header map, so every header a browser backend had
43+
collected was discarded before the crawl or the escalation path could read it — `ETag`,
44+
`Cache-Control` and `X-Robots-Tag` reached no caller and no WAF classifier, however faithfully the
45+
backend reported them. This is why a `nofollow` sent only as an `X-Robots-Tag` header had no effect
46+
in browser mode even after the crawl learned to honour it. Headers are now carried through. The
47+
chromiumoxide backend still hardcodes its own status, content type and headers, so this reaches
48+
callers today on the native backend only; #166 covers the rest. (#148)
49+
50+
- **Dropping a one-shot browser fetch ran no teardown at all.** Teardown was straight-line code
51+
after the fetch, reached only once the fetch had finished, so a caller that dropped the future
52+
while it ran — a cancelled request, a `select!` that lost, a deadline above crawlberg — got none
53+
of it. Against a `browser.endpoint` Chrome that left crawlberg's CDP websocket open, and the tab
54+
it had opened open with it: a connected `chromiumoxide::Browser` owns no child process, so
55+
dropping it does nothing, and its handler loop never ends by itself. Against a launched Chrome
56+
the process went with the dropped handle, but its `--user-data-dir` stayed on disk. Teardown now
57+
belongs to a value whose `Drop` runs it, so a dropped fetch and a finished one take the same
58+
path, and the profile directory is owned by a guard from the moment it is created rather than
59+
from the moment the launch succeeds — a fetch cancelled mid-launch never had a session to tear
60+
down. One window remains open: the Chrome process that `Browser::launch` is still building
61+
cannot be reaped from outside it, so a fetch cancelled during the launch can leave that process
62+
behind, and it recreates the directory it was just removed from (#198). (#131)
63+
64+
- **Teardown waited five seconds for the CDP handler after killing a hung Chrome.** Killing the
65+
process does not end the task that runs its CDP handler: chromiumoxide's handler loop returns
66+
only when a `Browser.close` response reaches it, and a closed websocket merely parks the loop, so
67+
the wait could never do anything but expire in full and abort the task anyway — about five
68+
seconds added to every teardown that had to kill a Chrome that had stopped responding. The close
69+
now reports whether the process exited or had to be killed, and the handler is aborted at once in
70+
the killed case. A browser that closed cleanly is unchanged, still given the same grace period to
71+
wind its handler down. (#146)
72+
73+
- **A pooled browser fetch that hit its overall deadline leaked its page.** `overall_timeout`
74+
wrapped the whole pooled fetch, so expiry dropped that future before it could release the page it
75+
had borrowed from the shared browser — and `chromiumoxide::Page` has no closing `Drop`, so the CDP
76+
target stayed open for the rest of the process's life, still running scripts. The deadline now
77+
bounds page acquisition and navigation individually and the release runs on every path, the
78+
deadline one included. That release is bounded by `shutdown_timeout` rather than by the overall
79+
deadline, so a browser too wedged to close a page cannot hold a fetch open, and an
80+
already-computed result is no longer replaced by a timeout error because teardown was slow.
81+
Closing a timed-out page's popups is not covered here. (#179)
82+
83+
- **A refused URL's credentials reached the error text.** The browser navigation path and interact
84+
mode built the SSRF violation error with a struct literal instead of the redacting constructor, so
85+
a request Chrome was refused at a redirect — `https://user:secret@10.0.0.1/` — carried its
86+
`user:pass@` userinfo into the error message, and from there into API error bodies, MCP error
87+
payloads and tracing fields. Both sites now build the error through `CrawlError::ssrf_violation`,
88+
which redacts the userinfo before it is stored. The pre-navigation seed check and the HTTP
89+
redirect path already used the redacting path and are unchanged. (#180)
90+
3291
- **Four CI gates passed without examining anything.** The vendored-C-header check compared only
3392
`packages/go/include/crawlberg.h`, the one copy the header generator writes alongside the
3493
canonical file, leaving the three prebuilt-native copies unchecked; it now discovers every

‎crates/crawlberg/src/browser.rs‎

Lines changed: 154 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
66
use std::time::Duration;
77

8+
use chromiumoxide::browser::Browser;
9+
use chromiumoxide::cdp::browser_protocol::target::TargetId;
10+
use tokio::sync::OwnedSemaphorePermit;
11+
use tokio::task::JoinHandle;
812
use tokio_stream::StreamExt;
913
use tracing::Instrument as _;
1014

@@ -124,10 +128,10 @@ fn overall_deadline_error(overall_timeout: Duration) -> CrawlError {
124128
/// Fetch using a page borrowed from a shared [`BrowserPool`], returning the page
125129
/// to the session pool on success when session affinity is enabled.
126130
///
127-
/// The whole operation -- page acquisition, navigation, rendering, and the
128-
/// page close that follows -- is bounded by `BrowserConfig::overall_timeout`,
129-
/// closing the gap where an unbounded semaphore wait or an unbounded
130-
/// `page.close()` could hold a fetch open indefinitely.
131+
/// Page acquisition, navigation and rendering are bounded as a single
132+
/// `BrowserConfig::overall_timeout` deadline, closing the gap where an unbounded semaphore
133+
/// wait could hold a fetch open indefinitely. The page release that follows runs on every
134+
/// path including the deadline path, and is bounded by `BrowserConfig::shutdown_timeout`.
131135
async fn pooled_fetch(
132136
url: &str,
133137
config: &CrawlConfig,
@@ -136,24 +140,8 @@ async fn pooled_fetch(
136140
want_screenshot: bool,
137141
) -> Result<HttpResponse, CrawlError> {
138142
let overall_timeout = config.browser.overall_timeout;
139-
match tokio::time::timeout(
140-
overall_timeout,
141-
pooled_fetch_inner(url, config, prior_cookies, pool, want_screenshot),
142-
)
143-
.await
144-
{
145-
Ok(result) => result,
146-
Err(_) => Err(overall_deadline_error(overall_timeout)),
147-
}
148-
}
143+
let deadline = tokio::time::Instant::now() + overall_timeout;
149144

150-
async fn pooled_fetch_inner(
151-
url: &str,
152-
config: &CrawlConfig,
153-
prior_cookies: Option<&[CookieInfo]>,
154-
pool: &BrowserPool,
155-
want_screenshot: bool,
156-
) -> Result<HttpResponse, CrawlError> {
157145
if config.browser_profile.is_some() {
158146
// ~keep Pool browsers launch once, ahead of any per-crawl CrawlConfig; a
159147
// ~keep profile named later cannot retroactively change that process's
@@ -165,11 +153,41 @@ async fn pooled_fetch_inner(
165153
);
166154
}
167155

168-
// ~keep `page` + `permit` are held across `page_fetch` below: the previous code let the
169-
// ~keep acquisition guard drop as the tail expression of this block, which released the
170-
// ~keep semaphore permit AND spawned a `Target.closeTarget` race against the navigation
171-
// ~keep that was about to start on the very same CDP target.
172-
let (page, permit) = if config.browser.session_affinity {
156+
let (page, permit) = match tokio::time::timeout_at(deadline, acquire_pooled_page(url, config, pool)).await {
157+
Ok(acquired) => acquired?,
158+
Err(_) => return Err(overall_deadline_error(overall_timeout)),
159+
};
160+
161+
// ~keep The deadline is applied to each stage here rather than by wrapping this whole
162+
// ~keep function in `tokio::time::timeout` at the call site. Wrapping dropped this future
163+
// ~keep the instant the deadline expired, which skipped the `release_pooled_page` below;
164+
// ~keep `chromiumoxide::Page` has no closing `Drop`, so every pooled fetch that hit its
165+
// ~keep overall deadline left its CDP target open in the shared browser for the rest of the
166+
// ~keep process's life. xberg-io/crawlberg#179.
167+
let result =
168+
match tokio::time::timeout_at(deadline, page_fetch(url, config, &page, prior_cookies, want_screenshot)).await {
169+
Ok(result) => result,
170+
Err(_) => Err(overall_deadline_error(overall_timeout)),
171+
};
172+
173+
release_pooled_page(url, config, page, permit, result.is_ok()).await;
174+
175+
result
176+
}
177+
178+
/// Take a page and its semaphore permit for this fetch, reusing a parked session-affinity
179+
/// page when one exists for this URL.
180+
///
181+
/// ~keep The page and its permit are returned as a pair for the caller to hold across
182+
/// ~keep `page_fetch`: letting a `PooledPage` guard drop as the tail expression of the
183+
/// ~keep acquisition released the semaphore permit AND spawned a `Target.closeTarget` race
184+
/// ~keep against the navigation that was about to start on the very same CDP target.
185+
async fn acquire_pooled_page(
186+
url: &str,
187+
config: &CrawlConfig,
188+
pool: &BrowserPool,
189+
) -> Result<(chromiumoxide::Page, Option<OwnedSemaphorePermit>), CrawlError> {
190+
if config.browser.session_affinity {
173191
let session_key = crate::browser_session_pool::SessionKey::from_url(
174192
url,
175193
config.browser.proxy.as_ref().map(|p| p.url.as_str()),
@@ -180,33 +198,49 @@ async fn pooled_fetch_inner(
180198
.ok_or_else(|| CrawlError::browser_error("session_affinity enabled but session pool is not configured"))?;
181199

182200
if let Some(reused) = session_pool.acquire(&session_key).await {
183-
reused
184-
} else {
185-
let pooled = pool.acquire_page().await?;
186-
pooled.into_parts()
201+
return Ok(reused);
187202
}
188-
} else {
189-
let pooled = pool.acquire_page().await?;
190-
pooled.into_parts()
191-
};
203+
}
192204

193-
let result = page_fetch(url, config, &page, prior_cookies, want_screenshot).await;
205+
Ok(pool.acquire_page().await?.into_parts())
206+
}
194207

208+
/// Park `page` for reuse when session affinity wants it and the fetch succeeded, otherwise
209+
/// close its CDP target and release the permit.
210+
///
211+
/// ~keep This runs on the overall-deadline path too, which is the whole reason `pooled_fetch`
212+
/// ~keep bounds its stages individually, so `page.close()` here must itself be bounded: an
213+
/// ~keep unbounded close against a browser already wedged enough to blow the overall deadline
214+
/// ~keep would reintroduce exactly the hang that deadline exists to cut short.
215+
async fn release_pooled_page(
216+
url: &str,
217+
config: &CrawlConfig,
218+
page: chromiumoxide::Page,
219+
permit: Option<OwnedSemaphorePermit>,
220+
reusable: bool,
221+
) {
195222
if config.browser.session_affinity
196-
&& result.is_ok()
223+
&& reusable
197224
&& let Ok(session_key) = crate::browser_session_pool::SessionKey::from_url(
198225
url,
199226
config.browser.proxy.as_ref().map(|p| p.url.as_str()),
200227
)
201228
&& let Some(session_pool) = config.browser_session_pool.as_deref()
202229
{
230+
tracing::debug!("parking a pooled browser page for session reuse");
203231
session_pool.insert(session_key, page, permit).await;
204-
} else {
205-
let _ = page.close().await;
206-
drop(permit);
232+
return;
207233
}
208234

209-
result
235+
let shutdown_timeout = config.browser.shutdown_timeout;
236+
tracing::debug!(reusable, "releasing a pooled browser page");
237+
if tokio::time::timeout(shutdown_timeout, page.close()).await.is_err() {
238+
tracing::warn!(
239+
timeout_secs = shutdown_timeout.as_secs_f64(),
240+
"a pooled page did not close before the shutdown timeout; its CDP target is left to Chrome"
241+
);
242+
}
243+
drop(permit);
210244
}
211245

212246
/// Launch (or connect to) a browser for this single fetch and tear it down again.
@@ -217,14 +251,16 @@ async fn pooled_fetch_inner(
217251
/// background, bounded by its own `BrowserConfig::shutdown_timeout`: a
218252
/// completed page result is returned to the caller without waiting for a
219253
/// Chrome process that refuses to exit.
254+
///
255+
/// Teardown is owned by [`OneShotSession`]'s `Drop`, so a caller that drops this future while
256+
/// the fetch runs gets the same teardown as a fetch that ran to completion.
220257
async fn one_shot_fetch(
221258
url: &str,
222259
config: &CrawlConfig,
223260
prior_cookies: Option<&[CookieInfo]>,
224261
want_screenshot: bool,
225262
) -> Result<HttpResponse, CrawlError> {
226263
let overall_timeout = config.browser.overall_timeout;
227-
let shutdown_timeout = config.browser.shutdown_timeout;
228264
let deadline = tokio::time::Instant::now() + overall_timeout;
229265

230266
let (browser, mut handler, data_dir) = match tokio::time::timeout_at(deadline, launch_or_connect(config)).await {
@@ -234,42 +270,95 @@ async fn one_shot_fetch(
234270
};
235271

236272
let handler_handle = tokio::spawn(async move { while handler.next().await.is_some() {} });
273+
let mut session = OneShotSession {
274+
browser: Some(browser),
275+
open_tab: None,
276+
handler_handle: Some(handler_handle),
277+
data_dir,
278+
shutdown_timeout: config.browser.shutdown_timeout,
279+
};
237280

238281
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
239-
// ~keep The tab's target id lives outside the deadline future so a fetch cut off by the
240-
// ~keep deadline still hands the tab to `release_browser`: an external Chrome
241-
// ~keep (`browser.endpoint`) is left running, so a tab left open there would outlive this fetch.
242-
let mut open_target = None;
243282
let fetch_outcome = tokio::time::timeout(remaining, async {
244-
let page = browser
245-
.new_page("about:blank")
246-
.await
247-
.map_err(|e| CrawlError::browser_error(format!("failed to create page: {e}")))?;
248-
open_target = Some(page.target_id().clone());
249-
283+
let page = session.open_page().await?;
250284
page_fetch(url, config, &page, prior_cookies, want_screenshot).await
251285
})
252286
.await;
253287

254-
let result = fetch_outcome.unwrap_or_else(|_| Err(overall_deadline_error(overall_timeout)));
288+
// ~keep `session` is dropped as this function returns, after the result below is computed,
289+
// ~keep and its `Drop` spawns the teardown rather than awaiting it: a Chrome process stuck
290+
// ~keep behind a blocking OS dialog (the originally reported case: a macOS keychain prompt)
291+
// ~keep must not hold up delivery of a result that was already computed. `release_browser`
292+
// ~keep bounds its work by `shutdown_timeout` and force-kills a launched Chrome on expiry,
293+
// ~keep so that background task always finishes.
294+
fetch_outcome.unwrap_or_else(|_| Err(overall_deadline_error(overall_timeout)))
295+
}
296+
297+
/// Everything one [`one_shot_fetch`] has to tear down, owned by a single value whose `Drop`
298+
/// runs that teardown.
299+
///
300+
/// ~keep Teardown used to be straight-line code after the fetch, reached only once the fetch
301+
/// ~keep had finished, so a caller that dropped the future while it ran got none of it: the CDP
302+
/// ~keep connection to a `browser.endpoint` Chrome stayed open with the tab crawlberg had
303+
/// ~keep opened, and a launched Chrome's `--user-data-dir` was left on disk
304+
/// ~keep (xberg-io/crawlberg#131). Owning it in a value makes cancellation and completion the
305+
/// ~keep same path by construction, instead of two blocks that have to be kept in step by hand.
306+
struct OneShotSession {
307+
browser: Option<Browser>,
308+
/// The tab this fetch opened, recorded as soon as it exists so teardown can close it in a
309+
/// caller's Chrome even when the fetch never reaches its own cleanup.
310+
open_tab: Option<TargetId>,
311+
handler_handle: Option<JoinHandle<()>>,
312+
data_dir: Option<std::path::PathBuf>,
313+
shutdown_timeout: Duration,
314+
}
255315

256-
// ~keep Shutdown is spawned rather than awaited inline: a Chrome process stuck behind a
257-
// ~keep blocking OS dialog (the originally reported case: a macOS keychain prompt) must
258-
// ~keep not hold up delivery of a result that was already computed above.
259-
// ~keep `release_browser` bounds its work by `shutdown_timeout` and force-kills a launched
260-
// ~keep Chrome on expiry, so this background task always finishes.
261-
tokio::spawn(async move {
316+
impl OneShotSession {
317+
/// Open this fetch's tab, recording it for teardown, and hand back a handle to it.
318+
async fn open_page(&mut self) -> Result<chromiumoxide::Page, CrawlError> {
319+
let browser = self.browser.as_ref().expect("browser is taken only by Drop");
320+
let page = browser
321+
.new_page("about:blank")
322+
.await
323+
.map_err(|e| CrawlError::browser_error(format!("failed to create page: {e}")))?;
324+
self.open_tab = Some(page.target_id().clone());
325+
Ok(page)
326+
}
327+
}
328+
329+
impl Drop for OneShotSession {
330+
// ~keep `tokio::spawn` panics when no runtime is active on the current thread, and these
331+
// ~keep futures cross an FFI boundary into host GC/finalizer threads, so an unguarded spawn
332+
// ~keep here turns a late drop into a panic that aborts the embedding process -- the same
333+
// ~keep reasoning as `PooledPage`'s Drop in browser_pool.rs.
334+
fn drop(&mut self) {
335+
let (Some(browser), Some(handler_handle)) = (self.browser.take(), self.handler_handle.take()) else {
336+
return;
337+
};
262338
let cleanup = ExternalTabCleanup {
263-
open_tab: open_target,
339+
open_tab: self.open_tab.take(),
264340
..ExternalTabCleanup::default()
265341
};
266-
release_browser(browser, handler_handle, cleanup, shutdown_timeout).await;
267-
if let Some(dir) = data_dir {
268-
let _ = tokio::fs::remove_dir_all(&dir).await;
269-
}
270-
});
342+
let data_dir = self.data_dir.take();
343+
let shutdown_timeout = self.shutdown_timeout;
271344

272-
result
345+
match tokio::runtime::Handle::try_current() {
346+
Ok(handle) => {
347+
handle.spawn(async move {
348+
release_browser(browser, handler_handle, cleanup, shutdown_timeout).await;
349+
if let Some(dir) = data_dir {
350+
let _ = tokio::fs::remove_dir_all(&dir).await;
351+
}
352+
});
353+
}
354+
Err(_) => {
355+
tracing::warn!(
356+
"dropping a one-shot browser session outside a Tokio runtime; its Chrome \
357+
teardown is left to the process"
358+
);
359+
}
360+
}
361+
}
273362
}
274363

275364
#[cfg(feature = "browser-native")]

0 commit comments

Comments
 (0)