Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/oneclient_app/src/components/memory_field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub fn memory_field(mut memory: State<String>) -> impl IntoElement {
.child(
TextInput::new(memory)
.width(Size::px(90.))
.placeholder("4096")
.placeholder(oneclient_common::default_mem_max().to_string())
.on_validate(validate_memory)
.trailing(
label()
Expand Down
16 changes: 3 additions & 13 deletions packages/oneclient_app/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use chrono::{Datelike, NaiveDate};
use oneclient_core::clusters::Cluster;
use oneclient_common::domain::GameLoader;
use oneclient_common::{ParsedMcVersion, VersionKey, format_mc_version, parse_mc_version};
use sysinfo::{MemoryRefreshKind, RefreshKind, System};

use oneclient_common::MEMORY_HEADROOM_GB;
pub use oneclient_common::total_ram_mb;

pub type ClusterGroups = BTreeMap<ReleaseLine, Vec<Cluster>>;

Expand Down Expand Up @@ -207,20 +209,8 @@ pub fn format_res((w, h): (u32, u32)) -> String {

/// Prevents user from choosing his max amount of ram preset (e.g Someone has 16GB of RAM,
/// so the max preset is 16GB - 2GB = 14GB)
const MEMORY_HEADROOM_GB: u32 = 2;
const MEMORY_PRESETS_GB: [u32; 10] = [2, 4, 6, 8, 12, 16, 24, 32, 48, 64];

pub fn total_ram_mb() -> u32 {
static TOTAL_RAM_MB: std::sync::OnceLock<u32> = std::sync::OnceLock::new();

*TOTAL_RAM_MB.get_or_init(|| {
let system = System::new_with_specifics(
RefreshKind::nothing().with_memory(MemoryRefreshKind::nothing().with_ram()),
);
(system.total_memory() / 1024 / 1024).min(u32::MAX as u64) as u32
})
}

pub fn memory_presets_mb() -> Vec<u32> {
presets_for_total_gb((total_ram_mb() as f32 / 1024.).round() as u32)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ impl Component for ClusterSettings {
MemoryRow {
cluster_id,
value: profile.mem_max,
global: global.mem_max.unwrap_or(4096),
global: global
.mem_max
.unwrap_or_else(oneclient_common::default_mem_max),
}
.into_element(),
)
Expand Down
2 changes: 1 addition & 1 deletion packages/oneclient_cluster/src/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl GameSettingsProfile {
java_path: None,
resolution: None,
force_fullscreen: Some(false),
mem_max: Some(4096),
mem_max: Some(oneclient_common::default_mem_max()),
launch_args: None,
launch_env: None,
hook_pre: None,
Expand Down
1 change: 1 addition & 0 deletions packages/oneclient_common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ interfrost.workspace = true
directories.workspace = true
serde.workspace = true
strum.workspace = true
sysinfo.workspace = true
thiserror.workspace = true
2 changes: 2 additions & 0 deletions packages/oneclient_common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

pub mod constants;
pub mod domain;
pub mod memory;
pub mod os_ext;
pub mod paths;
pub mod patch;
Expand All @@ -15,6 +16,7 @@ pub use domain::{
ContentType, GameLoader, HashAlgorithm, PackageUpdateMode, ProviderId, Resolution,
};
pub use error::{PathsError, PathsResult};
pub use memory::{MEMORY_HEADROOM_GB, default_mem_max, default_mem_max_for_total, total_ram_mb};
pub use os_ext::OsExt;
pub use patch::Patch;
pub use search::{MatchScore, SearchQuery, normalize_query};
Expand Down
55 changes: 55 additions & 0 deletions packages/oneclient_common/src/memory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use sysinfo::{MemoryRefreshKind, RefreshKind, System};

pub const MEMORY_HEADROOM_GB: u32 = 2;

const EIGHT_GB_MB: u32 = 7 * 1024;
const TWELVE_GB_MB: u32 = 11 * 1024;

pub fn total_ram_mb() -> u32 {
static TOTAL_RAM_MB: std::sync::OnceLock<u32> = std::sync::OnceLock::new();

*TOTAL_RAM_MB.get_or_init(|| {
let system = System::new_with_specifics(
RefreshKind::nothing().with_memory(MemoryRefreshKind::nothing().with_ram()),
);
(system.total_memory() / 1024 / 1024).min(u32::MAX as u64) as u32
})
}

#[must_use]
pub fn default_mem_max() -> u32 {
default_mem_max_for_total(total_ram_mb())
}

#[must_use]
pub fn default_mem_max_for_total(total_mb: u32) -> u32 {
match total_mb {
0..EIGHT_GB_MB => 2048,
EIGHT_GB_MB..TWELVE_GB_MB => 3072,
_ => 4096,
}
}

#[cfg(test)]
mod tests {
use super::default_mem_max_for_total;

#[test]
fn the_default_heap_ramps_with_total_ram() {
assert_eq!(default_mem_max_for_total(3987), 2048); // 4GB
assert_eq!(default_mem_max_for_total(6060), 2048); // 6GB
assert_eq!(default_mem_max_for_total(7167), 2048);
assert_eq!(default_mem_max_for_total(7168), 3072);
assert_eq!(default_mem_max_for_total(7900), 3072); // 8GB
assert_eq!(default_mem_max_for_total(11263), 3072);
assert_eq!(default_mem_max_for_total(11264), 4096);
assert_eq!(default_mem_max_for_total(11800), 4096); // 12GB
assert_eq!(default_mem_max_for_total(16290), 4096); // 16GB
assert_eq!(default_mem_max_for_total(65229), 4096); // 64GB
}

#[test]
fn a_machine_that_reports_nothing_still_gets_a_heap() {
assert_eq!(default_mem_max_for_total(0), 2048);
}
}
11 changes: 8 additions & 3 deletions packages/oneclient_core/src/game/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ pub async fn launch_cluster(
&libraries,
&classpaths,
&version_name,
profile.mem_max.unwrap_or(2048),
profile.mem_max.unwrap_or_else(oneclient_common::default_mem_max),
profile.launch_args.clone().unwrap_or_default(),
&java.os_arch,
java.major,
Expand Down Expand Up @@ -344,8 +344,13 @@ pub async fn launch_cluster(
mc_version: cluster.mc_version.clone(),
});

let recorder =
SessionRecorder::start(state, cluster_id, profile.mem_max.unwrap_or(2048), &java).await;
let recorder = SessionRecorder::start(
state,
cluster_id,
profile.mem_max.unwrap_or_else(oneclient_common::default_mem_max),
&java,
)
.await;

// Pinned to the session row so that if the launcher exits first the next
// start can tell whether the game is still playing
Expand Down
4 changes: 3 additions & 1 deletion packages/oneclient_core/src/settings/launcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub struct ViewState {
pub sort: Option<String>,
}

pub const SETTINGS_VERSION: u32 = 2;

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(default)]
pub struct LauncherSettings {
Expand Down Expand Up @@ -59,7 +61,7 @@ impl LauncherSettings {
impl Default for LauncherSettings {
fn default() -> Self {
Self {
settings_version: 1,
settings_version: SETTINGS_VERSION,
log_debug: false,
auto_update: true,
crash_reporting: true,
Expand Down
81 changes: 80 additions & 1 deletion packages/oneclient_core/src/settings/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use parking_lot::RwLock;

use oneclient_events::EventBus;
use oneclient_common::paths;
use oneclient_db::DbPool;
use crate::{LauncherError, LauncherResult};

use super::launcher::LauncherSettings;
use super::launcher::{LauncherSettings, SETTINGS_VERSION};
use oneclient_cluster::GameSettingsProfile;

#[tracing::instrument(level = "debug", skip(notify))]
Expand Down Expand Up @@ -35,6 +36,39 @@ pub async fn load_settings(notify: Option<&EventBus>) -> LauncherSettings {
}
}

const LEGACY_MEM_MAX: u32 = 4096;

#[tracing::instrument(level = "debug", skip_all)]
pub async fn migrate(pool: &DbPool, settings: &mut LauncherSettings) -> LauncherResult<()> {
if !migrate_settings(settings) {
return Ok(());
}

let mem_max = oneclient_common::default_mem_max();
if mem_max != LEGACY_MEM_MAX {
let profiles =
oneclient_db::dao::setting_profile::replace_mem_max(pool, LEGACY_MEM_MAX, mem_max)
.await?;

tracing::info!("lowered the default heap to {mem_max}MB on {profiles} cluster profiles");
}

save_settings(settings).await
}

fn migrate_settings(settings: &mut LauncherSettings) -> bool {
if settings.settings_version >= SETTINGS_VERSION {
return false;
}

if settings.global_game_settings.mem_max == Some(LEGACY_MEM_MAX) {
settings.global_game_settings.mem_max = Some(oneclient_common::default_mem_max());
}

settings.settings_version = SETTINGS_VERSION;
true
}

/// Prefer [`save_settings_and_apply`] this leaves the HTTP client on its old
/// endpoints/keys so those changes only take effect on the next launch
#[tracing::instrument(level = "debug", skip(settings))]
Expand Down Expand Up @@ -69,3 +103,48 @@ pub async fn save_global_profile(
let snapshot = settings.read().clone();
save_settings(&snapshot).await
}

#[cfg(test)]
mod tests {
use super::{GameSettingsProfile, LauncherSettings, SETTINGS_VERSION, migrate_settings};

fn v1(mem_max: Option<u32>) -> LauncherSettings {
LauncherSettings {
settings_version: 1,
global_game_settings: GameSettingsProfile {
mem_max,
..LauncherSettings::default().global_game_settings
},
..LauncherSettings::default()
}
}

#[test]
fn the_old_hardcoded_heap_becomes_the_per_machine_default() {
let mut settings = v1(Some(4096));
migrate_settings(&mut settings);

assert_eq!(
settings.global_game_settings.mem_max,
Some(oneclient_common::default_mem_max())
);
assert_eq!(settings.settings_version, SETTINGS_VERSION);
}

#[test]
fn a_heap_the_user_chose_survives() {
let mut settings = v1(Some(8192));
migrate_settings(&mut settings);

assert_eq!(settings.global_game_settings.mem_max, Some(8192));
}

#[test]
fn an_already_migrated_file_is_left_alone() {
let mut settings = v1(Some(4096));
settings.settings_version = SETTINGS_VERSION;
migrate_settings(&mut settings);

assert_eq!(settings.global_game_settings.mem_max, Some(4096));
}
}
6 changes: 5 additions & 1 deletion packages/oneclient_core/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ impl LauncherState {
packages: PackageProviderRegistry::new(),
};

let settings = store::load_settings(Some(&services.events)).await;
let mut settings = store::load_settings(Some(&services.events)).await;
if let Err(err) = store::migrate(&services.db, &mut settings).await {
tracing::error!("settings migration failed, retrying next start: {err}");
}

services
.requester
.set_config(crate::settings::net_config(&settings));
Expand Down
6 changes: 2 additions & 4 deletions packages/oneclient_core/tests/clusters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@ async fn cluster_lifecycle_with_settings_profile() {

let global = state.settings.read().global_game_settings.clone();

// Deliberately not the global default of 4096 so the assertions distinguish
// "the cluster's own profile was used" from "fell back to global and matched"
let cluster = state.clusters.create(
&global,
CreateClusterOptions::new("Test Cluster", "1.21.1", GameLoader::Fabric).mem_max(2048),
CreateClusterOptions::new("Test Cluster", "1.21.1", GameLoader::Fabric).mem_max(3072),
)
.await
.unwrap();
Expand All @@ -31,7 +29,7 @@ async fn cluster_lifecycle_with_settings_profile() {
let resolved = state.clusters.resolve_settings(&global, &cluster)
.await
.unwrap();
assert_eq!(resolved.mem_max, Some(2048));
assert_eq!(resolved.mem_max, Some(3072));

state.clusters.update_profile(cluster.id,
ProfileUpdate {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading