headless_browser_lib 0.1.24

A library providing a Chrome proxy API for managing Chrome instances in cloud environments.
Documentation
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
use std::sync::atomic::{AtomicBool, AtomicU64};

/// The performance arg count.
#[cfg(not(feature = "physical_gpu"))]
pub(crate) const PERF_ARGS: usize = 99;

/// The performance arg count.
#[cfg(feature = "physical_gpu")]
pub(crate) const PERF_ARGS: usize = 97;

lazy_static::lazy_static! {
    /// The chrome args to use test ( basic without anything used for testing ).
    pub static ref CHROME_ARGS_TEST: [&'static str; 6] = {
        let headless = std::env::args()
        .nth(6)
        .unwrap_or("true".into());

        let headless = if headless != "false" {
            match std::env::var("HEADLESS") {
                Ok(h) => {
                    if h == "false" {
                        ""
                    } else if h == "new" {
                        "--headless=new"
                    }else {
                        "--headless"
                    }
                }
                _ => "--headless"
            }
        } else {
            ""
        };

        let port = if DEFAULT_PORT.eq(&9223) {
            "--remote-debugging-port=9223"
        } else if DEFAULT_PORT.eq(&9224) {
            "--remote-debugging-port=9224"
        } else {
            "--remote-debugging-port=9222"
        };

        let use_gl = match std::env::var("CHROME_GL") {
            Ok(h) => {
                if h == "angle" {
                    "--use-gl=angle"
                } else {
                    "--use-gl=swiftshader"
                }
            }
            _ => "--use-gl=angle"
        };

        let gpu = std::env::var("ENABLE_GPU").unwrap_or_default() == "true";

        let gpu_enabled = if gpu { "--enable-gpu" } else { "--disable-gpu" };
        let gpu_enabled_sandboxed = if gpu { "--enable-gpu-sandbox" } else { "--disable-gpu-sandbox" };

        [
            // *SPECIAL*
            "--remote-debugging-address=0.0.0.0",
            port,
            // *SPECIAL*
            headless,
            gpu_enabled,
            gpu_enabled_sandboxed,
            use_gl,
        ]
    };
}

