use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::RwLock;
use crate::fingerprint::StealthProfile;
use crate::fingerprint::browser_catalog::HeaderProfile;
use crate::rotation::named_profile;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeaderOrder {
pub family: &'static str,
pub slots: &'static [&'static str],
}
pub const CHROME_HEADER_ORDER: HeaderOrder = HeaderOrder {
family: "chrome",
slots: &[
"host",
"connection",
"cache-control",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
"upgrade-insecure-requests",
"user-agent",
"accept",
"sec-fetch-site",
"sec-fetch-mode",
"sec-fetch-user",
"sec-fetch-dest",
"accept-encoding",
"accept-language",
"cookie",
],
};
pub const FIREFOX_HEADER_ORDER: HeaderOrder = HeaderOrder {
family: "firefox",
slots: &[
"host",
"user-agent",
"accept",
"accept-language",
"accept-encoding",
"connection",
"upgrade-insecure-requests",
"sec-fetch-dest",
"sec-fetch-mode",
"sec-fetch-site",
"sec-fetch-user",
"cookie",
],
};
pub const SAFARI_HEADER_ORDER: HeaderOrder = HeaderOrder {
family: "safari",
slots: &[
"host",
"accept",
"accept-encoding",
"connection",
"user-agent",
"accept-language",
"cookie",
],
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct H2Profile {
pub family: &'static str,
pub settings: &'static [(u16, u32)],
pub initial_window_increment: u32,
}
pub const CHROME_H2: H2Profile = H2Profile {
family: "chrome",
settings: &[(1, 65_536), (2, 0), (4, 6_291_456), (6, 262_144)],
initial_window_increment: 15_663_105,
};
pub const FIREFOX_H2: H2Profile = H2Profile {
family: "firefox",
settings: &[(1, 65_536), (4, 131_072), (5, 16_384)],
initial_window_increment: 12_517_377,
};
pub const SAFARI_H2: H2Profile = H2Profile {
family: "safari",
settings: &[(3, 100), (4, 2_097_152), (8, 1)],
initial_window_increment: 10_485_760,
};
#[must_use]
pub fn pair_for_profile(profile: StealthProfile) -> Option<(HeaderOrder, H2Profile)> {
match profile {
StealthProfile::ChromeWindowsStable
| StealthProfile::ChromeWindowsLegacy96
| StealthProfile::ChromeMacStable
| StealthProfile::EdgeWindowsStable
| StealthProfile::ChromeAndroid
| StealthProfile::ChromeLinux
| StealthProfile::BraveWindows
| StealthProfile::OperaWindows
| StealthProfile::SamsungInternetAndroid => Some((CHROME_HEADER_ORDER, CHROME_H2)),
StealthProfile::FirefoxLinux | StealthProfile::FirefoxWindows => {
Some((FIREFOX_HEADER_ORDER, FIREFOX_H2))
}
StealthProfile::SafariIphone
| StealthProfile::SafariIpad
| StealthProfile::SafariMacStable => Some((SAFARI_HEADER_ORDER, SAFARI_H2)),
StealthProfile::Ie11Windows => None,
_ => None,
}
}
#[must_use]
pub fn pair_for_name(name: &str) -> Option<(HeaderOrder, H2Profile)> {
let key = name.to_ascii_lowercase();
if let Some(profile) = named_profile(&key) {
if let Some(pair) = pair_for_profile(profile) {
return Some(pair);
}
}
if key.starts_with("chrome") || key.starts_with("edge") {
return Some((CHROME_HEADER_ORDER, CHROME_H2));
}
if key.starts_with("firefox") {
return Some((FIREFOX_HEADER_ORDER, FIREFOX_H2));
}
if key.starts_with("safari") {
return Some((SAFARI_HEADER_ORDER, SAFARI_H2));
}
None
}
impl HeaderOrder {
#[must_use]
pub fn apply_in_order(&self, headers: Vec<(String, String)>) -> Vec<(String, String)> {
let mut by_name: HashMap<String, Vec<(String, String)>> = HashMap::new();
let mut input_order: Vec<String> = Vec::new();
for (name, value) in headers {
let lower = name.to_ascii_lowercase();
input_order.push(lower.clone());
by_name.entry(lower).or_default().push((name, value));
}
let mut out = Vec::new();
let mut consumed = HashSet::new();
for slot in self.slots {
let slot_lower = slot.to_ascii_lowercase();
if let Some(entries) = by_name.remove(&slot_lower) {
out.extend(entries);
consumed.insert(slot_lower);
}
}
let mut seen = HashSet::new();
for lower in input_order {
if consumed.contains(&lower) || !seen.insert(lower.clone()) {
continue;
}
if let Some(entries) = by_name.remove(&lower) {
out.extend(entries);
}
}
out
}
}
pub struct SessionPool {
profiles: Vec<&'static HeaderProfile>,
rotate_after_requests: u32,
bindings: RwLock<HashMap<String, (usize, u32)>>,
cursor: AtomicUsize,
}
impl SessionPool {
#[must_use]
pub fn new(profiles: Vec<&'static HeaderProfile>, rotate_after_requests: u32) -> Self {
assert!(
!profiles.is_empty(),
"SessionPool::new requires at least one profile"
);
Self {
profiles,
rotate_after_requests: rotate_after_requests.max(1),
bindings: RwLock::new(HashMap::new()),
cursor: AtomicUsize::new(0),
}
}
pub fn profile_for(&self, host: &str) -> &'static HeaderProfile {
debug_assert!(!self.profiles.is_empty());
let mut bindings = self
.bindings
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(entry) = bindings.get_mut(host) {
let (idx, count) = *entry;
if count.saturating_add(1) < self.rotate_after_requests {
entry.1 += 1;
return self.profiles[idx];
}
}
let idx = self.cursor.fetch_add(1, Ordering::Relaxed) % self.profiles.len();
bindings.insert(host.to_string(), (idx, 1));
self.profiles[idx]
}
pub fn clear(&self) {
self.bindings
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clear();
}
#[must_use]
pub fn snapshot(&self) -> Vec<(String, &'static str, u32)> {
let bindings = self
.bindings
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner());
bindings
.iter()
.map(|(host, (idx, count))| (host.clone(), self.profiles[*idx].name, *count))
.collect()
}
}
#[cfg(test)]
#[path = "session_coherence/tests.rs"]
mod tests;