55use std:: sync:: atomic:: { AtomicU64 , Ordering as AtomicOrdering } ;
66use 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 ;
812use tokio_stream:: StreamExt ;
913use 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` .
131135async 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.
220257async 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