lazy_static::lazy_static! {
    /// Is the instance healthy?
    pub static ref IS_HEALTHY: AtomicBool = AtomicBool::new(true);
    pub static ref CHROME_INSTANCES: dashmap::DashSet<u32> = dashmap::DashSet::new();
    pub static ref DEFAULT_PORT: u32 = {
        let default_port = std::env::args()
            .nth(4)
            .unwrap_or("9223".into())
            .parse::<u32>()
            .unwrap_or_default();

        let default_port = if default_port == 0 {
            9223
        } else {
            default_port
        };

        default_port
    };
    pub static ref DEFAULT_PORT_SERVER: u16 = {
        let default_port = std::env::args()
            .nth(5)
            .unwrap_or("6000".into())
            .parse::<u16>()
            .unwrap_or_default();
        let default_port = if default_port == 0 {
            6000
        } else {
            default_port
        };

        default_port
    };
    /// Is a brave instance?
    pub(crate) static ref BRAVE_INSTANCE: bool = {
        CHROME_PATH.ends_with("Brave Browser")
        || CHROME_PATH.ends_with("brave-browser")
    };
    /// Is a lightpanda instance?
    pub(crate) static ref LIGHT_PANDA: bool = {
        CHROME_PATH.ends_with("lightpanda-aarch64-macos")
        || CHROME_PATH.ends_with("lightpanda-x86_64-linux")
    };
    /// The light panda args to use.
    pub static ref LIGHTPANDA_ARGS: [&'static str; 2] = {
        let port = if DEFAULT_PORT.eq(&9223) {
            "--port=9223"
        } else if DEFAULT_PORT.eq(&9224) {
            "--port=9224"
        } else {
            "--port=9222"
        };

        [
            "--host=0.0.0.0",
            port,
        ]
    };
    /// Return base target and replacement. Target port is the port for chrome.
    pub(crate) static ref TARGET_REPLACEMENT: (&'static [u8; 5], &'static[u8; 5]) = {
        if *DEFAULT_PORT == 9223 {
            let target_port = b":9223";
            let proxy_port = b":9222";

            (target_port, proxy_port)
        } else {
            // we need to allow dynamic ports instead of defaulting to standard and xfvb offport.
            let target_port = b":9224";
            let proxy_port = b":9223";

            (target_port, proxy_port)
        }
    };
    /// The hostname of the machine to replace 127.0.0.1 when making request to /json/version on port 6000.
    pub(crate) static ref HOST_NAME: String = {
        let mut hostname = String::new();

        if let Ok(name) = std::env::var("HOSTNAME_OVERRIDE") {
            if !name.is_empty() {
                hostname = name;
            }
        }

        if hostname.is_empty() {
            if let Ok(name) = std::env::var("HOSTNAME") {
                if !name.is_empty() {
                    hostname = name;
                }
            }
        }

        hostname
    };
    /// The main endpoint for entry.
    pub(crate) static ref ENDPOINT_BASE: String = {
        format!("http://127.0.0.1:{}", *DEFAULT_PORT)
    };
    /// The main endpoint json/version.
    pub(crate) static ref ENDPOINT: String = {
        format!("http://127.0.0.1:{}/json/version", *DEFAULT_PORT)
    };
    /// The chrome launch path.
    pub static ref CHROME_PATH: String = {
        // cargo bench will always pass in the first arg
        let default_path = std::env::args().nth(1).unwrap_or_default();
        let trimmed_path = default_path.trim();

        // handle testing and default to OS
        if default_path.is_empty() || trimmed_path == "--nocapture" || trimmed_path == "--bench" {
            let chrome_path = match std::env::var("CHROME_PATH") {
                Ok(p) => p,
                _ => Default::default()
            };

            if chrome_path.is_empty() {
                get_default_chrome_bin().to_string()
            } else {
                chrome_path
            }
        } else {
            default_path
        }
    };
    /// The chrome address.
    pub(crate) static ref CHROME_ADDRESS: String = {
        let mut host_address = std::env::args().nth(2).unwrap_or("127.0.0.1".to_string()).to_string();

        if host_address.is_empty() {
            host_address = String::from("127.0.0.1").into()
        }

        host_address
    };
    pub(crate) static ref CACHEABLE: AtomicBool = {
        AtomicBool::new(true)
    };
    /// The last cache date period.
    pub(crate) static ref LAST_CACHE: AtomicU64 = {
        AtomicU64::new(0)
    };
    /// Debug the json version endpoint.
    pub(crate) static ref DEBUG_JSON: bool = std::env::var("DEBUG_JSON").unwrap_or_default() == "true";
    /// Test headless without args.
    pub(crate) static ref TEST_NO_ARGS: bool = std::env::var("TEST_NO_ARGS").unwrap_or_default() == "true";
    /// Entry port to the proxy.
    pub(crate) static ref ENTRY: &'static str = {
        if crate::TARGET_REPLACEMENT.0 == b":9223" {
            "0.0.0.0:9222"
        } else {
            "0.0.0.0:9223"
        }
    };
    /// Target chrome server.
    pub(crate) static ref TARGET: &'static str = {
        if crate::TARGET_REPLACEMENT.1 == b":9222" {
            "0.0.0.0:9223"
        } else {
            "0.0.0.0:9224"
        }
    };
    /// The buffer size.
    pub(crate) static ref BUFFER_SIZE: usize = {
        let buffer_size = std::env::var("BUFFER_SIZE")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(131072); // Default to 128kb
        buffer_size
    };
    /// 10 sec cache
    pub(crate) static ref TEN_SECONDS: std::time::Duration = {
        std::time::Duration::from_secs(10)
    };
}

