mirror of
https://github.com/zhom/donutbrowser.git
synced 2026-12-05 01:53:29 +01:00
fix: small macOS RAM disk
This commit is contained in:
1 parent
ee138a1aed
commit
f8eba0d95a
2 files changed
+156
-26
No files matched your search
@@ -76,6 +76,44 @@ fn disk_fallback_base() -> PathBuf {
|
||||
std::env::temp_dir().join("donut-ephemeral")
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows", test))]
|
||||
const MIN_RAM_CAPACITY: u64 = 512 << 20;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows", test))]
|
||||
const MAX_RAM_CAPACITY: u64 = 4 << 30;
|
||||
|
||||
/// The size of the RAM storage for ephemeral and password-protected profiles:
|
||||
/// a quarter of the RAM, between 512 MiB and 4 GiB.
|
||||
#[cfg(any(target_os = "macos", target_os = "windows", test))]
|
||||
fn ram_capacity(total_ram: u64) -> u64 {
|
||||
(total_ram / 4).clamp(MIN_RAM_CAPACITY, MAX_RAM_CAPACITY)
|
||||
}
|
||||
|
||||
/// `ram_capacity` of this machine.
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
pub fn machine_ram_capacity() -> u64 {
|
||||
let mut system = crate::proxy_storage::process_table(sysinfo::RefreshKind::nothing());
|
||||
system.refresh_memory();
|
||||
ram_capacity(system.total_memory())
|
||||
}
|
||||
|
||||
/// Serializes making, reusing and detaching the macOS RAM disk, and counts the
|
||||
/// directories made on it, so an idle detach that a launch overtook does
|
||||
/// nothing.
|
||||
#[cfg(target_os = "macos")]
|
||||
static RAM_DISK_USES: Mutex<u64> = Mutex::new(0);
|
||||
|
||||
/// macOS reserves a RAM disk's whole size when it is made, and making one takes
|
||||
/// seconds, so the disk is detached once no profile has been on it this long.
|
||||
#[cfg(target_os = "macos")]
|
||||
const RAM_DISK_IDLE: std::time::Duration = std::time::Duration::from_secs(300);
|
||||
|
||||
/// A volume a quarter smaller than wanted was made for another size (an HFS+
|
||||
/// volume reports a little less than its device).
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn outgrown(size: u64, wanted: u64) -> bool {
|
||||
size < wanted / 4 * 3
|
||||
}
|
||||
|
||||
/// Whether an earlier run left a base that may hold directories to recover.
|
||||
/// Unlike `get_ephemeral_base_dir`, this never creates one.
|
||||
fn earlier_base_exists() -> bool {
|
||||
@@ -154,6 +192,10 @@ fn get_ephemeral_base_dir() -> Result<(PathBuf, EphemeralBacking), String> {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn get_or_create_macos_ramdisk() -> Result<PathBuf, String> {
|
||||
// A test that missed the override must not leave gigabytes of RAM mounted.
|
||||
if cfg!(test) {
|
||||
return Err("unit tests never mount a RAM disk".to_string());
|
||||
}
|
||||
let mount_point = PathBuf::from(MACOS_RAM_DISK);
|
||||
|
||||
// Reuse existing RAM disk from a previous session
|
||||
@@ -161,8 +203,8 @@ fn get_or_create_macos_ramdisk() -> Result<PathBuf, String> {
|
||||
return Ok(mount_point);
|
||||
}
|
||||
|
||||
// 256 MB in 512-byte sectors
|
||||
let sectors = 256 * 2048;
|
||||
let size = machine_ram_capacity();
|
||||
let sectors = size / 512;
|
||||
let output = std::process::Command::new("hdiutil")
|
||||
.args(["attach", "-nomount", &format!("ram://{sectors}")])
|
||||
.output()
|
||||
@@ -192,10 +234,87 @@ fn get_or_create_macos_ramdisk() -> Result<PathBuf, String> {
|
||||
));
|
||||
}
|
||||
|
||||
log::info!("RAM disk mounted path={MACOS_RAM_DISK} device={dev} size_mb=256");
|
||||
log::info!(
|
||||
"RAM disk mounted path={MACOS_RAM_DISK} device={dev} size_mb={}",
|
||||
size >> 20
|
||||
);
|
||||
Ok(mount_point)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn volume_size(path: &Path) -> Option<u64> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
|
||||
// SAFETY: `path` is NUL-terminated and `stat` is a valid out pointer.
|
||||
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
|
||||
(unsafe { libc::statvfs(path.as_ptr(), &mut stat) } == 0)
|
||||
.then(|| u64::from(stat.f_blocks) * stat.f_frsize)
|
||||
}
|
||||
|
||||
/// Detach the RAM disk now. Hold `RAM_DISK_USES`.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn detach_macos_ramdisk(reason: &str) -> bool {
|
||||
match std::process::Command::new("hdiutil")
|
||||
.args(["detach", "-force", MACOS_RAM_DISK])
|
||||
.output()
|
||||
{
|
||||
Ok(out) if out.status.success() => {
|
||||
log::info!("RAM disk detached path={MACOS_RAM_DISK} reason={reason}");
|
||||
true
|
||||
}
|
||||
Ok(out) => {
|
||||
log::warn!(
|
||||
"RAM disk detach failed path={MACOS_RAM_DISK} reason={reason} err=\"{}\"",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
);
|
||||
false
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("RAM disk detach failed path={MACOS_RAM_DISK} reason={reason} err=\"{e}\"");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A disk that an earlier session or an older Donut made smaller than this
|
||||
/// Mac's size gives way while no profile is on it, so the next one is made
|
||||
/// at full size. Hold `RAM_DISK_USES`.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn detach_outgrown_macos_ramdisk() {
|
||||
let mount = Path::new(MACOS_RAM_DISK);
|
||||
if ephemeral_base_override().is_some() || !holds_no_profile_dirs(mount) {
|
||||
return;
|
||||
}
|
||||
if volume_size(mount).is_some_and(|size| outgrown(size, machine_ram_capacity())) {
|
||||
detach_macos_ramdisk("outgrown");
|
||||
}
|
||||
}
|
||||
|
||||
/// Detach the RAM disk once it has held no profile for `RAM_DISK_IDLE`.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn detach_macos_ramdisk_when_idle() {
|
||||
if ephemeral_base_override().is_some() || !holds_no_profile_dirs(Path::new(MACOS_RAM_DISK)) {
|
||||
return;
|
||||
}
|
||||
let uses = *RAM_DISK_USES
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("ram-disk-idle".into())
|
||||
.spawn(move || {
|
||||
std::thread::sleep(RAM_DISK_IDLE);
|
||||
let now = RAM_DISK_USES
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if *now == uses && holds_no_profile_dirs(Path::new(MACOS_RAM_DISK)) {
|
||||
detach_macos_ramdisk("idle");
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("RAM disk idle timer failed to start err=\"{e}\"");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn existing_windows_ramdisk() -> Option<PathBuf> {
|
||||
['R', 'Q', 'P', 'O']
|
||||
@@ -216,6 +335,17 @@ fn get_or_create_windows_ramdisk() -> Result<PathBuf, String> {
|
||||
|
||||
pub fn create_ephemeral_dir(profile_id: &str) -> Result<PathBuf, String> {
|
||||
wait_for_recovery();
|
||||
// Held until the directory is on the disk, so an idle detach cannot take
|
||||
// the disk in between.
|
||||
#[cfg(target_os = "macos")]
|
||||
let _ram_disk = {
|
||||
let mut uses = RAM_DISK_USES
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
*uses += 1;
|
||||
detach_outgrown_macos_ramdisk();
|
||||
uses
|
||||
};
|
||||
let (base, backing) = get_ephemeral_base_dir()?;
|
||||
let dir_path = base.join(profile_id);
|
||||
|
||||
@@ -292,6 +422,10 @@ pub fn remove_ephemeral_dir(profile_id: &str) -> bool {
|
||||
if zero { "disk_zeroed" } else { "ram" },
|
||||
started.elapsed().as_millis()
|
||||
);
|
||||
#[cfg(target_os = "macos")]
|
||||
if backing == EphemeralBacking::Ram {
|
||||
detach_macos_ramdisk_when_idle();
|
||||
}
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -621,6 +755,22 @@ pub fn get_effective_profile_path(profile: &BrowserProfile, profiles_dir: &Path)
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ram_storage_is_a_quarter_of_ram_within_bounds() {
|
||||
assert_eq!(ram_capacity(1 << 30), MIN_RAM_CAPACITY);
|
||||
assert_eq!(ram_capacity(8 << 30), 2 << 30);
|
||||
assert_eq!(ram_capacity(64 << 30), MAX_RAM_CAPACITY);
|
||||
assert_eq!(ram_capacity(0), MIN_RAM_CAPACITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disk_from_the_old_fixed_size_is_outgrown() {
|
||||
// Issue: 256 MiB filled up with one protected profile's extensions.
|
||||
assert!(outgrown(256 << 20, 4 << 30));
|
||||
assert!(!outgrown((4 << 30) - (40 << 20), 4 << 30), "HFS+ overhead");
|
||||
assert!(!outgrown(4 << 30, 2 << 30), "a bigger disk stays");
|
||||
}
|
||||
|
||||
fn make_test_profile(id: uuid::Uuid, ephemeral: bool) -> BrowserProfile {
|
||||
BrowserProfile {
|
||||
id,
|
||||
|
||||
@@ -16,14 +16,6 @@ mod winfsp_fs;
|
||||
|
||||
pub use state::VolumeState;
|
||||
|
||||
const MIN_CAPACITY: u64 = 512 << 20;
|
||||
const MAX_CAPACITY: u64 = 4 << 30;
|
||||
|
||||
/// A quarter of the RAM, between 512 MiB and 4 GiB.
|
||||
pub fn volume_capacity(total_ram: u64) -> u64 {
|
||||
(total_ram / 4).clamp(MIN_CAPACITY, MAX_CAPACITY)
|
||||
}
|
||||
|
||||
/// Why the volume cannot be used, or `Ok` when WinFsp is ready.
|
||||
pub fn winfsp_available() -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
@@ -156,7 +148,7 @@ mod windows_client {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::host::{self, Unavailable};
|
||||
use super::{volume_capacity, Status, VolumeState};
|
||||
use super::{Status, VolumeState};
|
||||
|
||||
const MOUNT_WAIT: Duration = Duration::from_secs(10);
|
||||
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
|
||||
@@ -281,11 +273,7 @@ mod windows_client {
|
||||
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
let capacity = {
|
||||
let mut system = crate::proxy_storage::process_table(sysinfo::RefreshKind::nothing());
|
||||
system.refresh_memory();
|
||||
volume_capacity(system.total_memory())
|
||||
};
|
||||
let capacity = crate::ephemeral_dirs::machine_ram_capacity();
|
||||
let exe = crate::proxy_runner::find_sidecar_executable("donut-proxy")
|
||||
.map_err(|e| format!("donut-proxy not found: {e}"))?;
|
||||
let log =
|
||||
@@ -457,14 +445,6 @@ mod windows_client {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capacity_is_a_quarter_of_ram_within_bounds() {
|
||||
assert_eq!(volume_capacity(1 << 30), MIN_CAPACITY);
|
||||
assert_eq!(volume_capacity(8 << 30), 2 << 30);
|
||||
assert_eq!(volume_capacity(64 << 30), MAX_CAPACITY);
|
||||
assert_eq!(volume_capacity(0), MIN_CAPACITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_protected_profile_copy_holds_the_volume() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -510,7 +490,7 @@ mod tests {
|
||||
assert!(winfsp_available().is_err());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
host_main(&dir.path().join("m"), MIN_CAPACITY, &dir.path().join("s")),
|
||||
host_main(&dir.path().join("m"), 512 << 20, &dir.path().join("s")),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user