From 4e957374130e306f8429deafa1ecc42a6f77dc08 Mon Sep 17 00:00:00 2001 From: AngelOnFira <14791619+AngelOnFira@users.noreply.github.com> Date: Wed, 15 May 2024 17:41:32 +0000 Subject: [PATCH] chore: clippy fix pass (#790) ## Changes --- lib/api-helper/build/src/start.rs | 2 +- .../cli/src/commands/admin/cluster/mod.rs | 2 +- lib/bolt/cli/src/commands/config.rs | 6 ++-- lib/bolt/cli/src/commands/create.rs | 4 +-- lib/bolt/cli/src/commands/db/mod.rs | 2 +- lib/bolt/cli/src/commands/secret.rs | 6 ++-- lib/bolt/cli/src/commands/ssh.rs | 6 ++-- lib/bolt/cli/src/main.rs | 2 +- lib/bolt/config/src/ns.rs | 31 +++---------------- lib/bolt/config/src/service.rs | 5 +-- lib/bolt/core/src/context/project.rs | 22 ++++++------- lib/bolt/core/src/context/service.rs | 8 ++--- lib/bolt/core/src/dep/cargo/cli.rs | 4 +-- lib/bolt/core/src/dep/k8s/gen.rs | 4 +-- lib/bolt/core/src/dep/one_password/cli.rs | 2 +- lib/bolt/core/src/dep/terraform/cli.rs | 4 +-- lib/bolt/core/src/dep/terraform/gen.rs | 2 +- lib/bolt/core/src/tasks/config/generate.rs | 18 +++++------ lib/bolt/core/src/tasks/db.rs | 8 ++--- lib/bolt/core/src/tasks/gen.rs | 6 ++-- lib/bolt/core/src/tasks/infra/mod.rs | 8 ++--- lib/bolt/core/src/tasks/migrate.rs | 6 ++-- lib/bolt/core/src/tasks/ssh.rs | 16 +++++----- lib/bolt/core/src/tasks/template.rs | 16 +++++----- lib/bolt/core/src/tasks/test.rs | 26 ++++++++-------- lib/bolt/core/src/tasks/up.rs | 12 +++---- lib/bolt/core/src/utils/db_conn.rs | 4 +-- lib/bolt/core/src/utils/media_resize.rs | 4 +-- lib/bolt/core/src/utils/mod.rs | 14 ++++----- lib/bolt/core/src/utils/telemetry.rs | 6 ++-- svc/api/identity/src/route/events.rs | 16 +++++----- .../resolve-for-name-id/tests/integration.rs | 2 +- .../worker/src/workers/datacenter_update.rs | 2 +- .../src/workers/nomad_node_registered.rs | 2 +- .../src/workers/nomad_monitor_alloc_plan.rs | 2 +- .../ops/version-prepare/src/prewarm_ats.rs | 2 +- .../src/workers/lobby_create/nomad_job.rs | 8 ++--- .../mm/worker/src/workers/lobby_state_set.rs | 2 +- .../mm/worker/src/workers/player_remove.rs | 2 +- 39 files changed, 132 insertions(+), 162 deletions(-) diff --git a/lib/api-helper/build/src/start.rs b/lib/api-helper/build/src/start.rs index cf5a55e154..2dd1d77c04 100644 --- a/lib/api-helper/build/src/start.rs +++ b/lib/api-helper/build/src/start.rs @@ -1,4 +1,4 @@ -use std::{convert::Infallible, future::Future, net::SocketAddr, sync::Arc, time::Instant}; +use std::{convert::Infallible, future::Future, net::SocketAddr, time::Instant}; use hyper::{ body::HttpBody, diff --git a/lib/bolt/cli/src/commands/admin/cluster/mod.rs b/lib/bolt/cli/src/commands/admin/cluster/mod.rs index 9c0c724a3b..04f4e2c9e3 100644 --- a/lib/bolt/cli/src/commands/admin/cluster/mod.rs +++ b/lib/bolt/cli/src/commands/admin/cluster/mod.rs @@ -48,7 +48,7 @@ impl SubCommand { admin_clusters_api::admin_clusters_create( &ctx.openapi_config_cloud().await?, models::AdminClustersCreateRequest { - name_id: name_id, + name_id, owner_team_id: Some(Uuid::parse_str(&owner_team_id).unwrap()), }, ) diff --git a/lib/bolt/cli/src/commands/config.rs b/lib/bolt/cli/src/commands/config.rs index 259d116167..c862ce6234 100644 --- a/lib/bolt/cli/src/commands/config.rs +++ b/lib/bolt/cli/src/commands/config.rs @@ -66,10 +66,10 @@ impl SubCommand { match self { Self::Generate { namespace } => { let project_root = context::ProjectContextData::seek_project_root().await; - tasks::config::generate(&project_root, &namespace).await?; + tasks::config::generate(&project_root, namespace).await?; } Self::SetNamespace { namespace } => { - tasks::config::set_namespace(&namespace).await?; + tasks::config::set_namespace(namespace).await?; } Self::ServiceDependencies { svc_name, @@ -429,7 +429,7 @@ impl SubCommand { .context("failed to read namespace config")?; let local_secrets_str = fs::read_to_string(&secrets_path).await?; let secrets = - ProjectContextData::read_secrets(Some(ctx.ns()), ctx.path(), &ns_id).await; + ProjectContextData::read_secrets(Some(ctx.ns()), ctx.path(), ns_id).await; let ns_patches = json_patch::diff(&op_namespace, &namespace); if !ns_patches.is_empty() { diff --git a/lib/bolt/cli/src/commands/create.rs b/lib/bolt/cli/src/commands/create.rs index 97511da391..8ff7c32a65 100644 --- a/lib/bolt/cli/src/commands/create.rs +++ b/lib/bolt/cli/src/commands/create.rs @@ -122,12 +122,12 @@ impl SubCommand { }; assert!( - !pkg_name.contains("_"), + !pkg_name.contains('_'), "package name should not contain underscores, use dashes" ); assert!( - !service_name.contains("_"), + !service_name.contains('_'), "service name should not contain underscores, use dashes" ); diff --git a/lib/bolt/cli/src/commands/db/mod.rs b/lib/bolt/cli/src/commands/db/mod.rs index 4c137a2fd0..1bb7397e7b 100644 --- a/lib/bolt/cli/src/commands/db/mod.rs +++ b/lib/bolt/cli/src/commands/db/mod.rs @@ -27,7 +27,7 @@ impl SubCommand { tasks::db::shell( &ctx, &ctx.service_with_name(&service).await, - query.as_ref().map(String::as_str), + query.as_deref(), ) .await?; diff --git a/lib/bolt/cli/src/commands/secret.rs b/lib/bolt/cli/src/commands/secret.rs index a517a48b32..6d40fd10f5 100644 --- a/lib/bolt/cli/src/commands/secret.rs +++ b/lib/bolt/cli/src/commands/secret.rs @@ -34,7 +34,7 @@ impl SubCommand { optional, format, } => { - let path = path.split("/").collect::>(); + let path = path.split('/').collect::>(); // Fetch value let value = if optional { @@ -49,14 +49,14 @@ impl SubCommand { if let Some(value) = value { println!("{value}") } else { - println!("") + println!() } } Some(Format::Json) => println!("{}", json!({ "value": value })), } } Self::Set { path, value } => { - let path = path.split("/").collect::>(); + let path = path.split('/').collect::>(); let mut generator = ConfigGenerator::new(ctx.path(), ctx.ns_id()).await?; generator.set_secret(&path, toml_edit::value(value)).await?; diff --git a/lib/bolt/cli/src/commands/ssh.rs b/lib/bolt/cli/src/commands/ssh.rs index df894d799d..3c2d57796e 100644 --- a/lib/bolt/cli/src/commands/ssh.rs +++ b/lib/bolt/cli/src/commands/ssh.rs @@ -48,12 +48,12 @@ impl SubCommand { &ctx, &ip, &ssh_key, - command.as_ref().map(String::as_str), + command.as_deref(), ) .await?; } Self::Id { server_id, command } => { - bolt_core::tasks::ssh::id(&ctx, &server_id, command.as_ref().map(String::as_str)) + bolt_core::tasks::ssh::id(&ctx, &server_id, command.as_deref()) .await?; } Self::Pool { pool, command, all } => { @@ -61,7 +61,7 @@ impl SubCommand { let command = command.context("must provide command with --all")?; bolt_core::tasks::ssh::pool_all(&ctx, &pool, &command).await?; } else { - bolt_core::tasks::ssh::pool(&ctx, &pool, command.as_ref().map(String::as_str)) + bolt_core::tasks::ssh::pool(&ctx, &pool, command.as_deref()) .await?; } } diff --git a/lib/bolt/cli/src/main.rs b/lib/bolt/cli/src/main.rs index 21f58fd51c..f01ab50ab8 100644 --- a/lib/bolt/cli/src/main.rs +++ b/lib/bolt/cli/src/main.rs @@ -151,7 +151,7 @@ async fn prompt_prod(ctx: &bolt_core::context::ProjectContextData) -> Result<()> .await?; if response { - return Ok(()); + Ok(()) } else { bail!("Bailing"); } diff --git a/lib/bolt/config/src/ns.rs b/lib/bolt/config/src/ns.rs index 8bd950e98a..ec46fe57da 100644 --- a/lib/bolt/config/src/ns.rs +++ b/lib/bolt/config/src/ns.rs @@ -319,20 +319,12 @@ impl Default for Docker { } } -#[derive(Serialize, Deserialize, Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug, Default)] #[serde(deny_unknown_fields)] pub struct Nomad { pub health_checks: Option, } -impl Default for Nomad { - fn default() -> Self { - Self { - health_checks: None, - } - } -} - #[derive(Serialize, Deserialize, Clone, Debug, Default)] #[serde(deny_unknown_fields)] pub struct Kubernetes { @@ -570,7 +562,7 @@ pub struct RivetTest { pub load_tests: bool, } -#[derive(Serialize, Deserialize, Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug, Default)] #[serde(deny_unknown_fields)] pub struct Api { #[serde(default)] @@ -582,16 +574,6 @@ pub struct Api { pub hub_origin_regex: Option, } -impl Default for Api { - fn default() -> Self { - Self { - error_verbose: false, - hub_origin: None, - hub_origin_regex: None, - } - } -} - #[derive(Serialize, Deserialize, Clone, Debug, Default)] #[serde(deny_unknown_fields)] pub struct Profanity { @@ -627,20 +609,15 @@ pub struct Provisioning { pub acme_directory: ProvisioningAcmeDirectory, } -#[derive(Serialize, Deserialize, Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug, Default)] pub enum ProvisioningAcmeDirectory { #[serde(rename = "lets_encrypt")] + #[default] LetsEncrypt, #[serde(rename = "lets_encrypt_staging")] LetsEncryptStaging, } -impl Default for ProvisioningAcmeDirectory { - fn default() -> Self { - ProvisioningAcmeDirectory::LetsEncryptStaging - } -} - #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct ProvisioningCluster { diff --git a/lib/bolt/config/src/service.rs b/lib/bolt/config/src/service.rs index 32bdfffe3f..f852a43f83 100644 --- a/lib/bolt/config/src/service.rs +++ b/lib/bolt/config/src/service.rs @@ -343,10 +343,7 @@ impl ServiceKind { /// because this will be true for any services that are internally-facing HTTP servers, such as /// `api-job`. pub fn has_server(&self) -> bool { - match self { - ServiceKind::Api { .. } | ServiceKind::Static { .. } => true, - _ => false, - } + matches!(self, ServiceKind::Api { .. } | ServiceKind::Static { .. }) } pub fn short(&self) -> &str { diff --git a/lib/bolt/core/src/context/project.rs b/lib/bolt/core/src/context/project.rs index 51a6580bce..5852ba4b9e 100644 --- a/lib/bolt/core/src/context/project.rs +++ b/lib/bolt/core/src/context/project.rs @@ -60,7 +60,7 @@ impl ProjectContextData { reader: impl FnOnce(&config::cache::Cache) -> T + Sized, ) -> T { let cache = self.cache.lock().await; - reader(&*cache) + reader(&cache) } pub async fn cache_mut( @@ -69,7 +69,7 @@ impl ProjectContextData { ) -> T { let res = { let mut cache = self.cache.lock().await; - reader(&mut *cache) + reader(&mut cache) }; self.write_cache().await; @@ -368,7 +368,7 @@ impl ProjectContextData { // Load the service let svc_ctx = context::service::ServiceContextData::from_path( Weak::new(), - &svc_ctxs_map, + svc_ctxs_map, &workspace_path, &worker_path, ) @@ -415,7 +415,7 @@ impl ProjectContextData { // Load the service let svc_ctx = context::service::ServiceContextData::from_path( Weak::new(), - &svc_ctxs_map, + svc_ctxs_map, workspace_path, &entry.path(), ) @@ -461,10 +461,9 @@ impl ProjectContextData { let path = project_path .join("namespaces") .join(format!("{ns_id}.toml")); - let config_str = fs::read_to_string(&path).await.expect(&format!( - "failed to read namespace config: {}", - path.display() - )); + let config_str = fs::read_to_string(&path) + .await + .unwrap_or_else(|_| panic!("failed to read namespace config: {}", path.display())); let config = match toml::from_str::(&config_str) { Result::Ok(x) => x, Result::Err(err) => { @@ -497,8 +496,7 @@ impl ProjectContextData { project_path: &Path, ns_id: &str, ) -> serde_json::Value { - let secrets_path = ProjectContextData::get_secrets_path(ns, project_path, &ns_id); - + let secrets_path = ProjectContextData::get_secrets_path(ns, project_path, ns_id); // Read the config let config_str = fs::read_to_string(&secrets_path) .await @@ -546,7 +544,7 @@ impl ProjectContextData { name: &str, ) -> context::service::ServiceContext { if let Some(ctx) = self.svc_ctxs_map.get(name) { - return ctx.clone(); + ctx.clone() } else { panic!("Could not find service with name {}", name); } @@ -792,7 +790,7 @@ impl ProjectContextData { .clone() .unwrap_or_else(|| { // Create regex pattern from the default hub origin - format!("^{}$", self.origin_hub().replace(".", "\\.")) + format!("^{}$", self.origin_hub().replace('.', "\\.")) }) } diff --git a/lib/bolt/core/src/context/service.rs b/lib/bolt/core/src/context/service.rs index 7e0b748f33..7648a41cfc 100644 --- a/lib/bolt/core/src/context/service.rs +++ b/lib/bolt/core/src/context/service.rs @@ -725,7 +725,7 @@ impl ServiceContextData { // Aggregate secrets from all dependencies .flat_map(|x| x.config().secrets.clone().into_iter()) // Convert keys to string array - .map(|(k, v)| (k.split("/").map(|x| x.to_string()).collect::>(), v)) + .map(|(k, v)| (k.split('/').map(|x| x.to_string()).collect::>(), v)) // Dedupe .collect::>() .into_iter() @@ -1025,13 +1025,13 @@ impl ServiceContextData { if self.depends_on_provision_margin() { env.insert( - format!("RIVET_JOB_SERVER_PROVISION_MARGIN"), + "RIVET_JOB_SERVER_PROVISION_MARGIN".to_string(), provisioning.job_server_provision_margin.to_string(), ); } env.insert( - format!("TLS_ACME_DIRECTORY"), + "TLS_ACME_DIRECTORY".to_string(), serde_json::to_value(&provisioning.acme_directory)? .as_str() .unwrap() @@ -1180,7 +1180,7 @@ impl ServiceContextData { }; env.insert( - format!("REDIS_URL_{}", db_name.to_uppercase().replace("-", "_")), + format!("REDIS_URL_{}", db_name.to_uppercase().replace('-', "_")), url, ); } diff --git a/lib/bolt/core/src/dep/cargo/cli.rs b/lib/bolt/core/src/dep/cargo/cli.rs index e64bd16147..9fd1864d3a 100644 --- a/lib/bolt/core/src/dep/cargo/cli.rs +++ b/lib/bolt/core/src/dep/cargo/cli.rs @@ -325,10 +325,10 @@ pub async fn build_tests<'a, T: AsRef>( let package = v["package_id"] .as_str() .context("missing package_id")? - .split_once("#") + .split_once('#') .context("split_once failed")? .1 - .split_once("@") + .split_once('@') .context("split_once failed")? .0; diff --git a/lib/bolt/core/src/dep/k8s/gen.rs b/lib/bolt/core/src/dep/k8s/gen.rs index 6aab85ac47..1b5e9a92e9 100644 --- a/lib/bolt/core/src/dep/k8s/gen.rs +++ b/lib/bolt/core/src/dep/k8s/gen.rs @@ -857,7 +857,7 @@ fn build_ingress_router( } // Build paths for rule - rule.push_str("("); + rule.push('('); rule.push_str( &mount .paths @@ -866,7 +866,7 @@ fn build_ingress_router( .collect::>() .join(" || "), ); - rule.push_str(")"); + rule.push(')'); if let Some(strip_prefix) = &mount.strip_prefix { let mw_name = format!("{}-{i}-strip-prefix", svc_ctx.name()); diff --git a/lib/bolt/core/src/dep/one_password/cli.rs b/lib/bolt/core/src/dep/one_password/cli.rs index 23ec82ac2e..c6337a57f0 100644 --- a/lib/bolt/core/src/dep/one_password/cli.rs +++ b/lib/bolt/core/src/dep/one_password/cli.rs @@ -64,7 +64,7 @@ pub async fn write(service_token: Option<&str>, op_path: &str, tmp_path: &Path, let field_json = fields_json .iter_mut() .find(|f| f["label"] == field) - .expect(&format!("could not find field {field} in {item}")); + .unwrap_or_else(|| panic!("could not find field {field} in {item}")); field_json["value"] = content.into(); // Save to file diff --git a/lib/bolt/core/src/dep/terraform/cli.rs b/lib/bolt/core/src/dep/terraform/cli.rs index 2426e9e305..84570762ae 100644 --- a/lib/bolt/core/src/dep/terraform/cli.rs +++ b/lib/bolt/core/src/dep/terraform/cli.rs @@ -13,7 +13,7 @@ lazy_static! { /// Builds the workspace name that's used for the specific plan. This lets us /// store multiple workspaces on the same backend. pub fn build_localized_workspace_name(ns: &str, plan: &str) -> String { - format!("{}-{}", ns.replace("_", "-"), plan.replace("_", "-")) + format!("{}-{}", ns.replace('_', "-"), plan.replace('_', "-")) } pub async fn build_command(ctx: &ProjectContext, plan_id: &str) -> Command { @@ -120,7 +120,7 @@ pub async fn destroy(ctx: &ProjectContext, plan_id: &str, varfile_path: &Path) - event.insert_prop("plan_id", plan_id)?; utils::telemetry::capture_event(ctx, event).await?; - let mut cmd = build_command(&ctx, plan_id).await; + let mut cmd = build_command(ctx, plan_id).await; cmd.arg("destroy") .arg(format!("-var-file={}", varfile_path.display())); cmd.exec().await?; diff --git a/lib/bolt/core/src/dep/terraform/gen.rs b/lib/bolt/core/src/dep/terraform/gen.rs index 72cc02aeb1..e72c6fa014 100644 --- a/lib/bolt/core/src/dep/terraform/gen.rs +++ b/lib/bolt/core/src/dep/terraform/gen.rs @@ -105,7 +105,7 @@ fn gen_remote_state( let plan_id = &remote_state.plan_id; let data_name = remote_state.data_name(); let workspace = - dep::terraform::cli::build_localized_workspace_name(ctx.ns_id(), &remote_state.plan_id); + dep::terraform::cli::build_localized_workspace_name(ctx.ns_id(), remote_state.plan_id); let meta = if let Some(condition) = &remote_state.condition { format!("count = {condition} ? 1 : 0") diff --git a/lib/bolt/core/src/tasks/config/generate.rs b/lib/bolt/core/src/tasks/config/generate.rs index ceda4a4eca..2125ac3017 100644 --- a/lib/bolt/core/src/tasks/config/generate.rs +++ b/lib/bolt/core/src/tasks/config/generate.rs @@ -133,12 +133,12 @@ impl ConfigGenerator { /// Generates a new config & secrets based on user input. pub async fn generate(project_path: &Path, ns_id: &str) -> Result<()> { - let mut generator = ConfigGenerator::new(&project_path, ns_id).await?; + let mut generator = ConfigGenerator::new(project_path, ns_id).await?; // MARK: Cluster generator .generate_config(&["cluster", "id"], || async { - Ok(value(Uuid::new_v4().to_string()).into()) + Ok(value(Uuid::new_v4().to_string())) }) .await?; @@ -157,19 +157,19 @@ pub async fn generate(project_path: &Path, ns_id: &str) -> Result<()> { { generator .generate_config(&["cluster", "id"], || async { - Ok(value(Uuid::new_v4().to_string()).into()) + Ok(value(Uuid::new_v4().to_string())) }) .await?; generator .generate_config(&["cluster", "single_node", "public_ip"], || async { - Ok(value("127.0.0.1").into()) + Ok(value("127.0.0.1")) }) .await?; // Default to port 8080 since default port 80 is not suitable for most dev environments generator .generate_config(&["cluster", "single_node", "api_http_port"], || async { - Ok(value(8080).into()) + Ok(value(8080)) }) .await?; } @@ -330,7 +330,7 @@ pub async fn generate(project_path: &Path, ns_id: &str) -> Result<()> { eprintln!(); rivet_term::status::success( "Generated config", - &format!("namespaces/{ns_id}.toml & secrets/{ns_id}.toml"), + format!("namespaces/{ns_id}.toml & secrets/{ns_id}.toml"), ); Ok(()) @@ -476,9 +476,9 @@ fn generate_clickhouse_password(length: usize) -> String { let mut password: Vec = (0..length - 3) .map(|_| rng.sample(Alphanumeric) as char) .collect(); - password.push(rng.gen_range('A'..'Z')); - password.push(rng.gen_range('a'..'z')); - password.push(rng.gen_range('0'..'9')); + password.push(rng.gen_range('A'..='Z')); + password.push(rng.gen_range('a'..='z')); + password.push(rng.gen_range('0'..='9')); password.push(special_chars.chars().choose(&mut rng).unwrap()); password.shuffle(&mut rng); password.into_iter().collect() diff --git a/lib/bolt/core/src/tasks/db.rs b/lib/bolt/core/src/tasks/db.rs index 6aa443e61a..6fc2248d88 100644 --- a/lib/bolt/core/src/tasks/db.rs +++ b/lib/bolt/core/src/tasks/db.rs @@ -46,7 +46,7 @@ pub async fn shell(ctx: &ProjectContext, svc: &ServiceContext, query: Option<&st RuntimeKind::Redis { .. } => redis_shell(shell_ctx).await?, RuntimeKind::CRDB { .. } => crdb_shell(shell_ctx).await?, RuntimeKind::ClickHouse { .. } => clickhouse_shell(shell_ctx, false).await?, - x @ _ => bail!("cannot migrate this type of service: {x:?}"), + x => bail!("cannot migrate this type of service: {x:?}"), } Ok(()) @@ -74,7 +74,7 @@ async fn redis_shell(shell_ctx: ShellContext<'_>) -> Result<()> { unreachable!(); }; let host = conn.redis_hosts.get(&svc.name()).unwrap(); - let (hostname, port) = host.split_once(":").unwrap(); + let (hostname, port) = host.split_once(':').unwrap(); // Read auth secrets let (username, password) = match ctx.ns().redis.provider { @@ -99,7 +99,7 @@ async fn redis_shell(shell_ctx: ShellContext<'_>) -> Result<()> { ); if let LogType::Default = log_type { - rivet_term::status::progress("Connecting to Redis", &db_name); + rivet_term::status::progress("Connecting to Redis", db_name); } if query.is_some() { @@ -343,7 +343,7 @@ pub async fn clickhouse_shell(shell_ctx: ShellContext<'_>, no_db: bool) -> Resul .read_secret(&["clickhouse", "users", "default", "password"]) .await?; let host = conn.clickhouse_host.as_ref().unwrap(); - let (hostname, port) = host.split_once(":").unwrap(); + let (hostname, port) = host.split_once(':').unwrap(); let db_flag = if no_db { "".to_string() diff --git a/lib/bolt/core/src/tasks/gen.rs b/lib/bolt/core/src/tasks/gen.rs index 055e08b62f..cf17ec311a 100644 --- a/lib/bolt/core/src/tasks/gen.rs +++ b/lib/bolt/core/src/tasks/gen.rs @@ -185,7 +185,7 @@ async fn generate_root(path: &Path) { update_libs(&path.join("lib")).await; } -fn update_libs<'a>(lib_path: &'a Path) -> BoxFuture<'a, ()> { +fn update_libs(lib_path: &Path) -> BoxFuture<'_, ()> { async move { let mut lib_dir = fs::read_dir(lib_path).await.unwrap(); while let Some(entry) = lib_dir.next_entry().await.unwrap() { @@ -212,7 +212,7 @@ fn update_libs<'a>(lib_path: &'a Path) -> BoxFuture<'a, ()> { async fn set_license(path: &Path) { let toml = fs::read_to_string(path) .await - .expect(&format!("could not read path: {}", path.display())); + .unwrap_or_else(|_| panic!("could not read path: {}", path.display())); let mut doc = toml.parse::().unwrap(); let mut array = toml_edit::Array::new(); @@ -228,7 +228,7 @@ pub async fn generate_all_services(ctx: &ProjectContext) { // println!("\n> Generating all services"); for svc_ctx in ctx.all_services().await { - generate_service(&svc_ctx).await; + generate_service(svc_ctx).await; } } diff --git a/lib/bolt/core/src/tasks/infra/mod.rs b/lib/bolt/core/src/tasks/infra/mod.rs index d18799e9ed..fed447061f 100644 --- a/lib/bolt/core/src/tasks/infra/mod.rs +++ b/lib/bolt/core/src/tasks/infra/mod.rs @@ -53,7 +53,7 @@ impl PlanStepKind { } cmd.exec().await?; - terraform::output::clear_cache(&ctx, &plan_id).await; + terraform::output::clear_cache(&ctx, plan_id).await; } PlanStepKind::Migrate => { tasks::migrate::up_all(&ctx).await?; @@ -85,7 +85,7 @@ impl PlanStepKind { } cmd.exec().await?; - terraform::output::clear_cache(&ctx, &plan_id).await; + terraform::output::clear_cache(&ctx, plan_id).await; } PlanStepKind::Migrate | PlanStepKind::Up => { // Do nothing @@ -371,7 +371,7 @@ pub async fn execute_plan( plan: &[PlanStep], opts: ExecutePlanOpts, ) -> Result<()> { - tasks::gen::generate_project(&ctx, false).await; + tasks::gen::generate_project(ctx, false).await; for (i, step) in plan.iter().enumerate() { eprintln!(); @@ -397,7 +397,7 @@ pub async fn destroy_plan( plan: &[PlanStep], opts: ExecutePlanOpts, ) -> Result<()> { - tasks::gen::generate_project(&ctx, false).await; + tasks::gen::generate_project(ctx, false).await; for (i, step) in plan.iter().enumerate().rev() { eprintln!(); diff --git a/lib/bolt/core/src/tasks/migrate.rs b/lib/bolt/core/src/tasks/migrate.rs index 72547534fe..f430628a56 100644 --- a/lib/bolt/core/src/tasks/migrate.rs +++ b/lib/bolt/core/src/tasks/migrate.rs @@ -46,7 +46,7 @@ pub async fn create( let db_ext = match &service.config().runtime { RuntimeKind::CRDB { .. } => "sql", RuntimeKind::ClickHouse { .. } => "sql", - x @ _ => bail!("cannot migrate this type of service: {x:?}"), + x => bail!("cannot migrate this type of service: {x:?}"), }; block_in_place(|| { @@ -385,7 +385,7 @@ pub async fn up(ctx: &ProjectContext, services: &[ServiceContext]) -> Result<()> query: Some(query), }); } - x @ _ => bail!("cannot migrate this type of service: {x:?}"), + x => bail!("cannot migrate this type of service: {x:?}"), } } @@ -673,7 +673,7 @@ async fn upload_migrations(ctx: &ProjectContext, svc: &ServiceContext) -> Result }))?; let mut cmd = tokio::process::Command::new("kubectl"); - cmd.args(&["apply", "-f", "-"]); + cmd.args(["apply", "-f", "-"]); cmd.env("KUBECONFIG", ctx.gen_kubeconfig_path()); cmd.stdin(std::process::Stdio::piped()); cmd.stdout(std::process::Stdio::null()); diff --git a/lib/bolt/core/src/tasks/ssh.rs b/lib/bolt/core/src/tasks/ssh.rs index 0f07bc56f2..a9680d28d1 100644 --- a/lib/bolt/core/src/tasks/ssh.rs +++ b/lib/bolt/core/src/tasks/ssh.rs @@ -55,33 +55,33 @@ pub async fn ip( } pub async fn id(ctx: &ProjectContext, server_id: &str, command: Option<&str>) -> Result<()> { - let server_ips = tasks::api::get_cluster_server_ips(&ctx, Some(server_id), None).await?; + let server_ips = tasks::api::get_cluster_server_ips(ctx, Some(server_id), None).await?; let server_ip = server_ips .first() .context(format!("failed to find server with server id {server_id}"))?; // TODO: Choose correct SSH key - let ssh_key = TempSshKey::new(&ctx, "server").await?; - ip(ctx, &server_ip, &ssh_key, command).await?; + let ssh_key = TempSshKey::new(ctx, "server").await?; + ip(ctx, server_ip, &ssh_key, command).await?; Ok(()) } pub async fn pool(ctx: &ProjectContext, pool: &str, command: Option<&str>) -> Result<()> { - let server_ips = tasks::api::get_cluster_server_ips(&ctx, None, Some(pool)).await?; + let server_ips = tasks::api::get_cluster_server_ips(ctx, None, Some(pool)).await?; let server_ip = server_ips .first() .context(format!("failed to find server with pool {pool}"))?; - let ssh_key = TempSshKey::new(&ctx, "server").await?; - ip(ctx, &server_ip, &ssh_key, command).await?; + let ssh_key = TempSshKey::new(ctx, "server").await?; + ip(ctx, server_ip, &ssh_key, command).await?; Ok(()) } pub async fn pool_all(ctx: &ProjectContext, pool: &str, command: &str) -> Result<()> { - let server_ips = tasks::api::get_cluster_server_ips(&ctx, None, Some(pool)).await?; - let ssh_key = Arc::new(TempSshKey::new(&ctx, "server").await?); + let server_ips = tasks::api::get_cluster_server_ips(ctx, None, Some(pool)).await?; + let ssh_key = Arc::new(TempSshKey::new(ctx, "server").await?); futures_util::stream::iter(server_ips) .map(|server_ip| { diff --git a/lib/bolt/core/src/tasks/template.rs b/lib/bolt/core/src/tasks/template.rs index b8d500a870..b2676ff036 100644 --- a/lib/bolt/core/src/tasks/template.rs +++ b/lib/bolt/core/src/tasks/template.rs @@ -255,7 +255,7 @@ pub async fn generate(ctx: &mut ProjectContext, opts: TemplateOpts) -> Result<() } }; - eprintln!(""); + eprintln!(); rivet_term::status::success("Done", ""); Ok(()) @@ -268,7 +268,7 @@ async fn generate_worker_partial( output_path: PathBuf, service_name: String, ) -> Result<()> { - let snake_name = service_name.replace("-", "_"); + let snake_name = service_name.replace('-', "_"); // Create directories let workers_root = output_path.join("src").join("workers"); @@ -289,7 +289,7 @@ async fn generate_worker_partial( generate_file( hb, - &render_data, + render_data, input_path .join("src") .join("workers") @@ -299,7 +299,7 @@ async fn generate_worker_partial( .await?; generate_file( hb, - &render_data, + render_data, input_path.join("tests").join("{{ snake name }}.rs"), tests_root, ) @@ -311,7 +311,7 @@ async fn generate_worker_partial( rivet_term::status::progress("Editing", worker_mod_path.display()); let worker_mod_str = fs::read_to_string(&worker_mod_path).await?; - let Some(bracket_idx) = worker_mod_str.find("[") else { + let Some(bracket_idx) = worker_mod_str.find('[') else { bail!("malformed mod.rs file"); }; @@ -356,7 +356,7 @@ async fn generate_dir( while let Some(entry) = entries.next_entry().await? { let metadata = entry.metadata().await?; if metadata.is_file() { - generate_file(hb, &render_data, entry.path(), output_path.clone()).await?; + generate_file(hb, render_data, entry.path(), output_path.clone()).await?; } else if metadata.is_dir() { // Recursively generate next directory generate_dir( @@ -424,7 +424,7 @@ mod handlebars_helpers { .value() .as_str() .ok_or_else(|| RenderError::new("Could not convert value to string"))? - .replace("-", "_"); + .replace('-', "_"); out.write(value.as_str())?; Ok(()) } @@ -441,7 +441,7 @@ mod handlebars_helpers { .value() .as_str() .ok_or_else(|| RenderError::new("Could not convert value to string"))? - .replace("-", "_") + .replace('-', "_") .to_uppercase(); out.write(value.as_str())?; Ok(()) diff --git a/lib/bolt/core/src/tasks/test.rs b/lib/bolt/core/src/tasks/test.rs index 08993a69dd..7d6b96cc98 100644 --- a/lib/bolt/core/src/tasks/test.rs +++ b/lib/bolt/core/src/tasks/test.rs @@ -183,7 +183,7 @@ pub async fn test_services>( rivet_term::status::progress("Waiting for pod start", ""); let label = format!("app.kubernetes.io/name={k8s_svc_name}"); let status = Command::new("kubectl") - .args(&[ + .args([ "wait", "--for=condition=Ready", "pod", @@ -203,7 +203,7 @@ pub async fn test_services>( // Install CA rivet_term::status::progress("Installing CA", ""); let status = Command::new("kubectl") - .args(&[ + .args([ "exec", &format!("job/{k8s_svc_name}"), "-n", @@ -254,7 +254,7 @@ pub async fn test_services>( // Delete job Command::new("kubectl") - .args(&["delete", "job", &k8s_svc_name, "-n", "rivet-service"]) + .args(["delete", "job", &k8s_svc_name, "-n", "rivet-service"]) .env("KUBECONFIG", ctx.gen_kubeconfig_path()) .output() .await?; @@ -366,10 +366,10 @@ async fn run_test( rivet_term::status::error("Timeout", &run_info); } TestStatus::UnknownExitCode(code) => { - rivet_term::status::error(&format!("Unknown exit code {}", code), &run_info); + rivet_term::status::error(format!("Unknown exit code {}", code), &run_info); } TestStatus::UnknownError(err) => { - rivet_term::status::error(&format!("Unknown error: {}", err), &run_info); + rivet_term::status::error(format!("Unknown error: {}", err), &run_info); } } @@ -403,7 +403,7 @@ async fn exec_test( // Write logs to file let file = tokio::task::block_in_place(|| std::fs::File::create(&logs_path))?; let mut logs_child = Command::new("kubectl") - .args(&[ + .args([ "exec", &format!("job/{k8s_svc_name}"), "-n", @@ -595,7 +595,7 @@ async fn cleanup_servers(ctx: &ProjectContext) -> Result<()> { async { // Fetch all ssh keys with "test-" in their label and are in this namespace let res = client - .get(format!("https://api.linode.com/v4/profile/sshkeys")) + .get("https://api.linode.com/v4/profile/sshkeys".to_string()) .header( "X-Filter", format!(r#"{{ "label": {{ "+contains": "{test_tag}-{ns}-" }} }}"#), @@ -727,7 +727,7 @@ async fn cleanup_nomad_test(ctx: &ProjectContext, test_id: &str, purge: bool) -> ); let mut cmd = Command::new("kubectl"); - cmd.args(&[ + cmd.args([ "exec", "service/nomad-server", "-n", @@ -755,7 +755,7 @@ async fn cleanup_nomad_test(ctx: &ProjectContext, test_id: &str, purge: bool) -> .join("\n"); let mut cmd = Command::new("kubectl"); - cmd.args(&[ + cmd.args([ "exec", "service/nomad-server", "-n", @@ -791,7 +791,7 @@ async fn cleanup_nomad(ctx: &ProjectContext, purge: bool) -> Result<()> { ); let mut cmd = Command::new("kubectl"); - cmd.args(&[ + cmd.args([ "exec", "service/nomad-server", "-n", @@ -831,8 +831,8 @@ pub async fn gen_spec( let mut secret_env = IndexMap::new(); for svc_ctx in svcs { - env.extend(svc_ctx.env(&run_context).await.unwrap()); - secret_env.extend(svc_ctx.secret_env(&run_context).await.unwrap()); + env.extend(svc_ctx.env(run_context).await.unwrap()); + secret_env.extend(svc_ctx.secret_env(run_context).await.unwrap()); } let env = dep::k8s::gen::generate_k8s_variables() @@ -859,7 +859,7 @@ pub async fn gen_spec( "data": secret_data })); - let (volumes, volume_mounts) = build_volumes(&ctx, run_context, svcs).await; + let (volumes, volume_mounts) = build_volumes(ctx, run_context, svcs).await; let metadata = json!({ "name": k8s_svc_name, diff --git a/lib/bolt/core/src/tasks/up.rs b/lib/bolt/core/src/tasks/up.rs index 66ef315b6c..ea2c52b321 100644 --- a/lib/bolt/core/src/tasks/up.rs +++ b/lib/bolt/core/src/tasks/up.rs @@ -68,7 +68,7 @@ pub async fn up_services>( }; // Find all matching services - let all_svcs = ctx.services_with_patterns(&svc_names).await; + let all_svcs = ctx.services_with_patterns(svc_names).await; ensure!(!all_svcs.is_empty(), "input matched no services"); // Find all services that are executables @@ -203,7 +203,7 @@ pub async fn up_services>( .iter() .map(|(workspace_path, svc_names)| cargo::cli::BuildCall { path: workspace_path.strip_prefix(ctx.path()).unwrap(), - bins: &svc_names, + bins: svc_names, }) .collect::>(), release: ctx.build_optimization() == BuildOptimization::Release, @@ -226,7 +226,7 @@ pub async fn up_services>( match &ctx.ns().cluster.kind { config::ns::ClusterKind::SingleNode { .. } => {} config::ns::ClusterKind::Distributed { .. } => { - if let Some((repo, _)) = ctx.ns().docker.repository.split_once("/") { + if let Some((repo, _)) = ctx.ns().docker.repository.split_once('/') { let username = ctx .read_secret(&["docker", "registry", repo, "write", "username"]) .await?; @@ -301,7 +301,7 @@ pub async fn up_services>( } if skip_deploy { - return Ok(all_svcs.iter().cloned().collect()); + return Ok(all_svcs.to_vec()); } // Generate Kubernetes deployments @@ -321,7 +321,7 @@ pub async fn up_services>( pb.set_message(exec_ctx.svc_ctx.name()); // Save specs - specs.extend(dep::k8s::gen::gen_svc(&exec_ctx).await); + specs.extend(dep::k8s::gen::gen_svc(exec_ctx).await); pb.inc(1); } @@ -337,7 +337,7 @@ pub async fn up_services>( rivet_term::status::success("Finished", ""); // Return all deployed services. - Ok(all_svcs.iter().cloned().collect()) + Ok(all_svcs.to_vec()) } async fn upload_svc_build(svc_ctx: ServiceContext, upload_semaphore: Arc) -> Result<()> { diff --git a/lib/bolt/core/src/utils/db_conn.rs b/lib/bolt/core/src/utils/db_conn.rs index 4040ee011f..8c265b9ea4 100644 --- a/lib/bolt/core/src/utils/db_conn.rs +++ b/lib/bolt/core/src/utils/db_conn.rs @@ -193,9 +193,7 @@ impl DatabaseConnections { .await?; let host = self.clickhouse_host.as_ref().unwrap(); - let query_other = format!( - "&x-multi-statement=true&x-migrations-table-engine=ReplicatedMergeTree&secure=true&skip_verify=true", - ); + let query_other = "&x-multi-statement=true&x-migrations-table-engine=ReplicatedMergeTree&secure=true&skip_verify=true".to_string(); Ok(format!( "clickhouse://{}/?database={}&username={}&password={}{}", diff --git a/lib/bolt/core/src/utils/media_resize.rs b/lib/bolt/core/src/utils/media_resize.rs index 4d712ea447..86c57147f4 100644 --- a/lib/bolt/core/src/utils/media_resize.rs +++ b/lib/bolt/core/src/utils/media_resize.rs @@ -18,7 +18,7 @@ pub struct ResizePreset { impl ResizePreset { fn key(&self) -> String { let name = &self.name; - let path = self.file_path.replace("/", "-").replace(".", "-"); + let path = self.file_path.replace('/', "-").replace('.', "-"); if self.fallback { format!("{name}-{path}-fallback") } else { @@ -94,7 +94,7 @@ impl ResizePreset { if !filters.is_empty() { url.push_str(&format!("/filters:{}", filters.join(":"))); } - url.push_str("/"); + url.push('/'); url.push_str(&urlencoding::encode(&format!( "http://traffic-server.traffic-server.svc.cluster.local:8080/s3-cache/{ns}-{bucket}/", ns = self.ns, diff --git a/lib/bolt/core/src/utils/mod.rs b/lib/bolt/core/src/utils/mod.rs index 0eea3adfee..0582575afa 100644 --- a/lib/bolt/core/src/utils/mod.rs +++ b/lib/bolt/core/src/utils/mod.rs @@ -43,7 +43,7 @@ pub async fn join_set_progress(mut join_set: tokio::task::JoinSet>) - // Log all errors for err in &errors { - rivet_term::status::error("Error", &err); + rivet_term::status::error("Error", err); } // Return error @@ -71,14 +71,14 @@ impl MultiProgress { pub async fn insert(&self, name: &str) { let mut running = self.running.lock().await; running.push(name.to_owned()); - self.update(&*running); + self.update(&running); } pub async fn remove(&self, name: &str) { let mut running = self.running.lock().await; running.retain(|n| n != name); self.progress_bar.inc(1); - self.update(&*running); + self.update(&running); } pub fn finish(&self) { @@ -105,7 +105,7 @@ fn deep_modified_ts_inner(path: &Path, max_modified_ts: &mut u128) -> Result<()> let file_type = entry.file_type()?; // Skip non-source files - if file_name.starts_with(".") + if file_name.starts_with('.') || file_name == "node_modules" || file_name == "target" || file_name == "dist" @@ -297,7 +297,7 @@ pub fn render_diff(indent: usize, patches: &json_patch::Patch) { eprintln!( "{}{}{} {}", " ".repeat(indent), - op.path.replace("/", "."), + op.path.replace('/', "."), style(":").dim(), style("added").green().bold() ); @@ -306,7 +306,7 @@ pub fn render_diff(indent: usize, patches: &json_patch::Patch) { eprintln!( "{}{}{} {}", " ".repeat(indent), - op.path.replace("/", "."), + op.path.replace('/', "."), style(":").dim(), style("removed").red().bold() ); @@ -315,7 +315,7 @@ pub fn render_diff(indent: usize, patches: &json_patch::Patch) { eprintln!( "{}{}{} {}", " ".repeat(indent), - op.path.replace("/", "."), + op.path.replace('/', "."), style(":").dim(), style("changed").yellow().bold() ); diff --git a/lib/bolt/core/src/utils/telemetry.rs b/lib/bolt/core/src/utils/telemetry.rs index b34ef167e2..1233a60e26 100644 --- a/lib/bolt/core/src/utils/telemetry.rs +++ b/lib/bolt/core/src/utils/telemetry.rs @@ -63,7 +63,7 @@ pub async fn build_event(ctx: &ProjectContext, name: &str) -> Result Result>>()?; // Generate the command to download and decompress the file - let mut download_cmd = format!(r#"curl -Lf "$NOMAD_META_IMAGE_ARTIFACT_URL""#); + let mut download_cmd = r#"curl -Lf "$NOMAD_META_IMAGE_ARTIFACT_URL""#.to_string(); match build_compression { backend::build::BuildCompression::None => {} backend::build::BuildCompression::Lz4 => { @@ -641,5 +641,5 @@ fn inject_consul_env_template(input: &str) -> GlobalResult { } fn nomad_host_port_env_var(port_label: &str) -> String { - format!("NOMAD_HOST_PORT_{}", port_label.replace("-", "_")) + format!("NOMAD_HOST_PORT_{}", port_label.replace('-', "_")) } diff --git a/svc/pkg/mm/worker/src/workers/lobby_state_set.rs b/svc/pkg/mm/worker/src/workers/lobby_state_set.rs index baa31c5f5d..12b8c778ef 100644 --- a/svc/pkg/mm/worker/src/workers/lobby_state_set.rs +++ b/svc/pkg/mm/worker/src/workers/lobby_state_set.rs @@ -11,7 +11,7 @@ async fn worker(ctx: &OperationContext) -> Gl pipe.hset( util_mm::key::lobby_config(lobby_id), util_mm::key::lobby_config::STATE_JSON, - &state_json, + state_json, ); } else { pipe.hdel( diff --git a/svc/pkg/mm/worker/src/workers/player_remove.rs b/svc/pkg/mm/worker/src/workers/player_remove.rs index 5e71069ba4..1fa4dc4081 100644 --- a/svc/pkg/mm/worker/src/workers/player_remove.rs +++ b/svc/pkg/mm/worker/src/workers/player_remove.rs @@ -77,7 +77,7 @@ async fn worker(ctx: &OperationContext) -> Glob let player_row = if let Some(player_row) = player_row { player_row - } else if let Some(player_row) = fallback_fetch_player_from_redis(&ctx, player_id).await? { + } else if let Some(player_row) = fallback_fetch_player_from_redis(ctx, player_id).await? { player_row } else if ctx.req_dt() > util::duration::minutes(5) { tracing::error!("discarding stale message");