#[cfg(not(feature = "physical_gpu"))]
lazy_static::lazy_static! {
        /// The chrome args to use.
        pub static ref CHROME_ARGS: [&'static str; PERF_ARGS] = {
            let headless = std::env::args()
            .nth(6)
            .unwrap_or("true".into());

            let headless = match (headless != "false", std::env::var("HEADLESS").as_deref()) {
                (false, _) | (true, Ok("false")) => "--test-type=gpu",
                (_, Ok("new")) => "--headless=new",
                _ => "--headless",
            };

            let port = if DEFAULT_PORT.eq(&9223) {
                "--remote-debugging-port=9223"
            } else if DEFAULT_PORT.eq(&9224) {
                "--remote-debugging-port=9224"
            } else {
                "--remote-debugging-port=9222"
            };
            let gpu = std::env::var("ENABLE_GPU").unwrap_or_default() == "true";
            let gpu_enabled = if gpu { "--enable-gpu" } else { "--disable-gpu" };
            let gpu_enabled_sandboxed = if gpu { "--enable-gpu-sandbox" } else { "--disable-gpu-sandbox" };

            let use_gl = match std::env::var("CHROME_GL") {
                Ok(h) => {
                    if h == "angle" {
                        "--use-gl=angle"
                    } else {
                        "--use-gl=swiftshader"
                    }
                }
                _ => "--use-gl=swiftshader"
            };

            [
                // *SPECIAL*
                "--remote-debugging-address=0.0.0.0",
                port,
                // *SPECIAL*
                headless,
                gpu_enabled,
                gpu_enabled_sandboxed,
                use_gl,
                "--no-zygote",
                "--user-data-dir=~/.config/google-chrome",
                "--ignore-certificate-errors",
                "--no-default-browser-check",
                "--no-first-run",
                "--no-sandbox",
                "--enable-webgl",
                "--enable-webgl2-compute-context",
                "--enable-webgl-draft-extensions",
                "--enable-unsafe-webgpu",
                "--enable-web-bluetooth",
                "--enable-dom-distiller",
                "--enable-distillability-service",
                "--enable-surface-synchronization",
                "--enable-logging=stderr",
                "--enable-async-dns",
                "--disable-setuid-sandbox",
                "--disable-dev-shm-usage", // required or else container will crash not enough memory
                "--disable-threaded-scrolling",
                "--disable-cookie-encryption",
                "--disable-demo-mode",
                "--disable-dinosaur-easter-egg",
                "--disable-fetching-hints-at-navigation-start",
                "--disable-site-isolation-trials",
                "--disable-threaded-animation",
                "--disable-sync",
                "--disable-print-preview",
                "--disable-search-engine-choice-screen",
                "--disable-in-process-stack-traces",
                "--disable-low-res-tiling",
                "--disable-oobe-chromevox-hint-timer-for-testing",
                "--disable-smooth-scrolling",
                "--disable-prompt-on-repost",
                "--disable-domain-reliability",
                "--disable-gesture-typing",
                "--disable-background-timer-throttling",
                "--disable-breakpad",
                "--disable-crash-reporter",
                "--disable-asynchronous-spellchecking",
                "--disable-html5-camera",
                "--disable-hang-monitor",
                "--disable-checker-imaging",
                "--disable-image-animation-resync",
                "--disable-client-side-phishing-detection",
                "--disable-component-extensions-with-background-pages",
                "--disable-background-networking",
                "--disable-renderer-backgrounding",
                "--disable-field-trial-config",
                "--disable-back-forward-cache",
                "--disable-backgrounding-occluded-windows",
                "--disable-stack-profiler",
                "--disable-libassistant-logfile",
                "--disable-datasaver-prompt",
                "--disable-histogram-customizer",
                "--disable-vulkan-fallback-to-gl-for-testing",
                "--disable-vulkan-surface",
                "--disable-webrtc",
                "--disable-oopr-debug-crash-dump",
                "--disable-pnacl-crash-throttling",
                "--disable-renderer-accessibility",
                "--disable-pushstate-throttle",
                "--disable-blink-features=AutomationControlled",
                "--disable-ipc-flooding-protection", // we do not need to throttle navigation for https://github.com/spider-rs/spider/commit/9ff5bbd7a2656b8edb84b62843b72ae9d09af079#diff-75ce697faf0d37c3dff4a3a19e7524798b3cb5487f8f54beb5d04c4d48e34234R446.
                "--noerrdialogs",
                "--hide-scrollbars",
                "--allow-running-insecure-content",
                "--autoplay-policy=user-gesture-required",
                "--run-all-compositor-stages-before-draw",
                "--log-level=3",
                "--font-render-hinting=none",
                "--block-new-web-contents",
                "--no-subproc-heap-profiling",
                "--use-fake-device-for-media-stream",
                "--use-fake-ui-for-media-stream",
                "--no-pre-read-main-dll",
                "--ip-protection-proxy-opt-out",
                "--unsafely-disable-devtools-self-xss-warning",
                "--metrics-recording-only",
                "--use-mock-keychain",
                "--force-color-profile=srgb",
                "--disable-infobars",
                "--mute-audio",
                "--no-service-autorun",
                "--password-store=basic",
                "--export-tagged-pdf",
                "--no-pings",
                "--rusty-png",
                "--window-size=800,600",
                &crate::render_conf::RENDER_PROCESS_LIMIT,
                // --deterministic-mode 10-20% drop in perf
                // "--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4",
                "--enable-features=Vulkan,PdfOopif,SharedArrayBuffer,NetworkService,NetworkServiceInProcess",
                "--disable-features=PaintHolding,HttpsUpgrades,DeferRendererTasksAfterInput,LensOverlay,ThirdPartyStoragePartitioning,IsolateSandboxedIframes,ProcessPerSiteUpToMainFrameThreshold,site-per-process,WebUIJSErrorReportingExtended,DIPS,InterestFeedContentSuggestions,PrivacySandboxSettings4,AutofillServerCommunication,CalculateNativeWinOcclusion,OptimizationHints,AudioServiceOutOfProcess,IsolateOrigins,ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate",
                // put these args on the same command for now to prevent empty args cross-platform execution. The args will be one less on gpu enabled builds.
                "--enable-unsafe-swiftshader",
                "--use-angle=swiftshader"
            ]
        };
}

