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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
use std::collections::HashMap;
use std::ffi::OsString;
use std::fmt::Formatter;
use std::future::{Future, IntoFuture};
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex as StdMutex, MutexGuard as StdMutexGuard, Weak};
use std::time::Duration;
use serde_json::Value;
use tokio::sync::{Mutex, OnceCell};
use url::Url;
use crate::Capabilities;
use crate::common::config::WebDriverConfig;
use crate::error::{WebDriverError, WebDriverResult};
use crate::extensions::query::IntoElementPoller;
use crate::session::DriverGuard;
use crate::session::create::start_session;
use crate::session::handle::SessionHandle;
use crate::session::http::create_reqwest_client;
use crate::web_driver::WebDriver;
use super::browser::{BrowserKind, detect_local_version};
use super::download::{DownloadConfig, Mirror, ensure_driver, resolve_version};
use super::error::ManagerError;
use super::process::{ManagedDriverProcess, SpawnConfig, SpawnContext, StdioMode};
use super::status::{
DriverId, DriverLogCallback, DriverLogLine, DriverLogSubscription, Emitter, LogSubscribers,
Status, StatusCallback, Subscription,
};
use super::version::DriverVersion;
const DEFAULT_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_READY_TIMEOUT: Duration = Duration::from_secs(30);
/// Default cache directory: `<cache_dir>/thirtyfour/drivers`, falling back to the
/// system temp dir if no cache dir is available.
fn default_cache_dir() -> PathBuf {
dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join("thirtyfour").join("drivers")
}
/// `(browser, local_version, caps_version)` — see `WebDriverManager::resolved_versions`.
type ResolvedVersionKey = (BrowserKind, Option<String>, Option<String>);
/// Auto-download and lifetime-managed local WebDriver process manager.
///
/// See the [module documentation](super) for the high-level usage. The two
/// common entry points are [`WebDriver::managed`] (one-shot, fresh manager
/// per call) and [`WebDriverManager::builder`] (for sharing one manager
/// across many sessions).
///
/// [`WebDriver::managed`]: crate::WebDriver::managed
pub struct WebDriverManager {
pub(crate) cfg: ResolvedConfig,
/// Configuration applied to every WebDriver session launched by this manager.
pub(crate) web_driver_config: WebDriverConfig,
/// HTTP client used for fetching upstream metadata and binaries.
download_client: reqwest::Client,
/// Map from `(browser, resolved_version)` to a Weak handle on a live driver.
drivers: Mutex<HashMap<DriverKey, Weak<ManagedDriverProcess>>>,
/// Cache for the local-browser version probe. The installed browser
/// doesn't change for the lifetime of a manager, so probing
/// `<browser> --version` once per `(browser, custom_binary)` is enough.
/// Skips repeated subprocess spawns and avoids transient
/// `Command::output` failures on busy CI runners.
local_versions: Mutex<HashMap<(BrowserKind, Option<String>), String>>,
/// Cache for upstream version resolution, keyed by
/// `(browser, local_version, caps_version)` — the inputs that can vary
/// between launches (the requested [`DriverVersion`] is fixed per
/// manager). One cell per key, so a slow resolution only holds up
/// launches waiting on the same key. Unused for [`DriverVersion::Latest`].
resolved_versions: Mutex<HashMap<ResolvedVersionKey, Arc<OnceCell<String>>>>,
/// Status-event emitter (also forwards to `tracing`).
pub(crate) emitter: Emitter,
/// Manager-wide driver-log subscribers — propagated into every spawned
/// `ManagedDriverProcess` so subscribers added at any time see lines from
/// every live driver.
pub(crate) log_subscribers: LogSubscribers,
/// Monotonic counter for [`DriverId`].
next_driver_id: Arc<AtomicU64>,
}
impl std::fmt::Debug for WebDriverManager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WebDriverManager")
.field("cfg", &self.cfg)
.field("web_driver_config", &self.web_driver_config)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub(crate) struct ResolvedConfig {
pub version: DriverVersion,
pub cache_dir: PathBuf,
pub host: IpAddr,
pub download_timeout: Duration,
pub ready_timeout: Duration,
pub shutdown_timeout: Duration,
pub offline: bool,
pub mirror: Mirror,
pub stdio: StdioMode,
/// Windows only: give the driver process its own console window instead
/// of suppressing it with `CREATE_NO_WINDOW`.
pub show_console_window: bool,
/// Per-browser driver-binary overrides. When a browser appears here,
/// `ensure_driver` skips download/cache and spawns the supplied binary
/// directly.
pub driver_paths: HashMap<BrowserKind, PathBuf>,
/// Additional command-line arguments, applied only to the selected browser's driver.
pub driver_args: HashMap<BrowserKind, Vec<OsString>>,
}
impl std::fmt::Debug for ResolvedConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResolvedConfig")
.field("version", &self.version)
.field("cache_dir", &self.cache_dir)
.field("host", &self.host)
.field("download_timeout", &self.download_timeout)
.field("ready_timeout", &self.ready_timeout)
.field("shutdown_timeout", &self.shutdown_timeout)
.field("offline", &self.offline)
.field("stdio", &self.stdio)
.field("show_console_window", &self.show_console_window)
.field("driver_paths", &self.driver_paths)
.field("driver_args", &self.driver_args)
.finish_non_exhaustive()
}
}
#[derive(Hash, PartialEq, Eq, Clone, Debug)]
pub(super) struct DriverKey {
pub(super) browser: BrowserKind,
pub(super) version: String,
pub(super) host: IpAddr,
}
impl DriverGuard for ManagedDriverProcess {}
/// Per-session guard held by `SessionHandle::driver_guard`. Keeps the
/// underlying [`ManagedDriverProcess`] alive for the lifetime of the session,
/// and emits [`Status::SessionEnded`] when dropped.
pub(crate) struct SessionGuard {
driver: StdMutex<Option<Arc<ManagedDriverProcess>>>,
emitter: Emitter,
browser: BrowserKind,
session_id: String,
cleanup_profile: Option<PathBuf>,
shutdown_timeout: Duration,
}
impl std::fmt::Debug for SessionGuard {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionGuard")
.field("browser", &self.browser)
.field("session_id", &self.session_id)
.field("driver", &self.driver())
.finish_non_exhaustive()
}
}
impl SessionGuard {
fn driver(&self) -> StdMutexGuard<'_, Option<Arc<ManagedDriverProcess>>> {
self.driver.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub(crate) fn driver_id(&self) -> Option<DriverId> {
self.driver().as_ref().map(|driver| driver.driver_id)
}
pub(crate) fn subscribe_log<F>(&self, f: F) -> Option<DriverLogSubscription>
where
F: Fn(&DriverLogLine) + Send + Sync + 'static,
{
self.driver().as_ref().map(|driver| driver.subscribe_log(f))
}
}
impl Drop for SessionGuard {
fn drop(&mut self) {
self.emitter.emit(Status::SessionEnded {
browser: self.browser,
session_id: self.session_id.clone(),
});
}
}
impl DriverGuard for SessionGuard {
fn release(&self) -> Pin<Box<dyn Future<Output = WebDriverResult<()>> + Send + '_>> {
Box::pin(async move {
let driver = self.driver().take();
if let Some(driver) = driver {
let deadline = tokio::time::Instant::now() + self.shutdown_timeout;
if let Some(profile) = &self.cleanup_profile {
wait_for_profile_cleanup(profile, deadline).await;
}
if let Some(process) = Arc::into_inner(driver) {
// Profile cleanup and process exit share one grace budget.
process
.shutdown_with_budget(
deadline.saturating_duration_since(tokio::time::Instant::now()),
)
.await
.map_err(WebDriverError::from)?;
}
}
Ok(())
})
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
// The DELETE reply is posted before ChromeDriver destroys the session. Keep
// its process lease alive until the generated profile disappears; /shutdown
// alone can stop the command thread before the session destructor finishes.
async fn wait_for_profile_cleanup(profile: &Path, deadline: tokio::time::Instant) {
loop {
match profile.try_exists() {
Ok(false) => return,
Err(error) => {
tracing::warn!(%error, "unable to inspect managed Chromium profile cleanup");
return;
}
Ok(true) => {}
}
if tokio::time::Instant::now() >= deadline {
tracing::warn!("managed Chromium profile still exists at shutdown deadline");
return;
}
tokio::time::sleep_until(std::cmp::min(
deadline,
tokio::time::Instant::now() + Duration::from_millis(20),
))
.await;
}
}
fn chromium_profile_options(browser: BrowserKind, requested: &Capabilities) -> bool {
let key = match browser {
BrowserKind::Chrome => "goog:chromeOptions",
BrowserKind::Edge => "ms:edgeOptions",
_ => return false,
};
let Some(options) = requested.get(key) else {
return true;
};
if options.get("detach").and_then(Value::as_bool) == Some(true)
|| options.get("debuggerAddress").is_some()
{
return false;
}
!options.get("args").and_then(Value::as_array).is_some_and(|args| {
args.iter().filter_map(Value::as_str).any(|arg| {
let arg = arg.trim_start_matches('-');
arg == "user-data-dir" || arg.starts_with("user-data-dir=")
})
})
}
// Chromium 136 introduced quitGracefully. On Windows, force-terminating only
// the main Chrome process can leave descendants holding chrome_debug.log,
// outliving ChromeDriver's finite profile-deletion retries. Let Chrome close
// its children normally. Preserve explicit caller choices and older drivers.
fn prefer_graceful_browser_quit(
browser: BrowserKind,
version: &str,
caps: &mut Capabilities,
) -> WebDriverResult<()> {
if !chromium_profile_options(browser, caps)
|| !version
.split('.')
.next()
.and_then(|v| v.parse::<u32>().ok())
.is_some_and(|major| major >= 136)
{
return Ok(());
}
let key = match browser {
BrowserKind::Chrome => "goog:chromeOptions",
BrowserKind::Edge => "ms:edgeOptions",
_ => return Ok(()),
};
if caps.get(key).is_none() {
caps.set(key, serde_json::json!({}))?;
}
if let Some(options) = caps.get_mut(key).and_then(Value::as_object_mut) {
options.entry("quitGracefully").or_insert(Value::Bool(true));
}
Ok(())
}
fn generated_profile(browser: BrowserKind, returned: &Capabilities) -> Option<PathBuf> {
let vendor = match browser {
BrowserKind::Chrome => "chrome",
BrowserKind::Edge => "msedge",
_ => return None,
};
let path = PathBuf::from(returned.get(vendor)?.get("userDataDir")?.as_str()?);
// Never wait for user-owned directories or delete anything ourselves.
let name = path.file_name()?.to_str()?;
(name.starts_with("scoped_dir") || name.contains(".scoped_dir.")).then_some(path)
}
/// Builder for [`WebDriverManager`]. The same type is used both via
/// `WebDriverManager::builder()` and (with capabilities preloaded) via
/// [`WebDriver::managed`]. See the [module documentation](super) for examples.
///
/// [`WebDriver::managed`]: crate::WebDriver::managed
#[derive(Default)]
pub struct WebDriverManagerBuilder {
pub(crate) version: DriverVersion,
pub(crate) cache_dir: Option<PathBuf>,
pub(crate) host: Option<IpAddr>,
pub(crate) download_timeout: Option<Duration>,
pub(crate) ready_timeout: Option<Duration>,
pub(crate) shutdown_timeout: Option<Duration>,
pub(crate) offline: Option<bool>,
pub(crate) mirror: Option<Mirror>,
pub(crate) stdio: Option<StdioMode>,
pub(crate) show_console_window: Option<bool>,
/// Per-browser driver-binary overrides registered via
/// [`WebDriverManagerBuilder::driver_binary`].
pub(crate) driver_paths: HashMap<BrowserKind, PathBuf>,
/// Per-browser driver-process arguments registered via
/// [`WebDriverManagerBuilder::driver_arg`].
pub(crate) driver_args: HashMap<BrowserKind, Vec<OsString>>,
/// Status subscribers registered before `build`.
pub(crate) status_subscribers: Vec<StatusCallback>,
/// Driver-log subscribers registered before `build`.
pub(crate) log_subscribers: Vec<DriverLogCallback>,
/// Configuration applied to every WebDriver session launched by the manager.
pub(crate) web_driver_config: WebDriverConfig,
/// Set when constructed via `WebDriver::managed(caps)`.
pub(crate) preloaded_caps: Option<Capabilities>,
}
impl std::fmt::Debug for WebDriverManagerBuilder {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WebDriverManagerBuilder")
.field("version", &self.version)
.field("cache_dir", &self.cache_dir)
.field("host", &self.host)
.field("download_timeout", &self.download_timeout)
.field("ready_timeout", &self.ready_timeout)
.field("shutdown_timeout", &self.shutdown_timeout)
.field("offline", &self.offline)
.field("stdio", &self.stdio)
.field("show_console_window", &self.show_console_window)
.field("driver_paths", &self.driver_paths)
.field("driver_args", &self.driver_args)
.field("status_subscribers", &self.status_subscribers.len())
.field("log_subscribers", &self.log_subscribers.len())
.field("web_driver_config", &self.web_driver_config)
.finish_non_exhaustive()
}
}
impl Clone for WebDriverManagerBuilder {
fn clone(&self) -> Self {
Self {
version: self.version.clone(),
cache_dir: self.cache_dir.clone(),
host: self.host,
download_timeout: self.download_timeout,
ready_timeout: self.ready_timeout,
shutdown_timeout: self.shutdown_timeout,
offline: self.offline,
mirror: self.mirror.clone(),
stdio: self.stdio,
show_console_window: self.show_console_window,
driver_paths: self.driver_paths.clone(),
driver_args: self.driver_args.clone(),
status_subscribers: self.status_subscribers.iter().map(Arc::clone).collect(),
log_subscribers: self.log_subscribers.iter().map(Arc::clone).collect(),
web_driver_config: self.web_driver_config.clone(),
preloaded_caps: self.preloaded_caps.clone(),
}
}
}
impl WebDriverManagerBuilder {
/// Set the configuration used by every [`WebDriver`] session launched by
/// the resulting manager.
pub fn config(mut self, config: WebDriverConfig) -> Self {
self.web_driver_config = config;
self
}
/// Set the element poller used by every [`WebDriver`] session launched by
/// the resulting manager.
///
/// This replaces the poller in the current [`WebDriverConfig`], including
/// a configuration previously supplied via
/// [`WebDriverManagerBuilder::config`].
pub fn poller(mut self, poller: Arc<dyn IntoElementPoller + Send + Sync>) -> Self {
self.web_driver_config.poller = poller;
self
}
/// Pick a driver version. See [`DriverVersion`] for variants.
pub fn version(mut self, v: DriverVersion) -> Self {
self.version = v;
self
}
/// Use the latest stable driver from upstream metadata, checked on every
/// launch.
///
/// <div class="warning">
///
/// **Warning:** In offline mode, `.latest()` selects the newest cached
/// driver, which may be older than the latest upstream release.
///
/// </div>
pub fn latest(self) -> Self {
self.version(DriverVersion::Latest)
}
/// Probe the locally-installed browser and use a matching driver. This is
/// the default; calling it explicitly is a no-op.
pub fn match_local(self) -> Self {
self.version(DriverVersion::MatchLocalBrowser)
}
/// Read `browserVersion` from the capabilities supplied to `launch()` /
/// `WebDriver::managed()`.
pub fn from_caps(self) -> Self {
self.version(DriverVersion::FromCapabilities)
}
/// Pin a specific version (full like `"126.0.6478.126"` or major-only like `"126"`).
pub fn exact(self, v: impl Into<String>) -> Self {
self.version(DriverVersion::Exact(v.into()))
}
/// Override the cache directory. Default: `<system cache dir>/thirtyfour/drivers`.
pub fn cache_dir(mut self, p: PathBuf) -> Self {
self.cache_dir = Some(p);
self
}
/// Override the host the driver binds to. Default: `127.0.0.1`.
pub fn host(mut self, h: IpAddr) -> Self {
self.host = Some(h);
self
}
/// Override the timeout for upstream metadata + binary downloads. Default: 60s.
pub fn download_timeout(mut self, d: Duration) -> Self {
self.download_timeout = Some(d);
self
}
/// Override the timeout for waiting on driver `/status` readiness. Default: 30s.
pub fn ready_timeout(mut self, d: Duration) -> Self {
self.ready_timeout = Some(d);
self
}
/// Grace budget for generated Chrome/Edge profile cleanup after each
/// successful session quit, plus process shutdown for the last session.
/// Defaults to 10 seconds; zero skips the cleanup wait and graceful shutdown.
///
/// The driver is killed if it has not exited within this budget. This does
/// not bound the preceding WebDriver DELETE request or OS process reaping.
/// Other browsers retain their force-kill shutdown behavior.
pub fn shutdown_timeout(mut self, timeout: Duration) -> Self {
self.shutdown_timeout = Some(timeout);
self
}
/// Refuse to download anything; require the driver to already be in cache.
///
/// No upstream metadata is fetched. Chrome uses the exact cached version
/// if present, otherwise the newest cached driver of the same major.
/// Edge major-only versions select the newest cached driver of that major;
/// full versions must be cached exactly. Firefox requires the literal
/// geckodriver tag for [`DriverVersion::Exact`], or the version selected by
/// the embedded compatibility table for browser-matching modes, to be
/// cached. [`DriverVersion::Latest`] selects the newest cached driver.
///
/// <div class="warning">
///
/// **Warning:** In offline mode, `.latest()` selects the newest cached
/// driver, which may be older than the latest upstream release.
///
/// </div>
pub fn offline(self) -> Self {
self.offline_mode(true)
}
/// Allow downloads. This is the default.
pub fn online(self) -> Self {
self.offline_mode(false)
}
/// Set offline mode explicitly.
pub fn offline_mode(mut self, yes: bool) -> Self {
self.offline = Some(yes);
self
}
/// Override the Chrome-for-Testing metadata base URL.
pub fn chrome_metadata_mirror(mut self, base: Url) -> Self {
let m = self.mirror.get_or_insert_with(Mirror::default);
m.chrome_metadata = base;
self
}
/// Override the geckodriver release metadata base URL, used to look up
/// the latest release: `<base>latest` must redirect to
/// `<base>tag/v<version>`. Default:
/// `https://github.com/mozilla/geckodriver/releases/`.
pub fn geckodriver_metadata_mirror(mut self, base: Url) -> Self {
let m = self.mirror.get_or_insert_with(Mirror::default);
m.geckodriver_metadata = base;
self
}
/// Override the geckodriver binary download base URL.
pub fn geckodriver_downloads_mirror(mut self, base: Url) -> Self {
let m = self.mirror.get_or_insert_with(Mirror::default);
m.geckodriver_downloads = base;
self
}
/// Override the msedgedriver download host.
pub fn edge_downloads_mirror(mut self, base: Url) -> Self {
let m = self.mirror.get_or_insert_with(Mirror::default);
m.edge_downloads = base;
self
}
/// Set how driver-process stdout/stderr is handled. Default:
/// [`StdioMode::Tracing`].
pub fn stdio(mut self, mode: StdioMode) -> Self {
self.stdio = Some(mode);
self
}
/// Windows only: give the driver process its own console window.
///
/// By default the driver is spawned with the `CREATE_NO_WINDOW` creation
/// flag so that no console window flashes up — this matters for GUI apps
/// built with `#![windows_subsystem = "windows"]`, where the console
/// subprocess would otherwise pop open a visible console. Driver output
/// is unaffected either way: stdout/stderr are still delivered according
/// to [`WebDriverManagerBuilder::stdio`].
///
/// No-op on non-Windows platforms.
pub fn show_console_window(mut self, yes: bool) -> Self {
self.show_console_window = Some(yes);
self
}
/// Use an already-installed driver binary at `path` for the given
/// browser instead of resolving and downloading one. Skips the
/// version-resolution and download/cache flow entirely; the binary is
/// spawned as-is. Bare command names (e.g. `"chromedriver"`) are
/// resolved against the OS `PATH`.
///
/// This is intended for environments that ship their own driver — CI
/// images with pinned binaries, sandboxes with no network access, or
/// users who simply prefer to manage driver versions themselves. If
/// the binary doesn't match the installed browser's version, expect a
/// runtime error from the driver when the session is started.
///
/// Call once per browser to override drivers for a multi-browser
/// manager:
///
/// ```no_run
/// # use thirtyfour::manager::{WebDriverManager, BrowserKind};
/// let mgr = WebDriverManager::builder()
/// .driver_binary(BrowserKind::Chrome, "/usr/local/bin/chromedriver")
/// .driver_binary(BrowserKind::Firefox, "/usr/local/bin/geckodriver")
/// .build();
/// ```
pub fn driver_binary(mut self, browser: BrowserKind, path: impl Into<PathBuf>) -> Self {
self.driver_paths.insert(browser, path.into());
self
}
/// Append one command-line argument for the given browser's driver process.
///
/// Arguments are passed directly to the driver, without shell expansion or
/// splitting. Call repeatedly to add multiple arguments; their order is
/// preserved. They apply to every process spawned for this browser by the
/// manager, including when using [`WebDriverManagerBuilder::driver_binary`].
///
/// These configure the driver server, whereas arguments in browser
/// capabilities configure the browser itself. Do not override
/// manager-controlled flags such as `--port`, `--allowed-ips`, or
/// `--websocket-port`.
///
/// To display ChromeDriver's verbose output directly in the parent terminal:
///
/// ```no_run
/// # use thirtyfour::prelude::*;
/// # use thirtyfour::manager::{BrowserKind, StdioMode};
/// # async fn run() -> WebDriverResult<()> {
/// let driver = WebDriver::managed(DesiredCapabilities::chrome())
/// .driver_arg(BrowserKind::Chrome, "--verbose")
/// .stdio(StdioMode::Inherit)
/// .await?;
/// driver.quit().await?;
/// # Ok(()) }
/// ```
///
/// With the default [`StdioMode::Tracing`], output is instead forwarded to
/// `tracing` at debug level and to [`WebDriverManagerBuilder::on_driver_log`]
/// subscribers, including during startup.
pub fn driver_arg(mut self, browser: BrowserKind, arg: impl Into<OsString>) -> Self {
self.driver_args.entry(browser).or_default().push(arg.into());
self
}
/// Register a closure to receive every [`Status`] event emitted by the
/// resulting manager. Equivalent to calling
/// [`WebDriverManager::subscribe`] right after `build`, except the
/// subscriber is attached for the manager's whole lifetime — not removable.
pub fn on_status<F>(mut self, f: F) -> Self
where
F: Fn(&Status) + Send + Sync + 'static,
{
self.status_subscribers.push(Arc::new(f));
self
}
/// Register a closure to receive every [`DriverLogLine`] from drivers
/// spawned by the resulting manager. Equivalent to
/// [`WebDriverManager::on_driver_log`] applied right after `build`, except
/// the subscriber is attached for the manager's whole lifetime — not
/// removable.
pub fn on_driver_log<F>(mut self, f: F) -> Self
where
F: Fn(&DriverLogLine) + Send + Sync + 'static,
{
self.log_subscribers.push(Arc::new(f));
self
}
/// Build the manager.
pub fn build(self) -> Arc<WebDriverManager> {
let cfg = ResolvedConfig {
version: self.version,
cache_dir: self.cache_dir.unwrap_or_else(default_cache_dir),
host: self.host.unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST)),
download_timeout: self.download_timeout.unwrap_or(DEFAULT_DOWNLOAD_TIMEOUT),
ready_timeout: self.ready_timeout.unwrap_or(DEFAULT_READY_TIMEOUT),
shutdown_timeout: self.shutdown_timeout.unwrap_or(Duration::from_secs(10)),
offline: self.offline.unwrap_or(false),
mirror: self.mirror.unwrap_or_default(),
stdio: self.stdio.unwrap_or_default(),
show_console_window: self.show_console_window.unwrap_or(false),
driver_paths: self.driver_paths,
driver_args: self.driver_args,
};
let emitter = Emitter::new();
for cb in self.status_subscribers {
// `forget` so the subscriber lives for the manager's lifetime.
std::mem::forget(emitter.add_arc(cb));
}
let log_subscribers = LogSubscribers::new();
for cb in self.log_subscribers {
std::mem::forget(log_subscribers.add_arc(cb));
}
Arc::new(WebDriverManager {
web_driver_config: self.web_driver_config,
download_client: reqwest::Client::builder()
.build()
.expect("default reqwest client should always build"),
cfg,
drivers: Mutex::new(HashMap::new()),
local_versions: Mutex::new(HashMap::new()),
resolved_versions: Mutex::new(HashMap::new()),
emitter,
log_subscribers,
next_driver_id: Arc::new(AtomicU64::new(0)),
})
}
}
impl IntoFuture for WebDriverManagerBuilder {
type Output = WebDriverResult<WebDriver>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move {
let caps = self
.preloaded_caps
.clone()
.ok_or_else(|| WebDriverError::from(ManagerError::NoCapabilities))?;
self.build().launch(caps).await
})
}
}
impl WebDriverManager {
/// Construct an empty builder.
pub fn builder() -> WebDriverManagerBuilder {
WebDriverManagerBuilder::default()
}
/// Register a closure to receive every [`Status`] event emitted by this
/// manager. Returns an RAII guard; dropping it removes the subscriber.
/// `mem::forget` keeps the subscriber alive for the manager's lifetime.
///
/// Subscribers are also forwarded to the `tracing` ecosystem under the
/// `thirtyfour::manager` target — they're additive, not a replacement.
pub fn subscribe<F>(&self, f: F) -> Subscription
where
F: Fn(&Status) + Send + Sync + 'static,
{
self.emitter.add(f)
}
/// Register a closure to receive every [`DriverLogLine`] from drivers
/// spawned (or to be spawned) by this manager. Returns an RAII guard;
/// dropping it removes the subscriber.
pub fn on_driver_log<F>(&self, f: F) -> DriverLogSubscription
where
F: Fn(&DriverLogLine) + Send + Sync + 'static,
{
self.log_subscribers.add(f)
}
pub(crate) fn mint_driver_id(&self) -> DriverId {
DriverId::from_raw(self.next_driver_id.fetch_add(1, Ordering::Relaxed))
}
/// Spawn (or reuse) the appropriate driver and start a session.
///
/// If a driver process for the same `(browser, resolved_version, host)` is
/// already alive (held by another `WebDriver`), it's reused. Otherwise a
/// new one is downloaded if needed and spawned.
pub async fn launch(
self: &Arc<Self>,
capabilities: impl Into<Capabilities>,
) -> WebDriverResult<WebDriver> {
let mut caps: Capabilities = capabilities.into();
let driver = self.ensure_driver(&caps).await.map_err(WebDriverError::from)?;
let browser = driver.browser;
if cfg!(windows) {
prefer_graceful_browser_quit(browser, &driver.version, &mut caps)?;
}
let server_url: Url = driver
.url()
.parse()
.map_err(|e| WebDriverError::ParseError(format!("invalid driver url: {e}")))?;
let config = self.web_driver_config.clone();
let client = create_reqwest_client(config.request_timeout);
let client_arc: Arc<dyn crate::session::http::HttpClient> = Arc::new(client);
self.emitter.emit(Status::SessionStarting {
browser,
url: server_url.to_string(),
});
let wait_for_profile = chromium_profile_options(browser, &caps);
let started = start_session(client_arc.as_ref(), &server_url, &config, caps).await?;
let cleanup_profile =
wait_for_profile.then(|| generated_profile(browser, &started.capabilities)).flatten();
let session_id = started.session_id.clone();
self.emitter.emit(Status::SessionStarted {
browser,
session_id: session_id.to_string(),
url: server_url.to_string(),
});
let guard: Arc<dyn DriverGuard> = Arc::new(SessionGuard {
driver: StdMutex::new(Some(driver)),
emitter: self.emitter.clone(),
browser,
session_id: session_id.to_string(),
cleanup_profile,
shutdown_timeout: self.cfg.shutdown_timeout,
});
let handle = SessionHandle::new_with_config_guard_and_caps(
client_arc,
server_url,
session_id,
config,
Some(guard),
started.capabilities,
)?;
Ok(WebDriver {
handle: Arc::new(handle),
})
}
/// Ensure a driver is running and return an `Arc<ManagedDriverProcess>`
/// whose existence keeps the child alive.
async fn ensure_driver(
&self,
caps: &Capabilities,
) -> Result<Arc<ManagedDriverProcess>, ManagerError> {
let browser = BrowserKind::from_capabilities(caps)?;
self.emitter.emit(Status::BrowserKindResolved {
browser,
});
// Manual binary override: skip the resolve/download flow entirely
// and spawn the supplied path directly. Version string for the
// DriverKey + Status events is synthesized from the path so manual
// entries don't collide with cache-keyed (browser, version) tuples.
if let Some(binary) = self.cfg.driver_paths.get(&browser).cloned() {
let version = format!("manual:{}", binary.display());
return self.spawn_or_reuse(browser, version, &binary).await;
}
// For MatchLocalBrowser we probe the binary up front (potentially using a
// capabilities-supplied path). Cached per `(browser, custom_binary)` so
// we don't re-spawn `<browser> --version` for every session.
let local = match self.cfg.version {
DriverVersion::MatchLocalBrowser => {
let custom = browser.binary_from_caps(caps);
let key = (browser, custom.clone());
let mut cache = self.local_versions.lock().await;
let version = match cache.get(&key) {
Some(v) => v.clone(),
None => {
let v = detect_local_version(browser, custom.as_deref(), &self.emitter)?;
cache.insert(key, v.clone());
v
}
};
Some(version)
}
_ => None,
};
let caps_version = caps.get("browserVersion").and_then(Value::as_str);
let resolved = self.resolve_version_cached(browser, local.as_deref(), caps_version).await?;
// Fast path: live driver matching `(browser, resolved, host)` already exists.
{
let key = DriverKey {
browser,
version: resolved.clone(),
host: self.cfg.host,
};
let map = self.drivers.lock().await;
if let Some(existing) = map.get(&key).and_then(Weak::upgrade) {
self.emitter.emit(Status::DriverReused {
browser,
version: resolved,
url: existing.url(),
});
return Ok(existing);
}
}
let driver_path = ensure_driver(
&self.download_client,
&self.download_config(),
browser,
&resolved,
&self.emitter,
)
.await?;
self.spawn_or_reuse(browser, resolved, &driver_path.binary).await
}
/// Resolve the driver version for a launch. Done once per
/// `(browser, local_version, caps_version)`; later launches reuse the
/// result without emitting the resolution [`Status`] events again.
/// [`DriverVersion::Latest`] is resolved on every launch.
pub(crate) async fn resolve_version_cached(
&self,
browser: BrowserKind,
local: Option<&str>,
caps_version: Option<&str>,
) -> Result<String, ManagerError> {
let resolve = || {
let cfg = self.download_config();
async move {
resolve_version(
&self.download_client,
&cfg,
browser,
&self.cfg.version,
local,
caps_version,
&self.emitter,
)
.await
}
};
if self.cfg.version == DriverVersion::Latest {
return resolve().await;
}
let key = (browser, local.map(str::to_owned), caps_version.map(str::to_owned));
let cell = self.resolved_versions.lock().await.entry(key).or_default().clone();
// Concurrent launches for the same key wait for the first one instead
// of each fetching the same metadata. A failed resolution leaves the
// cell empty; the next launch tries again.
cell.get_or_try_init(resolve).await.cloned()
}
fn download_config(&self) -> DownloadConfig {
DownloadConfig {
cache_dir: self.cfg.cache_dir.clone(),
mirror: self.cfg.mirror.clone(),
download_timeout: self.cfg.download_timeout,
offline: self.cfg.offline,
}
}
/// Cache-check, spawn, and register a managed driver process for
/// `(browser, version, host)`.
async fn spawn_or_reuse(
&self,
browser: BrowserKind,
version: String,
binary: &Path,
) -> Result<Arc<ManagedDriverProcess>, ManagerError> {
let key = DriverKey {
browser,
version: version.clone(),
host: self.cfg.host,
};
{
let map = self.drivers.lock().await;
if let Some(existing) = map.get(&key).and_then(Weak::upgrade) {
self.emitter.emit(Status::DriverReused {
browser,
version: version.clone(),
url: existing.url(),
});
return Ok(existing);
}
}
let process = ManagedDriverProcess::spawn(
binary,
browser,
&SpawnConfig {
host: self.cfg.host,
ready_timeout: self.cfg.ready_timeout,
shutdown_timeout: self.cfg.shutdown_timeout,
stdio: self.cfg.stdio,
show_console_window: self.cfg.show_console_window,
args: self.cfg.driver_args.get(&browser).cloned().unwrap_or_default(),
},
SpawnContext {
driver_id: self.mint_driver_id(),
version: &version,
emitter: &self.emitter,
manager_log_subscribers: self.log_subscribers.clone(),
},
)
.await?;
let arc = Arc::new(process);
let mut map = self.drivers.lock().await;
// Re-check after re-locking — another caller may have raced us.
if let Some(existing) = map.get(&key).and_then(Weak::upgrade) {
self.emitter.emit(Status::DriverReused {
browser,
version,
url: existing.url(),
});
return Ok(existing);
}
map.insert(key, Arc::downgrade(&arc));
Ok(arc)
}
}
#[cfg(test)]
mod profile_cleanup_tests {
#[test]
fn graceful_browser_default_is_version_gated_and_preserves_caller_options() {
for (browser, key) in
[(BrowserKind::Chrome, "goog:chromeOptions"), (BrowserKind::Edge, "ms:edgeOptions")]
{
for version in ["135.0.1", "unknown"] {
let mut caps = Capabilities::new();
prefer_graceful_browser_quit(browser, version, &mut caps).unwrap();
assert!(caps.get(key).is_none());
}
let mut caps = Capabilities::new();
prefer_graceful_browser_quit(browser, "136.0.1", &mut caps).unwrap();
assert_eq!(caps.get(key).unwrap()["quitGracefully"], true);
caps.set(key, serde_json::json!({"quitGracefully": false})).unwrap();
prefer_graceful_browser_quit(browser, "153.0.1", &mut caps).unwrap();
assert_eq!(caps.get(key).unwrap()["quitGracefully"], false);
for options in [
serde_json::json!({"args": ["--user-data-dir=owned"]}),
serde_json::json!({"detach": true}),
serde_json::json!({"debuggerAddress":"localhost:1234"}),
] {
caps.set(key, options.clone()).unwrap();
prefer_graceful_browser_quit(browser, "153.0.1", &mut caps).unwrap();
assert_eq!(caps.get(key), Some(&options));
}
}
}
use super::*;
use serde_json::json;
fn caps(value: Value) -> Capabilities {
serde_json::from_value(value).unwrap()
}
#[test]
fn only_owned_chromium_profiles_are_eligible() {
for (browser, key) in
[(BrowserKind::Chrome, "goog:chromeOptions"), (BrowserKind::Edge, "ms:edgeOptions")]
{
assert!(chromium_profile_options(browser, &Capabilities::new()));
assert!(chromium_profile_options(
browser,
&caps(json!({key: {"detach": false, "args": ["--headless"]}}))
));
for options in [
json!({"detach": true}),
json!({"debuggerAddress": "127.0.0.1:9222"}),
json!({"args": ["--user-data-dir=/some/profile"]}),
json!({"args": ["--user-data-dir", "/some/profile"]}),
json!({"args": ["user-data-dir=/some/profile"]}),
json!({"args": ["--user-data-dir="]}),
] {
assert!(
!chromium_profile_options(browser, &caps(json!({key: options}))),
"must exclude {options}"
);
}
}
assert!(!chromium_profile_options(BrowserKind::Firefox, &Capabilities::new()));
assert!(!chromium_profile_options(BrowserKind::Safari, &Capabilities::new()));
}
#[test]
fn generated_profile_requires_matching_vendor_and_temporary_name() {
let root = tempfile::tempdir().unwrap();
for (browser, vendor) in [(BrowserKind::Chrome, "chrome"), (BrowserKind::Edge, "msedge")] {
for name in [
"scoped_dir123_456",
"com.google.Chrome.scoped_dir.ABCDEF",
".org.chromium.Chromium.scoped_dir.ABCDEF",
] {
let path = root.path().join(name);
assert_eq!(
generated_profile(browser, &caps(json!({vendor: {"userDataDir": path}}))),
Some(path)
);
}
for invalid in
[json!(""), json!(root.path().join("my-profile")), json!(42), Value::Null]
{
assert_eq!(
generated_profile(browser, &caps(json!({vendor: {"userDataDir": invalid}}))),
None
);
}
assert_eq!(generated_profile(browser, &Capabilities::new()), None);
assert_eq!(generated_profile(browser, &caps(json!({vendor: {}}))), None);
}
let chrome = caps(json!({"chrome": {"userDataDir": root.path().join("scoped_dir123")}}));
assert_eq!(generated_profile(BrowserKind::Edge, &chrome), None);
assert_eq!(generated_profile(BrowserKind::Firefox, &chrome), None);
assert_eq!(generated_profile(BrowserKind::Safari, &chrome), None);
}
#[tokio::test]
async fn waits_for_profile_to_disappear_without_removing_it() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("scoped_dir123");
std::fs::create_dir(&path).unwrap();
let wait =
wait_for_profile_cleanup(&path, tokio::time::Instant::now() + Duration::from_secs(3));
tokio::pin!(wait);
// Poll once to prove it waits while the profile is present, rather
// than relying on scheduler timing or simply asserting eventual exit.
let pending =
std::future::poll_fn(|cx| std::task::Poll::Ready(wait.as_mut().poll(cx).is_pending()))
.await;
assert!(pending);
assert!(path.exists(), "the waiter must never remove a profile");
std::fs::remove_dir(&path).unwrap(); // Stand in for ChromeDriver cleanup.
tokio::time::timeout(Duration::from_secs(1), wait).await.unwrap();
}
#[tokio::test]
async fn deadline_preserves_existing_profile_and_absent_profile_returns() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("scoped_dir123");
std::fs::create_dir(&path).unwrap();
for budget in [Duration::ZERO, Duration::from_millis(40)] {
let started = tokio::time::Instant::now();
tokio::time::timeout(
Duration::from_secs(1),
wait_for_profile_cleanup(&path, started + budget),
)
.await
.unwrap();
assert!(started.elapsed() >= budget);
assert!(path.exists(), "timeout must not delete the profile");
}
let absent = root.path().join("absent");
tokio::time::timeout(
Duration::from_millis(100),
wait_for_profile_cleanup(
&absent,
tokio::time::Instant::now() + Duration::from_secs(30),
),
)
.await
.unwrap();
}
}