#[cfg(feature = "physical_gpu")]
lazy_static::lazy_static! {
        /// The chrome args to use.
        pub static ref CHROME_ARGS: [&'static str; PERF_ARGS] = {
            let headless = std::env::args()
            .nth(6)
            .unwrap_or("true".into());

            let headless = match (headless != "false", std::env::var("HEADLESS").as_deref()) {
                (false, _) | (true, Ok("false")) => "--test-type=gpu",
                (_, Ok("new")) => "--headless=new",
                _ => "--headless",
            };

            let port = if DEFAULT_PORT.eq(&9223) {
                "--remote-debugging-port=9223"
            } else if DEFAULT_PORT.eq(&9224) {
                "--remote-debugging-port=9224"
            } else {
                "--remote-debugging-port=9222"
            };
            let use_gl = "--use-gl=angle";

            [
                // *SPECIAL*
                "--remote-debugging-address=0.0.0.0",
                port,
                // *SPECIAL*
                headless,
                "--enable-gpu",
                "--enable-gpu-sandbox",
                "--enable-webgl",
                "--enable-webgl2-compute-context",
                "--enable-webgl-draft-extensions",
                "--enable-unsafe-webgpu",
                use_gl,
                "--no-first-run",
                "--no-sandbox",
                "--disable-setuid-sandbox",
                "--no-zygote",
                "--enable-async-dns",
                "--hide-scrollbars",
                "--user-data-dir=~/.config/google-chrome",
                "--allow-running-insecure-content",
                "--autoplay-policy=user-gesture-required",
                "--ignore-certificate-errors",
                "--no-default-browser-check",
                "--disable-dev-shm-usage", // required or else container will crash not enough memory
                "--disable-threaded-scrolling",
                "--disable-cookie-encryption",
                "--disable-demo-mode",
                "--disable-dinosaur-easter-egg",
                "--disable-fetching-hints-at-navigation-start",
                "--disable-site-isolation-trials",
                "--disable-threaded-animation",
                "--disable-sync",
                "--disable-print-preview",
                "--disable-search-engine-choice-screen",
                "--disable-in-process-stack-traces",
                "--disable-low-res-tiling",
                "--disable-oobe-chromevox-hint-timer-for-testing",
                "--disable-smooth-scrolling",
                "--disable-prompt-on-repost",
                "--disable-domain-reliability",
                "--enable-web-bluetooth",
                "--enable-dom-distiller",
                "--enable-distillability-service",
                "--enable-surface-synchronization",
                "--disable-gesture-typing",
                "--disable-background-timer-throttling",
                "--disable-breakpad",
                "--disable-crash-reporter",
                "--disable-asynchronous-spellchecking",
                "--disable-html5-camera",
                "--noerrdialogs",
                "--disable-hang-monitor",
                "--disable-checker-imaging",
                "--disable-image-animation-resync",
                "--disable-client-side-phishing-detection",
                "--disable-component-extensions-with-background-pages",
                "--run-all-compositor-stages-before-draw",
                "--disable-background-networking",
                "--disable-renderer-backgrounding",
                "--disable-field-trial-config",
                "--disable-back-forward-cache",
                "--disable-backgrounding-occluded-windows",
                "--log-level=3",
                "--enable-logging=stderr",
                "--font-render-hinting=none",
                "--block-new-web-contents",
                "--no-subproc-heap-profiling",
                "--use-fake-device-for-media-stream",
                "--use-fake-ui-for-media-stream",
                "--no-pre-read-main-dll",
                "--disable-stack-profiler",
                "--disable-libassistant-logfile",
                "--ip-protection-proxy-opt-out",
                "--unsafely-disable-devtools-self-xss-warning",
                "--enable-features=Vulkan,PdfOopif,SharedArrayBuffer,NetworkService,NetworkServiceInProcess",
                "--metrics-recording-only",
                "--use-mock-keychain",
                "--force-color-profile=srgb",
                "--disable-infobars",
                "--mute-audio",
                "--disable-datasaver-prompt",
                "--no-service-autorun",
                "--password-store=basic",
                "--export-tagged-pdf",
                "--no-pings",
                "--rusty-png",
                "--disable-histogram-customizer",
                "--window-size=800,600",
                "--disable-vulkan-fallback-to-gl-for-testing",
                "--disable-vulkan-surface",
                "--disable-webrtc",
                "--disable-oopr-debug-crash-dump",
                "--disable-pnacl-crash-throttling",
                "--disable-renderer-accessibility",
                &crate::render_conf::RENDER_PROCESS_LIMIT,
                "--disable-pushstate-throttle",
                "--disable-blink-features=AutomationControlled",
                "--disable-ipc-flooding-protection", // we do not need to throttle navigation for https://github.com/spider-rs/spider/commit/9ff5bbd7a2656b8edb84b62843b72ae9d09af079#diff-75ce697faf0d37c3dff4a3a19e7524798b3cb5487f8f54beb5d04c4d48e34234R446.
                // --deterministic-mode 10-20% drop in perf
                // "--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4",
                "--disable-features=PaintHolding,HttpsUpgrades,DeferRendererTasksAfterInput,LensOverlay,ThirdPartyStoragePartitioning,IsolateSandboxedIframes,ProcessPerSiteUpToMainFrameThreshold,site-per-process,WebUIJSErrorReportingExtended,DIPS,InterestFeedContentSuggestions,PrivacySandboxSettings4,AutofillServerCommunication,CalculateNativeWinOcclusion,OptimizationHints,AudioServiceOutOfProcess,IsolateOrigins,ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate",
            ]
        };
}

/// Get the default chrome bin location per OS.
fn get_default_chrome_bin() -> &'static str {
    let brave = match std::env::var("BRAVE_ENABLED") {
        Ok(v) => v == "true",
        _ => false,
    };

    if cfg!(target_os = "windows") {
        if brave {
            "brave-browser.exe"
        } else {
            "chrome.exe"
        }
    } else if cfg!(target_os = "macos") {
        if brave {
            "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"
        } else {
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
        }
    } else if cfg!(target_os = "linux") {
        if brave {
            "brave-browser"
        } else {
            "chromium"
        }
    } else {
        if brave {
            "brave"
        } else {
            "chrome"
        }
    }
}