diff --git a/.rustfmt.toml b/.rustfmt.toml index 01b441c0efd..060859441e8 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,2 +1,2 @@ max_width = 120 -edition = "2021" +style_edition = "2021" diff --git a/Cargo.toml b/Cargo.toml index 006d5afc6de..2cbf67f4c36 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -106,7 +106,7 @@ debug = true [workspace.package] version = "2.0.0" -edition = "2021" +edition = "2024" # update rust-toolchain.toml too! rust-version = "1.93.0" diff --git a/crates/auth/src/identity.rs b/crates/auth/src/identity.rs index 785ddb4016e..5ecbe61dec7 100644 --- a/crates/auth/src/identity.rs +++ b/crates/auth/src/identity.rs @@ -115,12 +115,12 @@ impl TryInto for IncomingClaims { let computed_identity = Identity::from_claims(&self.issuer, &self.subject); // If an identity is provided, it must match the computed identity. - if let Some(token_identity) = self.identity { - if token_identity != computed_identity { - return Err(anyhow::anyhow!( + if let Some(token_identity) = self.identity + && token_identity != computed_identity + { + return Err(anyhow::anyhow!( "Identity mismatch: token identity {token_identity:?} does not match computed identity {computed_identity:?}", )); - } } Ok(SpacetimeIdentityClaims { diff --git a/crates/bench/src/schemas.rs b/crates/bench/src/schemas.rs index 01d9ddd3553..2ab7e57aedf 100644 --- a/crates/bench/src/schemas.rs +++ b/crates/bench/src/schemas.rs @@ -171,7 +171,7 @@ pub fn table_name(style: IndexStrategy) -> TableName { #[derive(Clone)] pub struct XorShiftLite(pub u64); impl XorShiftLite { - fn gen(&mut self) -> u64 { + fn r#gen(&mut self) -> u64 { let old = self.0; self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; @@ -189,36 +189,36 @@ pub trait RandomTable { /// Then in the filter benchmarks, `mean_result_count = table_size / buckets`. /// /// Currently the same number of buckets is used for all attributes. - fn gen(id: u32, rng: &mut XorShiftLite, buckets: u64) -> Self; + fn r#gen(id: u32, rng: &mut XorShiftLite, buckets: u64) -> Self; } impl RandomTable for u32_u64_str { - fn gen(id: u32, rng: &mut XorShiftLite, buckets: u64) -> Self { - let name = nth_name(rng.gen() % buckets).into(); - let age = rng.gen() % buckets; + fn r#gen(id: u32, rng: &mut XorShiftLite, buckets: u64) -> Self { + let name = nth_name(rng.r#gen() % buckets).into(); + let age = rng.r#gen() % buckets; u32_u64_str { id, name, age } } } impl RandomTable for u32_u64_u64 { - fn gen(id: u32, rng: &mut XorShiftLite, buckets: u64) -> Self { - let x = rng.gen() % buckets; - let y = rng.gen() % buckets; + fn r#gen(id: u32, rng: &mut XorShiftLite, buckets: u64) -> Self { + let x = rng.r#gen() % buckets; + let y = rng.r#gen() % buckets; u32_u64_u64 { id, x, y } } } impl RandomTable for u64_u64_u32 { - fn gen(id: u32, rng: &mut XorShiftLite, buckets: u64) -> Self { - let x = rng.gen() % buckets; - let y = rng.gen() % buckets; + fn r#gen(id: u32, rng: &mut XorShiftLite, buckets: u64) -> Self { + let x = rng.r#gen() % buckets; + let y = rng.r#gen() % buckets; u64_u64_u32 { x, y, id } } } pub fn create_sequential(seed: u64, count: u32, buckets: u64) -> Vec { let mut rng = XorShiftLite(seed); - (0..count).map(|id| T::gen(id, &mut rng, buckets)).collect() + (0..count).map(|id| T::r#gen(id, &mut rng, buckets)).collect() } /// Create a table whose first `identical` rows are identical except for their `id` column. @@ -237,13 +237,13 @@ pub fn create_partly_identical(seed: u64, identical: u64, total: for _ in 0..identical { // clone to preserve rng state let mut rng_ = rng.clone(); - result.push(T::gen(id as u32, &mut rng_, buckets)); + result.push(T::r#gen(id as u32, &mut rng_, buckets)); id += 1; } // advance rng - drop(T::gen(id as u32, &mut rng, buckets)); + drop(T::r#gen(id as u32, &mut rng, buckets)); for _ in identical..total { - result.push(T::gen(id as u32, &mut rng, buckets)); + result.push(T::r#gen(id as u32, &mut rng, buckets)); id += 1; } result @@ -254,8 +254,8 @@ pub fn create_random(seed: u64, count: u32, buckets: u64) -> Vec let mut rng = XorShiftLite(seed); (0..count) .map(|_| { - let id = (rng.gen() % (u32::MAX as u64)) as u32; - T::gen(id, &mut rng, buckets) + let id = (rng.r#gen() % (u32::MAX as u64)) as u32; + T::r#gen(id, &mut rng, buckets) }) .collect() } @@ -362,7 +362,7 @@ mod tests { } // sample some earlier names to make sure we haven't overlapped for _ in 0..30 { - let prev = rng.gen() % n; + let prev = rng.r#gen() % n; assert!( name != nth_name(prev), "names should not repeat, but {}->{} and {}->{}", diff --git a/crates/bench/src/sqlite.rs b/crates/bench/src/sqlite.rs index 115e74f4ad5..d1d366da406 100644 --- a/crates/bench/src/sqlite.rs +++ b/crates/bench/src/sqlite.rs @@ -227,10 +227,10 @@ fn memo_query String>(bench_name: BenchName, table_id: &str, gene // fast path let queries = QUERIES.read().unwrap(); - if let Some(bench_queries) = queries.get(&bench_name) { - if let Some(query) = bench_queries.get(table_id) { - return query.clone(); - } + if let Some(bench_queries) = queries.get(&bench_name) + && let Some(query) = bench_queries.get(table_id) + { + return query.clone(); } // slow path diff --git a/crates/bindings-macro/src/lib.rs b/crates/bindings-macro/src/lib.rs index 5825cd15f59..65049157e70 100644 --- a/crates/bindings-macro/src/lib.rs +++ b/crates/bindings-macro/src/lib.rs @@ -9,12 +9,81 @@ // (private documentation for the macro authors is totally fine here and you SHOULD write that!) mod procedure; + +#[proc_macro_attribute] +pub fn procedure(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream { + cvt_attr::(args, item, quote!(), |args, original_function| { + let args = procedure::ProcedureArgs::parse(args)?; + procedure::procedure_impl(args, original_function) + }) +} mod reducer; + +#[proc_macro_attribute] +pub fn reducer(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream { + cvt_attr::(args, item, quote!(), |args, original_function| { + let args = reducer::ReducerArgs::parse(args)?; + reducer::reducer_impl(args, original_function) + }) +} mod sats; mod table; + +#[proc_macro_attribute] +pub fn table(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream { + // put this on the struct so we don't get unknown attribute errors + let derive_table_helper: syn::Attribute = derive_table_helper_attr(); + + ok_or_compile_error(|| { + let item = TokenStream::from(item); + let mut derive_input: syn::DeriveInput = syn::parse2(item.clone())?; + + // Add `derive(__TableHelper)` only if it's not already in the attributes of the `derive_input.` + // If multiple `#[table]` attributes are applied to the same `struct` item, + // this will ensure that we don't emit multiple conflicting implementations + // for traits like `SpacetimeType`, `Serialize` and `Deserialize`. + // + // We need to push at the end, rather than the beginning, + // because rustc expands attribute macros (including derives) top-to-bottom, + // and we need *all* `#[table]` attributes *before* the `derive(__TableHelper)`. + // This way, the first `table` will insert a `derive(__TableHelper)`, + // and all subsequent `#[table]`s on the same `struct` will see it, + // and not add another. + // + // Note, thank goodness, that `syn`'s `PartialEq` impls (provided with the `extra-traits` feature) + // skip any [`Span`]s contained in the items, + // thereby comparing for syntactic rather than structural equality. This shouldn't matter, + // since we expect that the `derive_table_helper` will always have the same [`Span`]s, + // but it's nice to know. + if !derive_input.attrs.contains(&derive_table_helper) { + derive_input.attrs.push(derive_table_helper); + } + + let args = table::TableArgs::parse(args.into(), &derive_input.ident)?; + let generated = table::table_impl(args, &derive_input)?; + Ok(TokenStream::from_iter([quote!(#derive_input), generated])) + }) +} mod util; mod view; +#[proc_macro_attribute] +pub fn view(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream { + let item_ts: TokenStream = item.into(); + let original_function = match syn::parse2::(item_ts.clone()) { + Ok(f) => f, + Err(e) => return TokenStream::from_iter([item_ts, e.into_compile_error()]).into(), + }; + let args = match view::ViewArgs::parse(args.into(), &original_function.sig.ident) { + Ok(a) => a, + Err(e) => return TokenStream::from_iter([item_ts, e.into_compile_error()]).into(), + }; + match view::view_impl(args, &original_function) { + Ok(ts) => ts.into(), + Err(e) => TokenStream::from_iter([item_ts, e.into_compile_error()]).into(), + } +} + use proc_macro::TokenStream as StdTokenStream; use proc_macro2::TokenStream; use quote::quote; @@ -109,39 +178,6 @@ mod sym { } } -#[proc_macro_attribute] -pub fn procedure(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream { - cvt_attr::(args, item, quote!(), |args, original_function| { - let args = procedure::ProcedureArgs::parse(args)?; - procedure::procedure_impl(args, original_function) - }) -} - -#[proc_macro_attribute] -pub fn reducer(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream { - cvt_attr::(args, item, quote!(), |args, original_function| { - let args = reducer::ReducerArgs::parse(args)?; - reducer::reducer_impl(args, original_function) - }) -} - -#[proc_macro_attribute] -pub fn view(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream { - let item_ts: TokenStream = item.into(); - let original_function = match syn::parse2::(item_ts.clone()) { - Ok(f) => f, - Err(e) => return TokenStream::from_iter([item_ts, e.into_compile_error()]).into(), - }; - let args = match view::ViewArgs::parse(args.into(), &original_function.sig.ident) { - Ok(a) => a, - Err(e) => return TokenStream::from_iter([item_ts, e.into_compile_error()]).into(), - }; - match view::view_impl(args, &original_function) { - Ok(ts) => ts.into(), - Err(e) => TokenStream::from_iter([item_ts, e.into_compile_error()]).into(), - } -} - /// It turns out to be shockingly difficult to construct an [`Attribute`]. /// That type is not [`Parse`], instead having two distinct methods /// for parsing "inner" vs "outer" attributes. @@ -158,42 +194,6 @@ fn derive_table_helper_attr() -> Attribute { .unwrap() } -#[proc_macro_attribute] -pub fn table(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream { - // put this on the struct so we don't get unknown attribute errors - let derive_table_helper: syn::Attribute = derive_table_helper_attr(); - - ok_or_compile_error(|| { - let item = TokenStream::from(item); - let mut derive_input: syn::DeriveInput = syn::parse2(item.clone())?; - - // Add `derive(__TableHelper)` only if it's not already in the attributes of the `derive_input.` - // If multiple `#[table]` attributes are applied to the same `struct` item, - // this will ensure that we don't emit multiple conflicting implementations - // for traits like `SpacetimeType`, `Serialize` and `Deserialize`. - // - // We need to push at the end, rather than the beginning, - // because rustc expands attribute macros (including derives) top-to-bottom, - // and we need *all* `#[table]` attributes *before* the `derive(__TableHelper)`. - // This way, the first `table` will insert a `derive(__TableHelper)`, - // and all subsequent `#[table]`s on the same `struct` will see it, - // and not add another. - // - // Note, thank goodness, that `syn`'s `PartialEq` impls (provided with the `extra-traits` feature) - // skip any [`Span`]s contained in the items, - // thereby comparing for syntactic rather than structural equality. This shouldn't matter, - // since we expect that the `derive_table_helper` will always have the same [`Span`]s, - // but it's nice to know. - if !derive_input.attrs.contains(&derive_table_helper) { - derive_input.attrs.push(derive_table_helper); - } - - let args = table::TableArgs::parse(args.into(), &derive_input.ident)?; - let generated = table::table_impl(args, &derive_input)?; - Ok(TokenStream::from_iter([quote!(#derive_input), generated])) - }) -} - /// Special alias for `derive(SpacetimeType)`, aka [`schema_type`], for use by [`table`]. /// /// Provides helper attributes for `#[spacetimedb::table]`, so that we don't get unknown attribute errors. @@ -291,7 +291,7 @@ pub fn client_visibility_filter(args: StdTokenStream, item: StdTokenStream) -> S #item const _: () = { - #[export_name = #register_rls_symbol] + #[unsafe(export_name = #register_rls_symbol)] extern "C" fn __register_client_visibility_filter() { spacetimedb::rt::register_row_level_security(#rls_ident.sql_text()) } diff --git a/crates/bindings-macro/src/procedure.rs b/crates/bindings-macro/src/procedure.rs index e18f002c297..9f76e5b547f 100644 --- a/crates/bindings-macro/src/procedure.rs +++ b/crates/bindings-macro/src/procedure.rs @@ -81,7 +81,7 @@ pub(crate) fn procedure_impl(_args: ProcedureArgs, original_function: &ItemFn) - let lifetime_where_clause = &lifetime_params.where_clause; let generated_describe_function = quote! { - #[export_name = #register_describer_symbol] + #[unsafe(export_name = #register_describer_symbol)] pub extern "C" fn __register_describer() { spacetimedb::rt::register_procedure::<_, _, #func_name>(#func_name) } diff --git a/crates/bindings-macro/src/reducer.rs b/crates/bindings-macro/src/reducer.rs index dbf8afce373..ac261ced35f 100644 --- a/crates/bindings-macro/src/reducer.rs +++ b/crates/bindings-macro/src/reducer.rs @@ -67,12 +67,12 @@ pub(crate) fn assert_only_lifetime_generics(original_function: &ItemFn, function syn::GenericParam::Type(_) => { return Err(err(format!( "type parameters are not allowed on {function_kind_plural}" - ))) + ))); } syn::GenericParam::Const(_) => { return Err(err(format!( "const parameters are not allowed on {function_kind_plural}" - ))) + ))); } } } @@ -135,7 +135,7 @@ pub(crate) fn reducer_impl(args: ReducerArgs, original_function: &ItemFn) -> syn let lt_where_clause = <_params.where_clause; let generated_describe_function = quote! { - #[export_name = #register_describer_symbol] + #[unsafe(export_name = #register_describer_symbol)] pub extern "C" fn __register_describer() { spacetimedb::rt::register_reducer::<_, #func_name>(#func_name) } diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs index 4d7bfc396f6..a3bcd980661 100644 --- a/crates/bindings-macro/src/table.rs +++ b/crates/bindings-macro/src/table.rs @@ -784,14 +784,14 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R } } - if let Some(default_value) = &default_value { - if auto_inc.is_some() || primary_key.is_some() || unique.is_some() { - return Err(syn::Error::new( - default_value.span(), - "invalid combination: auto_inc, unique index or primary key cannot have a default value", - )); - }; - } + if let Some(default_value) = &default_value + && (auto_inc.is_some() || primary_key.is_some() || unique.is_some()) + { + return Err(syn::Error::new( + default_value.span(), + "invalid combination: auto_inc, unique index or primary key cannot have a default value", + )); + }; let column = Column { index: col_num, @@ -1038,7 +1038,7 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R let register_describer_symbol = format!("__preinit__20_register_describer_{table_ident}"); let describe_table_func = quote! { - #[export_name = #register_describer_symbol] + #[unsafe(export_name = #register_describer_symbol)] extern "C" fn __register_describer() { spacetimedb::rt::register_table::<#tablehandle_ident>() } diff --git a/crates/bindings-macro/src/view.rs b/crates/bindings-macro/src/view.rs index cb2ed4ecf3e..2acc83a8258 100644 --- a/crates/bindings-macro/src/view.rs +++ b/crates/bindings-macro/src/view.rs @@ -61,16 +61,13 @@ impl ViewArgs { fn extract_impl_query_inner(ty: &syn::Type) -> Option<&syn::Type> { if let syn::Type::ImplTrait(impl_trait) = ty { for bound in &impl_trait.bounds { - if let syn::TypeParamBound::Trait(trait_bound) = bound { - if let Some(seg) = trait_bound.path.segments.last() { - if seg.ident == "Query" { - if let syn::PathArguments::AngleBracketed(args) = &seg.arguments { - if let Some(syn::GenericArgument::Type(inner)) = args.args.first() { - return Some(inner); - } - } - } - } + if let syn::TypeParamBound::Trait(trait_bound) = bound + && let Some(seg) = trait_bound.path.segments.last() + && seg.ident == "Query" + && let syn::PathArguments::AngleBracketed(args) = &seg.arguments + && let Some(syn::GenericArgument::Type(inner)) = args.args.first() + { + return Some(inner); } } } @@ -162,7 +159,7 @@ pub(crate) fn view_impl(args: ViewArgs, original_function: &ItemFn) -> syn::Resu let lt_where_clause = <_params.where_clause; let generated_describe_function = quote! { - #[export_name = #register_describer_symbol] + #[unsafe(export_name = #register_describer_symbol)] pub extern "C" fn __register_describer() { spacetimedb::rt::ViewRegistrar::<#ctx_ty>::register::<_, #func_name, _, _>(#func_name) } diff --git a/crates/bindings-sys/src/lib.rs b/crates/bindings-sys/src/lib.rs index aa212413bef..95dfbc7e600 100644 --- a/crates/bindings-sys/src/lib.rs +++ b/crates/bindings-sys/src/lib.rs @@ -19,7 +19,7 @@ pub mod raw { // with a module identifier with a minor version 1 above the previous highest minor version. // For breaking changes, all functions should be moved into one new `spacetime_X.0` block. #[link(wasm_import_module = "spacetime_10.0")] - extern "C" { + unsafe extern "C" { /// Queries the `table_id` associated with the given (table) `name` /// where `name` is the UTF-8 slice in WASM memory at `name_ptr[..name_len]`. /// @@ -592,7 +592,7 @@ pub mod raw { // See comment on previous `extern "C"` block re: ABI version. #[link(wasm_import_module = "spacetime_10.1")] - extern "C" { + unsafe extern "C" { /// Read the remaining length of a [`BytesSource`] and write it to `out`. /// /// Note that the host automatically frees byte sources which are exhausted. @@ -621,7 +621,7 @@ pub mod raw { // See comment on previous `extern "C"` block re: ABI version. #[link(wasm_import_module = "spacetime_10.2")] - extern "C" { + unsafe extern "C" { /// Finds the JWT payload associated with `connection_id`. /// A `[ByteSourceId]` for the payload will be written to `target_ptr`. /// If nothing is found for the connection, `[ByteSourceId::INVALID]` (zero) is written to `target_ptr`. @@ -646,7 +646,7 @@ pub mod raw { #[cfg(feature = "unstable")] #[link(wasm_import_module = "spacetime_10.3")] - extern "C" { + unsafe extern "C" { /// Suspends execution of this WASM instance until approximately `wake_at_micros_since_unix_epoch`. /// /// Returns immediately if `wake_at_micros_since_unix_epoch` is in the past. @@ -786,7 +786,7 @@ pub mod raw { } #[link(wasm_import_module = "spacetime_10.4")] - extern "C" { + unsafe extern "C" { /// Finds all rows in the index identified by `index_id`, /// according to `point = point_ptr[..point_len]` in WASM memory. /// @@ -1039,10 +1039,12 @@ fn cvt(x: u16) -> Result<()> { /// before writing a safe and valid `T` to it. #[inline] unsafe fn call(f: impl FnOnce(*mut T) -> u16) -> Result { - let mut out = MaybeUninit::uninit(); - let f_code = f(out.as_mut_ptr()); - cvt(f_code)?; - Ok(out.assume_init()) + unsafe { + let mut out = MaybeUninit::uninit(); + let f_code = f(out.as_mut_ptr()); + cvt(f_code)?; + Ok(out.assume_init()) + } } /// Runs the given function `f`. diff --git a/crates/bindings-typescript/test-app/server/Cargo.toml b/crates/bindings-typescript/test-app/server/Cargo.toml index f47518024d9..c61fe890b87 100644 --- a/crates/bindings-typescript/test-app/server/Cargo.toml +++ b/crates/bindings-typescript/test-app/server/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "typescript-test-app" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/crates/bindings-typescript/test-react-router-app/server/Cargo.toml b/crates/bindings-typescript/test-react-router-app/server/Cargo.toml index 2bd6ae607e2..99797536040 100644 --- a/crates/bindings-typescript/test-react-router-app/server/Cargo.toml +++ b/crates/bindings-typescript/test-react-router-app/server/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "typescript-test-react-router-app" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/crates/bindings/src/logger.rs b/crates/bindings/src/logger.rs index 58416e55981..8d2203320b5 100644 --- a/crates/bindings/src/logger.rs +++ b/crates/bindings/src/logger.rs @@ -5,7 +5,7 @@ use std::sync::Mutex; use std::{fmt, panic}; /// Registers the panic hook to our own. -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn __preinit__00_panic_hook() { panic::set_hook(Box::new(panic_hook)); } @@ -77,7 +77,7 @@ static LOGGER: Logger = Logger { /// Registers our logger unless already set. /// The maximum level is `Trace`. -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn __preinit__15_init_log() { // if the user wants to set their own logger, that's fine if log::set_logger(&LOGGER).is_ok() { diff --git a/crates/bindings/src/rt.rs b/crates/bindings/src/rt.rs index e99ac2df73a..28682c0d244 100644 --- a/crates/bindings/src/rt.rs +++ b/crates/bindings/src/rt.rs @@ -908,7 +908,7 @@ static ANONYMOUS_VIEWS: OnceLock> = OnceLock::new(); /// to define and, to a limited extent, alter the schema at initialization time, /// including when modules are updated (re-publishing). /// After initialization, the module cannot alter the schema. -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn __describe_module__(description: BytesSink) { // Collect the `module`. let mut module = ModuleBuilder::default(); @@ -964,7 +964,7 @@ extern "C" fn __describe_module__(description: BytesSink) { /// it is expected that `HOST_CALL_FAILURE` is returned. /// Otherwise, `0` should be returned, i.e., the reducer completed successfully. /// Note that in the future, more failure codes could be supported. -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn __call_reducer__( id: usize, sender_0: u64, @@ -1061,7 +1061,7 @@ fn convert_err_to_errno(res: Result<(), Box>, out: BytesSink) -> i16 { /// /// Procedures always return the error 0. All other return values are reserved. #[cfg(feature = "unstable")] -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn __call_procedure__( id: usize, sender_0: u64, @@ -1115,7 +1115,7 @@ extern "C" fn __call_procedure__( /// /// The current abi is identified by a return code of 2. /// The previous abi, which we still support, is identified by a return code of 0. -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn __call_view_anon__(id: usize, args: BytesSource, sink: BytesSink) -> i16 { let views = ANONYMOUS_VIEWS.get().unwrap(); write_to_sink( @@ -1143,7 +1143,7 @@ extern "C" fn __call_view_anon__(id: usize, args: BytesSource, sink: BytesSink) /// /// The current abi is identified by a return code of 2. /// The previous abi, which we still support, is identified by a return code of 0. -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn __call_view__( id: usize, sender_0: u64, @@ -1277,7 +1277,7 @@ fn write_to_sink(sink: BytesSink, mut buf: &[u8]) { macro_rules! __make_register_reftype { ($ty:ty, $name:literal) => { const _: () = { - #[export_name = concat!("__preinit__20_register_describer_", $name)] + #[unsafe(export_name = concat!("__preinit__20_register_describer_", $name))] extern "C" fn __register_describer() { $crate::rt::register_reftype::<$ty>() } diff --git a/crates/bindings/src/table.rs b/crates/bindings/src/table.rs index c0cdb684f23..55b77a08622 100644 --- a/crates/bindings/src/table.rs +++ b/crates/bindings/src/table.rs @@ -576,7 +576,7 @@ impl PointIndex /// } /// # } /// ``` - pub fn filter(&self, point: P) -> impl Iterator + pub fn filter(&self, point: P) -> impl Iterator + use where P: WithPointArg, { @@ -664,7 +664,7 @@ impl PointIndexReadOnly(&self, point: P) -> impl Iterator + pub fn filter(&self, point: P) -> impl Iterator + use where P: WithPointArg, { @@ -856,7 +856,7 @@ impl RangedIndex /// > | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `RangedIndex::::filter` /// > ``` /// - pub fn filter(&self, b: B) -> impl Iterator + pub fn filter(&self, b: B) -> impl Iterator + use where B: IndexScanRangeBounds, { @@ -997,7 +997,7 @@ impl RangedIndexReadOnly #[doc(hidden)] pub const __NEW: Self = Self { _marker: PhantomData }; - pub fn filter(&self, b: B) -> impl Iterator + pub fn filter(&self, b: B) -> impl Iterator + use where B: IndexScanRangeBounds, { diff --git a/crates/bindings/tests/ui/tables.stderr b/crates/bindings/tests/ui/tables.stderr index 5c8b05e0d11..bbb002775dd 100644 --- a/crates/bindings/tests/ui/tables.stderr +++ b/crates/bindings/tests/ui/tables.stderr @@ -196,7 +196,7 @@ help: the trait `FilterableValue` is not implemented for `Alpha` note: required by a bound in `RangedIndex::::filter` --> src/table.rs | - | pub fn filter(&self, b: B) -> impl Iterator + | pub fn filter(&self, b: B) -> impl Iterator + use | ------ required by a bound in this associated function | where | B: IndexScanRangeBounds, diff --git a/crates/cli/build.rs b/crates/cli/build.rs index 1754c3f4c99..adb8740a352 100644 --- a/crates/cli/build.rs +++ b/crates/cli/build.rs @@ -638,10 +638,10 @@ fn write_if_changed(path: &Path, contents: &[u8]) -> io::Result<()> { fn copy_if_changed(src: &Path, dst: &Path) -> io::Result<()> { let src_bytes = fs::read(src)?; - if let Ok(existing) = fs::read(dst) { - if existing == src_bytes { - return Ok(()); - } + if let Ok(existing) = fs::read(dst) + && existing == src_bytes + { + return Ok(()); } if let Some(parent) = dst.parent() { diff --git a/crates/cli/src/config.rs b/crates/cli/src/config.rs index abcac98fbaa..eb559199daf 100644 --- a/crates/cli/src/config.rs +++ b/crates/cli/src/config.rs @@ -220,22 +220,22 @@ impl RawConfig { ecdsa_public_key: Option, nickname: Option, ) -> anyhow::Result<()> { - if let Some(nickname) = &nickname { - if let Ok(cfg) = self.find_server(nickname) { - anyhow::bail!( - "Server nickname {} already in use: {}://{}", - nickname, - cfg.protocol, - cfg.host, - ); - } + if let Some(nickname) = &nickname + && let Ok(cfg) = self.find_server(nickname) + { + anyhow::bail!( + "Server nickname {} already in use: {}://{}", + nickname, + cfg.protocol, + cfg.host, + ); } if let Ok(cfg) = self.find_server(&host) { - if let Some(nick) = &cfg.nickname { - if nick == &host { - anyhow::bail!("Server host name is ambiguous with existing server nickname: {nick}"); - } + if let Some(nick) = &cfg.nickname + && nick == &host + { + anyhow::bail!("Server host name is ambiguous with existing server nickname: {nick}"); } anyhow::bail!("Server already configured for host: {host}"); } @@ -295,10 +295,10 @@ impl RawConfig { // If we're removing the default server, // unset the default server. - if let Some(default_server) = &self.default_server { - if cfg.nick_or_host_or_url_is(default_server) { - self.default_server = None; - } + if let Some(default_server) = &self.default_server + && cfg.nick_or_host_or_url_is(default_server) + { + self.default_server = None; } return Ok(()); @@ -370,27 +370,27 @@ Fetch the server's fingerprint with: ) -> anyhow::Result<(Option, Option, Option)> { // Check if the new nickname or host name would introduce ambiguities between // server configurations. - if let Some(new_nick) = new_nickname { - if let Ok(other_server) = self.find_server(new_nick) { - anyhow::bail!( - "Nickname {} conflicts with saved configuration for server {}: {}://{}", - new_nick, - other_server.nick_or_host(), - other_server.protocol, - other_server.host - ); - } + if let Some(new_nick) = new_nickname + && let Ok(other_server) = self.find_server(new_nick) + { + anyhow::bail!( + "Nickname {} conflicts with saved configuration for server {}: {}://{}", + new_nick, + other_server.nick_or_host(), + other_server.protocol, + other_server.host + ); } - if let Some(new_host) = new_host { - if let Ok(other_server) = self.find_server(new_host) { - anyhow::bail!( - "Host {} conflicts with saved configuration for server {}: {}://{}", - new_host, - other_server.nick_or_host(), - other_server.protocol, - other_server.host - ); - } + if let Some(new_host) = new_host + && let Ok(other_server) = self.find_server(new_host) + { + anyhow::bail!( + "Host {} conflicts with saved configuration for server {}: {}://{}", + new_host, + other_server.nick_or_host(), + other_server.protocol, + other_server.host + ); } let cfg = self.find_server_mut(server)?; @@ -418,10 +418,10 @@ Fetch the server's fingerprint with: if default_server == old_host { *default_server = new_host.unwrap().to_string(); } - } else if let Some(old_nick) = &old_nickname { - if default_server == old_nick { - *default_server = new_nickname.unwrap().to_string(); - } + } else if let Some(old_nick) = &old_nickname + && default_server == old_nick + { + *default_server = new_nickname.unwrap().to_string(); } } diff --git a/crates/cli/src/spacetime_config.rs b/crates/cli/src/spacetime_config.rs index 29b45b8765a..f5d00740ac0 100644 --- a/crates/cli/src/spacetime_config.rs +++ b/crates/cli/src/spacetime_config.rs @@ -303,13 +303,13 @@ impl CommandSchemaBuilder { } // Validate alias if present - if let Some(alias) = &key.clap_alias { - if !clap_arg_names.contains(alias) { - return Err(CommandConfigError::InvalidAliasReference { - config_name: key.config_name().to_string(), - alias: alias.clone(), - }); - } + if let Some(alias) = &key.clap_alias + && !clap_arg_names.contains(alias) + { + return Err(CommandConfigError::InvalidAliasReference { + config_name: key.config_name().to_string(), + alias: alias.clone(), + }); } } @@ -391,23 +391,20 @@ impl CommandSchema { .unwrap_or(config_name); // Only return the value if it was actually provided by the user, not from defaults - if let Some(source) = matches.value_source(clap_name) { - if source == clap::parser::ValueSource::CommandLine { - if let Some(value) = matches.get_one::(clap_name) { - return Ok(Some(value.clone())); - } - } + if let Some(source) = matches.value_source(clap_name) + && source == clap::parser::ValueSource::CommandLine + && let Some(value) = matches.get_one::(clap_name) + { + return Ok(Some(value.clone())); } // Try clap with the alias if it exists - if let Some(alias) = self.config_to_alias.get(config_name) { - if let Some(source) = matches.value_source(alias) { - if source == clap::parser::ValueSource::CommandLine { - if let Some(value) = matches.get_one::(alias) { - return Ok(Some(value.clone())); - } - } - } + if let Some(alias) = self.config_to_alias.get(config_name) + && let Some(source) = matches.value_source(alias) + && source == clap::parser::ValueSource::CommandLine + && let Some(value) = matches.get_one::(alias) + { + return Ok(Some(value.clone())); } Ok(None) @@ -424,19 +421,18 @@ impl CommandSchema { .unwrap_or(config_name); // Use value_source to check if the value was actually provided by the user - if let Some(source) = matches.value_source(clap_name) { - if source == clap::parser::ValueSource::CommandLine { - return true; - } + if let Some(source) = matches.value_source(clap_name) + && source == clap::parser::ValueSource::CommandLine + { + return true; } // Check clap with alias - if let Some(alias) = self.config_to_alias.get(config_name) { - if let Some(source) = matches.value_source(alias) { - if source == clap::parser::ValueSource::CommandLine { - return true; - } - } + if let Some(alias) = self.config_to_alias.get(config_name) + && let Some(source) = matches.value_source(alias) + && source == clap::parser::ValueSource::CommandLine + { + return true; } false @@ -999,16 +995,15 @@ pub fn detect_package_manager(project_dir: &Path) -> Option { pub fn detect_client_command(project_dir: &Path) -> Option<(String, Option)> { // JavaScript/TypeScript: package.json with "dev" script let package_json = project_dir.join("package.json"); - if package_json.exists() { - if let Ok(content) = fs::read_to_string(&package_json) { - if let Ok(json) = serde_json::from_str::(&content) { - let has_dev = json.get("scripts").and_then(|s| s.get("dev")).is_some(); - if has_dev { - let pm = detect_package_manager(project_dir); - let cmd = pm.map(|p| p.run_dev_command()).unwrap_or("npm run dev"); - return Some((cmd.to_string(), pm)); - } - } + if package_json.exists() + && let Ok(content) = fs::read_to_string(&package_json) + && let Ok(json) = serde_json::from_str::(&content) + { + let has_dev = json.get("scripts").and_then(|s| s.get("dev")).is_some(); + if has_dev { + let pm = detect_package_manager(project_dir); + let cmd = pm.map(|p| p.run_dev_command()).unwrap_or("npm run dev"); + return Some((cmd.to_string(), pm)); } } @@ -2746,9 +2741,9 @@ mod tests { target.fields.get("module-path").and_then(|v| v.as_str()), Some("./server") ); - let gen = target.generate.as_ref().unwrap(); - assert_eq!(gen.len(), 1); - assert_eq!(gen[0].get("language").and_then(|v| v.as_str()), Some("typescript")); + let r#gen = target.generate.as_ref().unwrap(); + assert_eq!(r#gen.len(), 1); + assert_eq!(r#gen[0].get("language").and_then(|v| v.as_str()), Some("typescript")); } // All have the same (module-path, generate) so dedup should reduce to 1 diff --git a/crates/cli/src/subcommands/dev.rs b/crates/cli/src/subcommands/dev.rs index 783b47f8a3f..466bd0b47c9 100644 --- a/crates/cli/src/subcommands/dev.rs +++ b/crates/cli/src/subcommands/dev.rs @@ -486,20 +486,21 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E } // Safety prompt: warn if publishing from spacetime.json (not a dev-specific config) - if let Some(ref lc) = loaded_config { - if !lc.has_dev_file && !force { - eprintln!( - "{} Publishing from spacetime.json (not a dev-specific config).", - "Warning:".yellow().bold() - ); - eprintln!( - "{}", - "Consider creating spacetime.dev.json for development settings.".dimmed() - ); - let should_continue = Confirm::new().with_prompt("Continue?").default(true).interact()?; - if !should_continue { - anyhow::bail!("Aborted."); - } + if let Some(ref lc) = loaded_config + && !lc.has_dev_file + && !force + { + eprintln!( + "{} Publishing from spacetime.json (not a dev-specific config).", + "Warning:".yellow().bold() + ); + eprintln!( + "{}", + "Consider creating spacetime.dev.json for development settings.".dimmed() + ); + let should_continue = Confirm::new().with_prompt("Continue?").default(true).interact()?; + if !should_continue { + anyhow::bail!("Aborted."); } } @@ -588,13 +589,13 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E let (tx, rx) = channel(); let mut watcher: RecommendedWatcher = Watcher::new( move |res: Result| { - if let Ok(event) = res { - if matches!( + if let Ok(event) = res + && matches!( event.kind, notify::EventKind::Modify(_) | notify::EventKind::Create(_) | notify::EventKind::Remove(_) - ) { - let _ = tx.send(()); - } + ) + { + let _ = tx.send(()); } }, notify::Config::default().with_poll_interval(Duration::from_millis(500)), @@ -887,10 +888,10 @@ async fn generate_build_and_publish( } // Forward per-target build options if set - if let Some(build_opts) = config_entry.get_config_value("build_options").and_then(|v| v.as_str()) { - if !build_opts.is_empty() { - publish_args.extend_from_slice(&["--build-options".to_string(), build_opts.to_string()]); - } + if let Some(build_opts) = config_entry.get_config_value("build_options").and_then(|v| v.as_str()) + && !build_opts.is_empty() + { + publish_args.extend_from_slice(&["--build-options".to_string(), build_opts.to_string()]); } // Forward break-clients if set @@ -1170,28 +1171,28 @@ fn format_log_record( let mut need_space_before_filename = false; let mut need_colon_sep = false; let dimmed = ColorSpec::new().set_dimmed(true).clone(); - if let Some(function) = &record.function { - if function.as_ref() != SENTINEL { - out.set_color(&dimmed)?; - write!(out, "{function}")?; - out.reset()?; - need_space_before_filename = true; - need_colon_sep = true; - } + if let Some(function) = &record.function + && function.as_ref() != SENTINEL + { + out.set_color(&dimmed)?; + write!(out, "{function}")?; + out.reset()?; + need_space_before_filename = true; + need_colon_sep = true; } - if let Some(filename) = &record.filename { - if filename.as_ref() != SENTINEL { - out.set_color(&dimmed)?; - if need_space_before_filename { - write!(out, " ")?; - } - write!(out, "{filename}")?; - if let Some(line) = record.line_number { - write!(out, ":{line}")?; - } - out.reset()?; - need_colon_sep = true; + if let Some(filename) = &record.filename + && filename.as_ref() != SENTINEL + { + out.set_color(&dimmed)?; + if need_space_before_filename { + write!(out, " ")?; } + write!(out, "{filename}")?; + if let Some(line) = record.line_number { + write!(out, ":{line}")?; + } + out.reset()?; + need_colon_sep = true; } if need_colon_sep { write!(out, ": ")?; diff --git a/crates/cli/src/subcommands/generate.rs b/crates/cli/src/subcommands/generate.rs index f7ef86dc1fa..be148f63b08 100644 --- a/crates/cli/src/subcommands/generate.rs +++ b/crates/cli/src/subcommands/generate.rs @@ -691,7 +691,7 @@ mod tests { let mut child_fields = HashMap::new(); child_fields.insert("database".to_string(), serde_json::json!("my-db")); - let gen = { + let r#gen = { let mut m = HashMap::new(); m.insert("language".to_string(), serde_json::json!("rust")); m.insert("out_dir".to_string(), serde_json::json!("/tmp/out")); @@ -700,7 +700,7 @@ mod tests { let spacetime_config = SpacetimeConfig { additional_fields: parent_fields, - children: Some(vec![make_gen_config(child_fields, vec![gen])]), + children: Some(vec![make_gen_config(child_fields, vec![r#gen])]), ..Default::default() }; @@ -720,7 +720,7 @@ mod tests { let cmd = cli(); let schema = build_generate_config_schema(&cmd).unwrap(); - let gen = { + let r#gen = { let mut m = HashMap::new(); m.insert("language".to_string(), serde_json::json!("typescript")); m.insert("out_dir".to_string(), serde_json::json!("/tmp/out")); @@ -732,7 +732,7 @@ mod tests { let spacetime_config = SpacetimeConfig { additional_fields: parent_fields, - generate: Some(vec![gen]), + generate: Some(vec![r#gen]), children: Some(vec![ { let mut f = HashMap::new(); @@ -895,7 +895,7 @@ mod tests { let cmd = cli(); let schema = build_generate_config_schema(&cmd).unwrap(); - let gen = { + let r#gen = { let mut m = HashMap::new(); m.insert("language".to_string(), serde_json::json!("typescript")); m.insert("out_dir".to_string(), serde_json::json!("/tmp/bindings")); @@ -907,7 +907,7 @@ mod tests { let spacetime_config = SpacetimeConfig { additional_fields: parent_fields, - generate: Some(vec![gen]), + generate: Some(vec![r#gen]), children: Some(vec![ { let mut f = HashMap::new(); @@ -946,7 +946,7 @@ mod tests { let cmd = cli(); let schema = build_generate_config_schema(&cmd).unwrap(); - let gen = { + let r#gen = { let mut m = HashMap::new(); m.insert("language".to_string(), serde_json::json!("rust")); m.insert("out_dir".to_string(), serde_json::json!("/tmp/out")); @@ -962,7 +962,7 @@ mod tests { m.insert("module-path".to_string(), serde_json::json!("./m1")); m }, - vec![gen.clone()], + vec![r#gen.clone()], ), make_gen_config( { @@ -971,7 +971,7 @@ mod tests { m.insert("module-path".to_string(), serde_json::json!("./m2")); m }, - vec![gen.clone()], + vec![r#gen.clone()], ), make_gen_config( { @@ -980,7 +980,7 @@ mod tests { m.insert("module-path".to_string(), serde_json::json!("./m3")); m }, - vec![gen], + vec![r#gen], ), ]), ..Default::default() @@ -999,7 +999,7 @@ mod tests { let cmd = cli(); let schema = build_generate_config_schema(&cmd).unwrap(); - let gen = { + let r#gen = { let mut m = HashMap::new(); m.insert("language".to_string(), serde_json::json!("rust")); m.insert("out_dir".to_string(), serde_json::json!("/tmp/out")); @@ -1013,7 +1013,7 @@ mod tests { m.insert("module-path".to_string(), serde_json::json!("./server")); m }, - vec![gen], + vec![r#gen], ); let matches = cmd.clone().get_matches_from(vec!["generate", "nonexistent-*"]); diff --git a/crates/cli/src/subcommands/init.rs b/crates/cli/src/subcommands/init.rs index df6a6a0e580..23dae6378b0 100644 --- a/crates/cli/src/subcommands/init.rs +++ b/crates/cli/src/subcommands/init.rs @@ -746,10 +746,10 @@ fn clone_github_template(repo_input: &str, target: &Path, is_server_only: bool) let mut callbacks = git2::RemoteCallbacks::new(); callbacks.credentials(|_url, username_from_url, allowed_types| { - if allowed_types.contains(git2::CredentialType::SSH_KEY) { - if let Some(username) = username_from_url { - return git2::Cred::ssh_key_from_agent(username); - } + if allowed_types.contains(git2::CredentialType::SSH_KEY) + && let Some(username) = username_from_url + { + return git2::Cred::ssh_key_from_agent(username); } if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) { return git2::Cred::userpass_plaintext("", ""); @@ -815,10 +815,10 @@ fn update_package_json(dir: &Path, package_name: &str) -> anyhow::Result<()> { package["name"] = json!(package_name); // Update spacetimedb version if it exists in dependencies - if let Some(deps) = package.get_mut("dependencies") { - if deps.get("spacetimedb").is_some() { - deps["spacetimedb"] = json!(format!("^{}", get_spacetimedb_typescript_version())); - } + if let Some(deps) = package.get_mut("dependencies") + && deps.get("spacetimedb").is_some() + { + deps["spacetimedb"] = json!(format!("^{}", get_spacetimedb_typescript_version())); } let updated_content = serde_json::to_string_pretty(&package)?; @@ -851,40 +851,40 @@ fn update_cargo_toml_name(dir: &Path, package_name: &str) -> anyhow::Result<()> .map(|c| if c.is_alphanumeric() || c == '_' { c } else { '_' }) .collect::(); - if let Some(package_item) = doc.get_mut("package") { - if let Some(package_table) = package_item.as_table_mut() { - package_table["name"] = value(safe_name); - if let Some(edition_item) = package_table.get_mut("edition") { - if edition_uses_workspace(edition_item) { - *edition_item = value(embedded::get_workspace_edition()); - } - } + if let Some(package_item) = doc.get_mut("package") + && let Some(package_table) = package_item.as_table_mut() + { + package_table["name"] = value(safe_name); + if let Some(edition_item) = package_table.get_mut("edition") + && edition_uses_workspace(edition_item) + { + *edition_item = value(embedded::get_workspace_edition()); } } - if let Some(deps_item) = doc.get_mut("dependencies") { - if let Some(deps_table) = deps_item.as_table_mut() { - let keys: Vec = deps_table.iter().map(|(k, _)| k.to_string()).collect(); - for key in keys { - if let Some(dep_item) = deps_table.get_mut(&key) { - if dependency_uses_workspace(dep_item) { - if has_path(dep_item) { - if key == "spacetimedb" { - if let Some(version) = embedded::get_workspace_dependency_version(&key) { - set_dependency_version(dep_item, version, true); - } - } else if key == "spacetimedb-sdk" { - set_dependency_version(dep_item, patch_wildcard.as_str(), true); - } - continue; - } - - if uses_workspace(dep_item) { - if let Some(version) = embedded::get_workspace_dependency_version(&key) { - set_dependency_version(dep_item, version, key == "spacetimedb"); - } + if let Some(deps_item) = doc.get_mut("dependencies") + && let Some(deps_table) = deps_item.as_table_mut() + { + let keys: Vec = deps_table.iter().map(|(k, _)| k.to_string()).collect(); + for key in keys { + if let Some(dep_item) = deps_table.get_mut(&key) + && dependency_uses_workspace(dep_item) + { + if has_path(dep_item) { + if key == "spacetimedb" { + if let Some(version) = embedded::get_workspace_dependency_version(&key) { + set_dependency_version(dep_item, version, true); } + } else if key == "spacetimedb-sdk" { + set_dependency_version(dep_item, patch_wildcard.as_str(), true); } + continue; + } + + if uses_workspace(dep_item) + && let Some(version) = embedded::get_workspace_dependency_version(&key) + { + set_dependency_version(dep_item, version, key == "spacetimedb"); } } } @@ -964,20 +964,20 @@ fn find_first_csproj(dir: &Path) -> anyhow::Result> { /// Remove every under any fn remove_all_project_references(project: &mut Element) { for node in project.children.iter_mut() { - if let XMLNode::Element(item_group) = node { - if item_group.name == "ItemGroup" { - item_group - .children - .retain(|n| !matches!(n, XMLNode::Element(el) if el.name == "ProjectReference")); - } + if let XMLNode::Element(item_group) = node + && item_group.name == "ItemGroup" + { + item_group + .children + .retain(|n| !matches!(n, XMLNode::Element(el) if el.name == "ProjectReference")); } } // Optional: prune empty ItemGroups project.children.retain(|n| { - if let XMLNode::Element(el) = n { - if el.name == "ItemGroup" { - return el.children.iter().any(|c| matches!(c, XMLNode::Element(_))); - } + if let XMLNode::Element(el) = n + && el.name == "ItemGroup" + { + return el.children.iter().any(|c| matches!(c, XMLNode::Element(_))); } true }); @@ -987,19 +987,18 @@ fn remove_all_project_references(project: &mut Element) { fn upsert_packageref(project: &mut Element, include: &str, version: &str) { // Try to find an existing PackageReference for node in project.children.iter_mut() { - if let XMLNode::Element(item_group) = node { - if item_group.name == "ItemGroup" { - if let Some(XMLNode::Element(existing)) = item_group.children.iter_mut().find(|n| { - matches!(n, - XMLNode::Element(e) - if e.name == "PackageReference" - && e.attributes.get("Include").map(|v| v == include).unwrap_or(false) - ) - }) { - existing.attributes.insert("Version".to_string(), version.to_string()); - return; - } - } + if let XMLNode::Element(item_group) = node + && item_group.name == "ItemGroup" + && let Some(XMLNode::Element(existing)) = item_group.children.iter_mut().find(|n| { + matches!(n, + XMLNode::Element(e) + if e.name == "PackageReference" + && e.attributes.get("Include").map(|v| v == include).unwrap_or(false) + ) + }) + { + existing.attributes.insert("Version".to_string(), version.to_string()); + return; } } // Otherwise create one in (or create) an ItemGroup @@ -1667,15 +1666,15 @@ fn has_path(item: &Item) -> bool { } fn set_dependency_version(item: &mut Item, version: &str, remove_path: bool) { - if let Item::Value(val) = item { - if let Some(inline) = val.as_inline_table_mut() { - inline.remove("workspace"); - if remove_path { - inline.remove("path"); - } - inline.insert("version", toml_edit::Value::from(version.to_string())); - return; + if let Item::Value(val) = item + && let Some(inline) = val.as_inline_table_mut() + { + inline.remove("workspace"); + if remove_path { + inline.remove("path"); } + inline.insert("version", toml_edit::Value::from(version.to_string())); + return; } if let Item::Table(table) = item { @@ -1766,13 +1765,13 @@ fn install_ai_rules(config: &TemplateConfig, project_path: &Path) -> anyhow::Res /// Strip YAML frontmatter from .mdc files (the --- delimited section at the start) fn strip_mdc_frontmatter(content: &str) -> &str { // Look for frontmatter: starts with --- and ends with --- - if let Some(after_opening) = content.strip_prefix("---") { - if let Some(end_idx) = after_opening.find("\n---") { - // Skip past the closing --- and the newline after it - let remaining = &after_opening[end_idx + 4..]; // 4 for \n--- - // Skip any leading newlines after frontmatter - return remaining.trim_start_matches('\n'); - } + if let Some(after_opening) = content.strip_prefix("---") + && let Some(end_idx) = after_opening.find("\n---") + { + // Skip past the closing --- and the newline after it + let remaining = &after_opening[end_idx + 4..]; // 4 for \n--- + // Skip any leading newlines after frontmatter + return remaining.trim_start_matches('\n'); } content } diff --git a/crates/cli/src/subcommands/logs.rs b/crates/cli/src/subcommands/logs.rs index 4f8ed6a5b01..5ad3baa27d2 100644 --- a/crates/cli/src/subcommands/logs.rs +++ b/crates/cli/src/subcommands/logs.rs @@ -206,28 +206,28 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E let mut need_space_before_filename = false; let mut need_colon_sep = false; let dimmed = ColorSpec::new().set_dimmed(true).clone(); - if let Some(function) = record.function { - if function != SENTINEL { - out.set_color(&dimmed)?; - write!(out, "{function}")?; - out.reset()?; - need_space_before_filename = true; - need_colon_sep = true; - } + if let Some(function) = record.function + && function != SENTINEL + { + out.set_color(&dimmed)?; + write!(out, "{function}")?; + out.reset()?; + need_space_before_filename = true; + need_colon_sep = true; } - if let Some(filename) = record.filename { - if filename != SENTINEL { - out.set_color(&dimmed)?; - if need_space_before_filename { - write!(out, " ")?; - } - write!(out, "{filename}")?; - if let Some(line) = record.line_number { - write!(out, ":{line}")?; - } - out.reset()?; - need_colon_sep = true; + if let Some(filename) = record.filename + && filename != SENTINEL + { + out.set_color(&dimmed)?; + if need_space_before_filename { + write!(out, " ")?; + } + write!(out, "{filename}")?; + if let Some(line) = record.line_number { + write!(out, ":{line}")?; } + out.reset()?; + need_colon_sep = true; } if need_colon_sep { write!(out, ": ")?; diff --git a/crates/cli/src/subcommands/publish.rs b/crates/cli/src/subcommands/publish.rs index 4785cf4ac76..a3db7534609 100644 --- a/crates/cli/src/subcommands/publish.rs +++ b/crates/cli/src/subcommands/publish.rs @@ -385,13 +385,13 @@ pub async fn exec_with_options( let (name_or_identity, parent) = validate_name_and_parent(name_or_identity, parent)?; - if let Some(path_to_project) = path_to_project.as_ref() { - if !path_to_project.exists() { - return Err(anyhow::anyhow!( - "Project path does not exist: {}", - path_to_project.display() - )); - } + if let Some(path_to_project) = path_to_project.as_ref() + && !path_to_project.exists() + { + return Err(anyhow::anyhow!( + "Project path does not exist: {}", + path_to_project.display() + )); } // Decide program file path and read program. diff --git a/crates/client-api/src/lib.rs b/crates/client-api/src/lib.rs index 01b78da9b00..8e34a41a91b 100644 --- a/crates/client-api/src/lib.rs +++ b/crates/client-api/src/lib.rs @@ -168,11 +168,9 @@ impl Host { .await .map_err(log_and_500)??; - if confirmed_read { - if let Some(mut durable_offset) = durable_offset { - let tx_offset = tx_offset.await.map_err(|_| log_and_500("transaction aborted"))?; - durable_offset.wait_for(tx_offset).await.map_err(log_and_500)?; - } + if confirmed_read && let Some(mut durable_offset) = durable_offset { + let tx_offset = tx_offset.await.map_err(|_| log_and_500("transaction aborted"))?; + durable_offset.wait_for(tx_offset).await.map_err(log_and_500)?; } Ok(json) diff --git a/crates/client-api/src/routes/energy.rs b/crates/client-api/src/routes/energy.rs index b2ab94c0c66..a554c418ad9 100644 --- a/crates/client-api/src/routes/energy.rs +++ b/crates/client-api/src/routes/energy.rs @@ -22,7 +22,7 @@ pub async fn get_energy_balance( Path(IdentityParams { identity }): Path, ) -> axum::response::Result { let identity = Identity::from(identity); - get_budget_inner(ctx, &identity).await + get_budget_inner(ctx, identity).await } #[serde_with::serde_as] @@ -66,10 +66,10 @@ pub async fn add_energy( async fn get_budget_inner( ctx: impl ControlStateDelegate, - identity: &Identity, + identity: Identity, ) -> axum::response::Result { let balance = ctx - .get_energy_balance(identity) + .get_energy_balance(&identity) .await .map_err(log_and_500)? .map_or(0, |quanta| quanta.get()); diff --git a/crates/client-api/src/routes/subscribe.rs b/crates/client-api/src/routes/subscribe.rs index 206624fbda8..500e9b1fe35 100644 --- a/crates/client-api/src/routes/subscribe.rs +++ b/crates/client-api/src/routes/subscribe.rs @@ -632,19 +632,17 @@ async fn ws_main_loop( // [`tokio::task::AbortHandle`]s), the reasonable thing to do is to // exit the loop as if the tasks completed normally. res = &mut send_task => { - if let Err(e) = res { - if e.is_panic() { + if let Err(e) = res + && e.is_panic() { panic::resume_unwind(e.into_panic()) } - } break; }, res = &mut recv_task => { - if let Err(e) = res { - if e.is_panic() { + if let Err(e) = res + && e.is_panic() { panic::resume_unwind(e.into_panic()) } - } break; }, @@ -762,15 +760,15 @@ async fn ws_recv_task( while let Some((data, timer)) = recv_handler.next().await { let result = message_handler(data, timer).await; if let Err(e) = result { - if ws_version == WsVersion::V1 { - if let MessageHandleError::Execution(err) = e { - log::error!("{err:#}"); - // If the send task has exited, also exit this recv task. - if unordered_tx.send(err.into()).is_err() { - break; - } - continue; + if ws_version == WsVersion::V1 + && let MessageHandleError::Execution(err) = e + { + log::error!("{err:#}"); + // If the send task has exited, also exit this recv task. + if unordered_tx.send(err.into()).is_err() { + break; } + continue; } log::debug!("Client caused error: {e}"); let close = CloseFrame { @@ -1442,7 +1440,7 @@ async fn ws_encode_message_v2( message: ws_v2::ServerMessage, is_large_message: bool, bsatn_rlb_pool: &BsatnRowListBuilderPool, -) -> (EncodeMetrics, InUseSerializeBuffer, impl Iterator) { +) -> (EncodeMetrics, InUseSerializeBuffer, impl Iterator + use<>) { let start = Instant::now(); let (in_use, data) = if is_large_message { diff --git a/crates/codegen/src/rust.rs b/crates/codegen/src/rust.rs index f4e3ec1996c..fd89c20eb62 100644 --- a/crates/codegen/src/rust.rs +++ b/crates/codegen/src/rust.rs @@ -71,28 +71,27 @@ impl __sdk::InModule for {type_name} {{ // Do not implement query col types for nested types. // as querying is only supported on top-level table row types. let name = type_ref_name(module, typ.ty); - let implemented = if let Some(table) = module + let implemented = match module .tables() .find(|t| type_ref_name(module, t.product_type_ref) == name) { - implement_query_col_types_for_table_struct(module, out, table) - .expect("failed to implement query col types"); - out.newline(); - true - } else { - false + Some(table) => { + implement_query_col_types_for_table_struct(module, out, table) + .expect("failed to implement query col types"); + out.newline(); + true + } + _ => false, }; - if !implemented { - if let Some(type_ref) = module + if !implemented + && let Some(type_ref) = module .views() .map(|v| v.product_type_ref) .find(|type_ref| type_ref_name(module, *type_ref) == name) - { - implement_query_col_types_for_struct(module, out, type_ref) - .expect("failed to implement query col types"); - out.newline(); - } + { + implement_query_col_types_for_struct(module, out, type_ref).expect("failed to implement query col types"); + out.newline(); } vec![OutputFile { diff --git a/crates/codegen/src/util.rs b/crates/codegen/src/util.rs index 135fdd746dc..3728caa7b65 100644 --- a/crates/codegen/src/util.rs +++ b/crates/codegen/src/util.rs @@ -194,7 +194,7 @@ pub(super) fn iter_unique_cols<'a>( constraints[&ColList::from(field.col_pos)] .has_unique() .then(|| { - let res @ (_, ref ty) = &product_def.elements[field.col_pos.idx()]; + let res @ (_, ty) = &product_def.elements[field.col_pos.idx()]; is_type_filterable(typespace, ty).then_some(res) }) .flatten() diff --git a/crates/commitlog/src/commitlog.rs b/crates/commitlog/src/commitlog.rs index 03c590e4950..ad63043b6f6 100644 --- a/crates/commitlog/src/commitlog.rs +++ b/crates/commitlog/src/commitlog.rs @@ -311,7 +311,7 @@ impl Generic { &self, offset: u64, decoder: &'a D, - ) -> impl Iterator, D::Error>> + 'a + ) -> impl Iterator, D::Error>> + 'a + use<'a, D, R, T> where D: Decoder, D::Error: From, @@ -347,10 +347,10 @@ impl Generic { impl Drop for Generic { fn drop(&mut self) { - if !self.panicked { - if let Err(e) = self.head.commit() { - warn!("failed to commit on drop: {e}"); - } + if !self.panicked + && let Err(e) = self.head.commit() + { + warn!("failed to commit on drop: {e}"); } } } diff --git a/crates/commitlog/src/lib.rs b/crates/commitlog/src/lib.rs index 1e7a8c0047e..67baec24a81 100644 --- a/crates/commitlog/src/lib.rs +++ b/crates/commitlog/src/lib.rs @@ -307,7 +307,7 @@ impl Commitlog { /// This means that, when this iterator yields an `Err` value, the consumer /// may want to check if the iterator is exhausted (by calling `next()`) /// before treating the `Err` value as an application error. - pub fn commits(&self) -> impl Iterator> { + pub fn commits(&self) -> impl Iterator> + use { self.commits_from(0) } @@ -320,7 +320,7 @@ impl Commitlog { /// Note that the first [`StoredCommit`] yielded is the first commit /// containing the given transaction offset, i.e. its `min_tx_offset` may be /// smaller than `offset`. - pub fn commits_from(&self, offset: u64) -> impl Iterator> { + pub fn commits_from(&self, offset: u64) -> impl Iterator> + use { self.inner.read().unwrap().commits_from(offset) } @@ -459,7 +459,10 @@ impl Commitlog { /// This means that, when this iterator yields an `Err` value, the consumer /// may want to check if the iterator is exhausted (by calling `next()`) /// before treating the `Err` value as an application error. - pub fn transactions<'a, D>(&self, de: &'a D) -> impl Iterator, D::Error>> + 'a + pub fn transactions<'a, D>( + &self, + de: &'a D, + ) -> impl Iterator, D::Error>> + 'a + use<'a, D, T> where D: Decoder, D::Error: From, @@ -478,7 +481,7 @@ impl Commitlog { &self, offset: u64, de: &'a D, - ) -> impl Iterator, D::Error>> + 'a + ) -> impl Iterator, D::Error>> + 'a + use<'a, D, T> where D: Decoder, D::Error: From, diff --git a/crates/commitlog/src/stream/writer.rs b/crates/commitlog/src/stream/writer.rs index 83f37a9f1d6..b2f2b0c279a 100644 --- a/crates/commitlog/src/stream/writer.rs +++ b/crates/commitlog/src/stream/writer.rs @@ -228,13 +228,16 @@ where segment, offset_index: index, } - } else if let Some(current_segment) = self.current_segment.take() { - current_segment } else { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "no current segment, expected segment header", - )); + match self.current_segment.take() { + Some(current_segment) => current_segment, + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "no current segment, expected segment header", + )); + } + } }; // What follows is commits to be written to `current_segment`, diff --git a/crates/commitlog/src/tests/partial.rs b/crates/commitlog/src/tests/partial.rs index e4020f93006..0f2f27055b1 100644 --- a/crates/commitlog/src/tests/partial.rs +++ b/crates/commitlog/src/tests/partial.rs @@ -334,13 +334,13 @@ where total_txs += 1; } let res = log.commit(); - if let Err(Some(os)) = res.as_ref().map_err(|e| e.raw_os_error()) { - if os == ENOSPC { - debug!("fill: ignoring ENOSPC"); - seen_enospc = true; - log.commit().unwrap(); - continue; - } + if let Err(Some(os)) = res.as_ref().map_err(|e| e.raw_os_error()) + && os == ENOSPC + { + debug!("fill: ignoring ENOSPC"); + seen_enospc = true; + log.commit().unwrap(); + continue; } res.unwrap(); } diff --git a/crates/commitlog/tests/streaming/mod.rs b/crates/commitlog/tests/streaming/mod.rs index 0474ae75b30..2f9b2547abf 100644 --- a/crates/commitlog/tests/streaming/mod.rs +++ b/crates/commitlog/tests/streaming/mod.rs @@ -214,7 +214,7 @@ fn repo(at: &Path) -> repo::Fs { repo::Fs::new(CommitLogDir::from_path_unchecked(at), None).unwrap() } -fn create_reader(path: &Path, range: impl RangeBounds) -> impl AsyncBufRead { +fn create_reader>(path: &Path, range: R) -> impl AsyncBufRead + use { BufReader::new(StreamReader::new(stream::commits( repo::Fs::new(CommitLogDir::from_path_unchecked(path), None).unwrap(), range, diff --git a/crates/core/src/auth/token_validation.rs b/crates/core/src/auth/token_validation.rs index 9fa5fed7418..c38d732882d 100644 --- a/crates/core/src/auth/token_validation.rs +++ b/crates/core/src/auth/token_validation.rs @@ -167,14 +167,14 @@ impl TokenValidator for BasicTokenValidator { async fn validate_token(&self, token: &str) -> Result { // This validates everything but the issuer. let claims = self.public_key.validate_token(token).await?; - if let Some(expected_issuer) = &self.issuer { - if *claims.issuer != **expected_issuer { - return Err(TokenValidationError::Other(anyhow::anyhow!( - "Issuer mismatch: got {:?}, expected {:?}", - claims.issuer, - expected_issuer - ))); - } + if let Some(expected_issuer) = &self.issuer + && *claims.issuer != **expected_issuer + { + return Err(TokenValidationError::Other(anyhow::anyhow!( + "Issuer mismatch: got {:?}, expected {:?}", + claims.issuer, + expected_issuer + ))); } Ok(claims) } diff --git a/crates/core/src/database_logger.rs b/crates/core/src/database_logger.rs index 0ab92742923..0e202229dea 100644 --- a/crates/core/src/database_logger.rs +++ b/crates/core/src/database_logger.rs @@ -526,7 +526,7 @@ impl DatabaseLoggerWorker { } } - fn subscribe(&self) -> impl Stream { + fn subscribe(&self) -> impl Stream + use { BroadcastStream::new(self.broadcast.subscribe()).filter_map(move |x| { future::ready(match x { Ok(chunk) => Some(chunk), diff --git a/crates/core/src/db/relational_db.rs b/crates/core/src/db/relational_db.rs index 75fb75cbce7..f8a511f8e5f 100644 --- a/crates/core/src/db/relational_db.rs +++ b/crates/core/src/db/relational_db.rs @@ -864,12 +864,11 @@ impl RelationalDB { /// This requires a small amount of additional logic when restoring from a snapshot /// to ensure we don't restore a snapshot more recent than the durable TX offset. fn maybe_do_snapshot(&self, tx_data: &TxData) { - if let Some(snapshot_worker) = &self.snapshot_worker { - if let Some(tx_offset) = tx_data.tx_offset() { - if tx_offset % SNAPSHOT_FREQUENCY == 0 { - snapshot_worker.request_snapshot(); - } - } + if let Some(snapshot_worker) = &self.snapshot_worker + && let Some(tx_offset) = tx_data.tx_offset() + && tx_offset % SNAPSHOT_FREQUENCY == 0 + { + snapshot_worker.request_snapshot(); } } @@ -1404,7 +1403,7 @@ impl RelationalDB { TableId, Bound, Bound, - impl Iterator>, + impl Iterator> + use<'a>, ), DBError, > { @@ -1416,7 +1415,7 @@ impl RelationalDB { tx: &'a MutTx, index_id: IndexId, point: &[u8], - ) -> Result<(TableId, AlgebraicValue, impl Iterator>), DBError> { + ) -> Result<(TableId, AlgebraicValue, impl Iterator> + use<'a>), DBError> { Ok(tx.index_scan_point(index_id, point)?) } @@ -1779,7 +1778,7 @@ pub async fn local_durability( /// Open a [History] for replay from the local durable state. /// /// Currently, this is simply a read-only copy of the commitlog. -pub async fn local_history(replica_dir: &ReplicaDir) -> io::Result> { +pub async fn local_history(replica_dir: &ReplicaDir) -> io::Result + use<>> { let commitlog_dir = replica_dir.commit_log(); asyncify(move || Commitlog::open(commitlog_dir, <_>::default(), None)).await } @@ -1799,10 +1798,10 @@ pub async fn snapshot_watching_commitlog_compressor( let snapshot_offset = *snapshot_rx.borrow_and_update(); let durability = durability.clone(); - if let Some(snap_tx) = &mut snap_tx { - if let Err(err) = snap_tx.try_send(snapshot_offset) { - tracing::warn!("failed to send offset {snapshot_offset} after snapshot creation: {err}"); - } + if let Some(snap_tx) = &mut snap_tx + && let Err(err) = snap_tx.try_send(snapshot_offset) + { + tracing::warn!("failed to send offset {snapshot_offset} after snapshot creation: {err}"); } let res: io::Result<_> = asyncify(move || { @@ -1835,10 +1834,10 @@ pub async fn snapshot_watching_commitlog_compressor( }; prev_snapshot_offset = snapshot_offset; - if let Some((clog_tx, last_compressed_segment)) = clog_tx.as_mut().zip(last_compressed_segment) { - if let Err(err) = clog_tx.try_send(last_compressed_segment) { - tracing::warn!("failed to send offset {last_compressed_segment} after compression: {err}"); - } + if let Some((clog_tx, last_compressed_segment)) = clog_tx.as_mut().zip(last_compressed_segment) + && let Err(err) = clog_tx.try_send(last_compressed_segment) + { + tracing::warn!("failed to send offset {last_compressed_segment} after compression: {err}"); } } } diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index 4c0b3439175..8ebee4ce4af 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -165,10 +165,10 @@ pub enum DBError { impl DBError { pub fn get_auth_error(&self) -> Option<&ErrorLang> { - if let Self::VmUser(err) = self { - if err.kind == ErrorKind::Unauthorized { - return Some(err); - } + if let Self::VmUser(err) = self + && err.kind == ErrorKind::Unauthorized + { + return Some(err); } None } diff --git a/crates/core/src/host/host_controller.rs b/crates/core/src/host/host_controller.rs index d03edb4bd6e..87f332756c8 100644 --- a/crates/core/src/host/host_controller.rs +++ b/crates/core/src/host/host_controller.rs @@ -272,11 +272,11 @@ impl HostController { ) -> anyhow::Result> { // Try a read lock first. { - if let Ok(guard) = self.acquire_read_lock(replica_id).await { - if let Some(host) = &*guard { - trace!("cached host {}/{}", database.database_identity, replica_id); - return Ok(host.module.subscribe()); - } + if let Ok(guard) = self.acquire_read_lock(replica_id).await + && let Some(host) = &*guard + { + trace!("cached host {}/{}", database.database_identity, replica_id); + return Ok(host.module.subscribe()); } } @@ -615,7 +615,7 @@ impl HostController { /// On-panic callback passed to [`ModuleHost`]s created by this controller. /// /// Removes the module with the given `replica_id` from this controller. - fn unregister_fn(&self, replica_id: u64) -> impl Fn() + Send + Sync + 'static { + fn unregister_fn(&self, replica_id: u64) -> impl Fn() + Send + Sync + 'static + use<> { let hosts = Arc::downgrade(&self.hosts); move || { if let Some(hosts) = hosts.upgrade() { diff --git a/crates/core/src/host/instance_env.rs b/crates/core/src/host/instance_env.rs index a3f5bb9299c..c8e0827aa24 100644 --- a/crates/core/src/host/instance_env.rs +++ b/crates/core/src/host/instance_env.rs @@ -809,7 +809,7 @@ impl InstanceEnv { &mut self, request: st_http::Request, body: bytes::Bytes, - ) -> Result>, NodesError> { + ) -> Result> + use<>, NodesError> { if self.in_tx() { // If we're holding a transaction open, refuse to perform this blocking operation. return Err(NodesError::WouldBlockTransaction(super::AbiCall::ProcedureHttpRequest)); diff --git a/crates/core/src/host/module_host.rs b/crates/core/src/host/module_host.rs index 39552b1385b..2489c1e4261 100644 --- a/crates/core/src/host/module_host.rs +++ b/crates/core/src/host/module_host.rs @@ -1114,7 +1114,7 @@ impl ModuleHost { }) } - fn start_call_timer(&self, label: &str) -> ScopeGuard<(), impl FnOnce(())> { + fn start_call_timer(&self, label: &str) -> ScopeGuard<(), impl FnOnce(()) + use<>> { // Record the time until our function starts running. let queue_timer = WORKER_METRICS .reducer_wait_time @@ -1312,10 +1312,8 @@ impl ModuleHost { // Decrement the number of subscribers for each view this caller is subscribed to let dec_view_subscribers = |tx: &mut MutTxId| { - if drop_view_subscribers { - if let Err(err) = tx.unsubscribe_views(caller_identity) { - log::error!("`call_identity_disconnected`: failed to delete client view data: {err}"); - } + if drop_view_subscribers && let Err(err) = tx.unsubscribe_views(caller_identity) { + log::error!("`call_identity_disconnected`: failed to delete client view data: {err}"); } }; diff --git a/crates/core/src/host/scheduler.rs b/crates/core/src/host/scheduler.rs index 76203fa23c7..75917b10c34 100644 --- a/crates/core/src/host/scheduler.rs +++ b/crates/core/src/host/scheduler.rs @@ -499,21 +499,24 @@ fn delete_scheduled_function_row_with_tx( id: ScheduledFunctionId, ) -> Option { if let Ok(Some(schedule_row)) = get_schedule_row_mut(&tx, db, id) { - if let Ok(schedule_at) = read_schedule_at(&schedule_row, id.at_column) { - // If the schedule is an interval, we handle it as a repeated schedule - if let ScheduleAt::Interval(_) = schedule_at { - return Some(schedule_at); + match read_schedule_at(&schedule_row, id.at_column) { + Ok(schedule_at) => { + // If the schedule is an interval, we handle it as a repeated schedule + if let ScheduleAt::Interval(_) = schedule_at { + return Some(schedule_at); + } + let row_ptr = schedule_row.pointer(); + db.delete(&mut tx, id.table_id, [row_ptr]); + + commit_and_broadcast_deletion_event(tx, module_info); + } + _ => { + log::debug!( + "Failed to read 'scheduled_at' from row: table_id {}, schedule_id {}", + id.table_id, + id.schedule_id + ); } - let row_ptr = schedule_row.pointer(); - db.delete(&mut tx, id.table_id, [row_ptr]); - - commit_and_broadcast_deletion_event(tx, module_info); - } else { - log::debug!( - "Failed to read 'scheduled_at' from row: table_id {}, schedule_id {}", - id.table_id, - id.schedule_id - ); } } None diff --git a/crates/core/src/host/v8/syscall/v2.rs b/crates/core/src/host/v8/syscall/v2.rs index 8aea8789813..54a74ac2b61 100644 --- a/crates/core/src/host/v8/syscall/v2.rs +++ b/crates/core/src/host/v8/syscall/v2.rs @@ -443,22 +443,22 @@ pub(super) fn call_call_reducer<'scope>( // and overwrite the previously caught exception, which is our desired behavior. // If we're terminating execution, don't try to check `instanceof`. - if scope.can_continue() { - if let Some(exc) = scope.exception().and_then(|exc| exc.try_cast::().ok()) { - // if (exc instanceof SenderError) - if exc - .instance_of(scope, hooks.sender_error_class.unwrap().into()) - .ok_or_else(exception_already_thrown)? - { - // let message = String(exc.message) - let key = str_from_ident!(message).string(scope); - let message = exc.get(scope, key.into()).ok_or_else(exception_already_thrown)?; - let message = message.to_string(scope).ok_or_else(exception_already_thrown)?; - return Ok(Err(message.to_rust_string_lossy(scope).into())); - } - } + if scope.can_continue() + && let Some(exc) = scope.exception() + && let Ok(exc) = exc.try_cast::() + // if (exc instanceof SenderError) + && exc + .instance_of(scope, hooks.sender_error_class.unwrap().into()) + .ok_or_else(exception_already_thrown)? + { + // let message = String(exc.message) + let key = str_from_ident!(message).string(scope); + let message = exc.get(scope, key.into()).ok_or_else(exception_already_thrown)?; + let message = message.to_string(scope).ok_or_else(exception_already_thrown)?; + Ok(Err(message.to_rust_string_lossy(scope).into())) + } else { + Err(e) } - Err(e) } } } diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs index eb17de1e8a4..f801f64d177 100644 --- a/crates/core/src/sql/compiler.rs +++ b/crates/core/src/sql/compiler.rs @@ -74,16 +74,17 @@ fn compile_select(table: From, project: Box<[Column]>, selection: Option not_found.push(field), Err(err) => return Err(err), }, - Column::QualifiedWildcard { table: name } => { - if let Some(t) = table.iter_tables().find(|x| *x.table_name == name) { + Column::QualifiedWildcard { table: name } => match table.iter_tables().find(|x| *x.table_name == name) { + Some(t) => { for c in t.columns().iter() { col_ids.push(FieldName::new(t.table_id, c.col_pos).into()); } qualified_wildcards.push(t.table_id); - } else { + } + _ => { return Err(PlanError::TableNotFoundQualified { expect: name }); } - } + }, Column::Wildcard => {} } } diff --git a/crates/core/src/sql/type_check.rs b/crates/core/src/sql/type_check.rs index e302eeabe95..12324686407 100644 --- a/crates/core/src/sql/type_check.rs +++ b/crates/core/src/sql/type_check.rs @@ -95,16 +95,17 @@ fn resolve_type(field: &FieldExpr, ty: AlgebraicType) -> Result Result<(), PlanError> { /// Patch the type of the field if the type is an `Identity`, `ConnectionId` or `Enum` fn patch_type(lhs: &FieldOp, ty_lhs: &mut Typed, ty_rhs: &Typed) -> Result<(), PlanError> { - if let FieldOp::Field(lhs_field) = lhs { - if let Some(ty) = ty_rhs.ty() { - if ty.is_sum() || ty.as_product().is_some_and(|x| x.is_special()) { - ty_lhs.set_ty(resolve_type(lhs_field, ty.clone())?); - } - } + if let FieldOp::Field(lhs_field) = lhs + && let Some(ty) = ty_rhs.ty() + && (ty.is_sum() || ty.as_product().is_some_and(|x| x.is_special())) + { + ty_lhs.set_ty(resolve_type(lhs_field, ty.clone())?); } Ok(()) } diff --git a/crates/core/src/startup.rs b/crates/core/src/startup.rs index 8f55321eeeb..c73585c44d8 100644 --- a/crates/core/src/startup.rs +++ b/crates/core/src/startup.rs @@ -137,13 +137,13 @@ fn reload_config(conf_file: &ConfigToml, reload_handle: &reload::Handle prev) { - log::info!("reloading log config..."); - prev_time = Some(modified); - if reload_handle.reload(parse_from_file(conf_file)).is_err() { - break; - } + if let Ok(modified) = conf_file.metadata().and_then(|m| m.modified()) + && prev_time.is_none_or(|prev| modified > prev) + { + log::info!("reloading log config..."); + prev_time = Some(modified); + if reload_handle.reload(parse_from_file(conf_file)).is_err() { + break; } } } diff --git a/crates/core/src/subscription/mod.rs b/crates/core/src/subscription/mod.rs index b1ec6fa8acf..40d6d712504 100644 --- a/crates/core/src/subscription/mod.rs +++ b/crates/core/src/subscription/mod.rs @@ -270,27 +270,31 @@ pub fn execute_plans( let start_time = std::time::Instant::now(); let result = if plan.returns_view_table() { - if let Some(schema) = plan.return_table() { - let pipelined_plan = PipelinedProject::from(plan.clone()); - let view_plan = ViewProject::new(pipelined_plan, schema.num_cols(), schema.num_private_cols()); - collect_table_update_for_view( - &[view_plan], - table_id, - table_name.clone(), - tx, - update_type, - rlb_pool, - )? - } else { - let pipelined_plan = PipelinedProject::from(plan.clone()); - collect_table_update( - &[pipelined_plan], - table_id, - table_name.clone(), - tx, - update_type, - rlb_pool, - )? + match plan.return_table() { + Some(schema) => { + let pipelined_plan = PipelinedProject::from(plan.clone()); + let view_plan = + ViewProject::new(pipelined_plan, schema.num_cols(), schema.num_private_cols()); + collect_table_update_for_view( + &[view_plan], + table_id, + table_name.clone(), + tx, + update_type, + rlb_pool, + )? + } + _ => { + let pipelined_plan = PipelinedProject::from(plan.clone()); + collect_table_update( + &[pipelined_plan], + table_id, + table_name.clone(), + tx, + update_type, + rlb_pool, + )? + } } } else { let pipelined_plan = PipelinedProject::from(plan.clone()); diff --git a/crates/core/src/subscription/module_subscription_actor.rs b/crates/core/src/subscription/module_subscription_actor.rs index c3248ae979f..9f782599376 100644 --- a/crates/core/src/subscription/module_subscription_actor.rs +++ b/crates/core/src/subscription/module_subscription_actor.rs @@ -1056,20 +1056,26 @@ impl ModuleSubscriptions { let mut new_queries = 0; for (sql, hash, hash_with_param) in query_hashes { - if let Some(unit) = guard.query(&hash) { - plans.push(unit); - } else if let Some(unit) = guard.query(&hash_with_param) { - plans.push(unit); - } else { - plans.push(Arc::new( - compile_query_with_hashes(&auth, &*mut_tx, sql, hash, hash_with_param).map_err(|err| { - DBError::WithSql { - error: Box::new(DBError::Other(err.into())), - sql: sql.into(), - } - })?, - )); - new_queries += 1; + match guard.query(&hash) { + Some(unit) => { + plans.push(unit); + } + _ => match guard.query(&hash_with_param) { + Some(unit) => { + plans.push(unit); + } + _ => { + plans.push(Arc::new( + compile_query_with_hashes(&auth, &*mut_tx, sql, hash, hash_with_param).map_err(|err| { + DBError::WithSql { + error: Box::new(DBError::Other(err.into())), + sql: sql.into(), + } + })?, + )); + new_queries += 1; + } + }, } } diff --git a/crates/core/src/subscription/module_subscription_manager.rs b/crates/core/src/subscription/module_subscription_manager.rs index 4cdacd39ff4..7d6223bf8ce 100644 --- a/crates/core/src/subscription/module_subscription_manager.rs +++ b/crates/core/src/subscription/module_subscription_manager.rs @@ -97,7 +97,7 @@ impl Plan { } /// Returns the index ids from which this subscription reads - pub fn index_ids(&self) -> impl Iterator { + pub fn index_ids(&self) -> impl Iterator + use<> { self.plans .iter() .flat_map(|plan| plan.index_ids()) @@ -115,7 +115,7 @@ impl Plan { } /// Return the search arguments for this query - fn search_args(&self) -> impl Iterator { + fn search_args(&self) -> impl Iterator + use<> { let mut args = HashSet::new(); for arg in self .plans @@ -250,7 +250,7 @@ impl QueryState { } /// Return the search arguments for this query - fn search_args(&self) -> impl Iterator { + fn search_args(&self) -> impl Iterator + use<> { self.query.search_args() } } @@ -406,16 +406,16 @@ impl QueriedTableIndexIds { /// Note, different queries may read from the same index. /// Hence we only remove this key from the map if its ref count goes to zero. pub fn delete_index_id(&mut self, table_id: TableId, index_id: IndexId) { - if let Some(ids) = self.ids.get_mut(&table_id) { - if let Some(n) = ids.get_mut(&index_id) { - *n -= 1; + if let Some(ids) = self.ids.get_mut(&table_id) + && let Some(n) = ids.get_mut(&index_id) + { + *n -= 1; - if *n == 0 { - ids.remove(&index_id); + if *n == 0 { + ids.remove(&index_id); - if ids.is_empty() { - self.ids.remove(&table_id); - } + if ids.is_empty() { + self.ids.remove(&table_id); } } } @@ -466,14 +466,14 @@ impl JoinEdges { /// If this query has any join edges, remove them from the map. fn remove_query(&mut self, query: &Query) { for (edge, rhs_val) in query.join_edges() { - if let Some(values) = self.edges.get_mut(&edge) { - if let Some(hashes) = values.get_mut(&rhs_val) { - hashes.remove(&query.hash); - if hashes.is_empty() { - values.remove(&rhs_val); - if values.is_empty() { - self.edges.remove(&edge); - } + if let Some(values) = self.edges.get_mut(&edge) + && let Some(hashes) = values.get_mut(&rhs_val) + { + hashes.remove(&query.hash); + if hashes.is_empty() { + values.remove(&rhs_val); + if values.is_empty() { + self.edges.remove(&edge); } } } @@ -828,10 +828,10 @@ impl SubscriptionManager { /// Remove any clients that have been marked for removal pub fn remove_dropped_clients(&mut self) { for id in self.clients.keys().copied().collect::>() { - if let Some(client) = self.clients.get(&id) { - if client.dropped.load(Ordering::Relaxed) { - self.remove_all_subscriptions(&id); - } + if let Some(client) = self.clients.get(&id) + && client.dropped.load(Ordering::Relaxed) + { + self.remove_all_subscriptions(&id); } } } @@ -1284,14 +1284,14 @@ impl SubscriptionManager { fn queries_for_table_update<'a>( &'a self, table_update: &'a DatabaseTableUpdate, - find_rhs_val: &impl Fn(&JoinEdge, &ProductValue) -> Option, + find_rhs_val: impl Fn(&JoinEdge, &ProductValue) -> Option, ) -> impl Iterator { let mut queries = HashSet::new(); for hash in table_update .inserts .iter() .chain(table_update.deletes.iter()) - .flat_map(|row| self.queries_for_row(table_update.table_id, row, find_rhs_val)) + .flat_map(|row| self.queries_for_row(table_update.table_id, row, &find_rhs_val)) { queries.insert(hash); } @@ -1441,7 +1441,7 @@ impl SubscriptionManager { .iter() .filter(|table| !table.inserts.is_empty() || !table.deletes.is_empty()) .flat_map(|table_update| { - self.queries_for_table_update(table_update, &|edge, row| find_rhs_val(edge, row, tx)) + self.queries_for_table_update(table_update, |edge, row| find_rhs_val(edge, row, tx)) }) // deduplicate queries by their hash .filter({ @@ -1547,7 +1547,7 @@ impl SubscriptionManager { .iter() .filter(|table| !table.inserts.is_empty() || !table.deletes.is_empty()) .flat_map(|table_update| { - self.queries_for_table_update(table_update, &|edge, row| find_rhs_val(edge, row, tx)) + self.queries_for_table_update(table_update, |edge, row| find_rhs_val(edge, row, tx)) }) // deduplicate queries by their hash .filter({ @@ -2103,20 +2103,18 @@ impl SendWorker { } } } - if !sent_to_caller { - if let Some(caller) = caller { - let server_message = ws_v2::ServerMessage::ReducerResult(ws_v2::ReducerResult { - request_id: event.request_id.unwrap(), // TODO: Handle error here. - timestamp: event.timestamp, - result: ws_v2::ReducerOutcome::Ok(ws_v2::ReducerOk { - ret_value: event.reducer_return_value.clone().unwrap_or_default(), - transaction_update: ws_v2::TransactionUpdate { - query_sets: vec![].into_boxed_slice(), - }, - }), - }); - send_to_client(&caller, Some(tx_offset), OutboundMessage::V2(server_message)); - } + if !sent_to_caller && let Some(caller) = caller { + let server_message = ws_v2::ServerMessage::ReducerResult(ws_v2::ReducerResult { + request_id: event.request_id.unwrap(), // TODO: Handle error here. + timestamp: event.timestamp, + result: ws_v2::ReducerOutcome::Ok(ws_v2::ReducerOk { + ret_value: event.reducer_return_value.clone().unwrap_or_default(), + transaction_update: ws_v2::TransactionUpdate { + query_sets: vec![].into_boxed_slice(), + }, + }), + }); + send_to_client(&caller, Some(tx_offset), OutboundMessage::V2(server_message)); } } @@ -2804,7 +2802,7 @@ mod tests { }; let hashes = subscriptions - .queries_for_table_update(&table_update, &|_, _| None) + .queries_for_table_update(&table_update, |_, _| None) .collect::>(); assert!(hashes.len() == 3); @@ -2822,7 +2820,7 @@ mod tests { }; let hashes = subscriptions - .queries_for_table_update(&table_update, &|_, _| None) + .queries_for_table_update(&table_update, |_, _| None) .collect::>(); assert!(hashes.len() == 1); @@ -2863,7 +2861,7 @@ mod tests { }; let hashes = subscriptions - .queries_for_table_update(&table_update, &|_, _| None) + .queries_for_table_update(&table_update, |_, _| None) .cloned() .collect::>(); @@ -2879,7 +2877,7 @@ mod tests { }; let hashes = subscriptions - .queries_for_table_update(&table_update, &|_, _| None) + .queries_for_table_update(&table_update, |_, _| None) .cloned() .collect::>(); @@ -2895,7 +2893,7 @@ mod tests { }; let hashes = subscriptions - .queries_for_table_update(&table_update, &|_, _| None) + .queries_for_table_update(&table_update, |_, _| None) .cloned() .collect::>(); diff --git a/crates/core/src/subscription/subscription.rs b/crates/core/src/subscription/subscription.rs index b27dd5e1ce1..528aae82033 100644 --- a/crates/core/src/subscription/subscription.rs +++ b/crates/core/src/subscription/subscription.rs @@ -896,7 +896,7 @@ mod tests { assert_eq!(virtual_plan.head(), expr.head()); assert_eq!(virtual_plan.query.len(), 1); let incr_join = &virtual_plan.query[0]; - let Query::JoinInner(ref incr_join) = incr_join else { + let Query::JoinInner(incr_join) = incr_join else { panic!("expected an inner semijoin, but got {incr_join:#?}"); }; assert!(incr_join.rhs.source.is_mem_table()); diff --git a/crates/core/src/util/jobs.rs b/crates/core/src/util/jobs.rs index d58b856c023..ad925f162a7 100644 --- a/crates/core/src/util/jobs.rs +++ b/crates/core/src/util/jobs.rs @@ -252,10 +252,10 @@ impl CorePinner { /// Repin the current thread to the new appropriate core, if it's changed /// since the last call to `pin_now()` or `pin_if_changed()`. pub fn pin_if_changed(&mut self) { - if let Some(move_core_rx) = &mut self.move_core_rx { - if let Ok(true) = move_core_rx.has_changed() { - Self::do_pin(move_core_rx); - } + if let Some(move_core_rx) = &mut self.move_core_rx + && let Ok(true) = move_core_rx.has_changed() + { + Self::do_pin(move_core_rx); } } @@ -382,10 +382,10 @@ pub struct LoadBalanceOnDropGuard { impl Drop for LoadBalanceOnDropGuard { fn drop(&mut self) { - if let Some((manager, database_executor_id)) = &self.inner { - if let Some(cores) = manager.upgrade() { - cores.lock().unwrap().deallocate(*database_executor_id); - } + if let Some((manager, database_executor_id)) = &self.inner + && let Some(cores) = manager.upgrade() + { + cores.lock().unwrap().deallocate(*database_executor_id); } } } diff --git a/crates/core/src/vm.rs b/crates/core/src/vm.rs index e995cf72cb3..62d30dc32a4 100644 --- a/crates/core/src/vm.rs +++ b/crates/core/src/vm.rs @@ -466,17 +466,17 @@ pub fn check_row_limit( row_est: impl Fn(&Query, &TxId) -> u64, auth: &AuthCtx, ) -> Result<(), DBError> { - if !auth.exceed_row_limit() { - if let Some(limit) = db.row_limit(tx)? { - let mut estimate: u64 = 0; - for query in queries { - estimate = estimate.saturating_add(row_est(query, tx)); - } - if estimate > limit { - return Err(DBError::Other(anyhow::anyhow!( - "Estimated cardinality ({estimate} rows) exceeds limit ({limit} rows)" - ))); - } + if !auth.exceed_row_limit() + && let Some(limit) = db.row_limit(tx)? + { + let mut estimate: u64 = 0; + for query in queries { + estimate = estimate.saturating_add(row_est(query, tx)); + } + if estimate > limit { + return Err(DBError::Other(anyhow::anyhow!( + "Estimated cardinality ({estimate} rows) exceeds limit ({limit} rows)" + ))); } } Ok(()) diff --git a/crates/data-structures/src/slim_slice.rs b/crates/data-structures/src/slim_slice.rs index 38fbebef2e7..0255e76fce6 100644 --- a/crates/data-structures/src/slim_slice.rs +++ b/crates/data-structures/src/slim_slice.rs @@ -256,10 +256,12 @@ impl SlimRawSlice { /// The caller must ensure that `ptr != NULL`. #[inline] const unsafe fn from_len_ptr(len: usize, ptr: *mut T) -> Self { - // SAFETY: caller ensured that `!ptr.is_null()`. - let ptr = NonNull::new_unchecked(ptr); - let len = len as u32; - Self { ptr, len } + unsafe { + // SAFETY: caller ensured that `!ptr.is_null()`. + let ptr = NonNull::new_unchecked(ptr); + let len = len as u32; + Self { ptr, len } + } } } @@ -319,13 +321,15 @@ mod slim_slice_box { #[inline] // Clippy doesn't seem to consider unsafe code here. pub unsafe fn from_boxed_unchecked(boxed: Box<[T]>) -> Self { - let len = boxed.len(); - let ptr = Box::into_raw(boxed) as *mut T; - // SAFETY: `Box`'s ptr was a `NonNull` already. - // and our caller has promised that `boxed.len() <= u32::MAX`. - let raw = SlimRawSlice::from_len_ptr(len, ptr); - let owned = PhantomData; - Self { raw, owned } + unsafe { + let len = boxed.len(); + let ptr = Box::into_raw(boxed) as *mut T; + // SAFETY: `Box`'s ptr was a `NonNull` already. + // and our caller has promised that `boxed.len() <= u32::MAX`. + let raw = SlimRawSlice::from_len_ptr(len, ptr); + let owned = PhantomData; + Self { raw, owned } + } } /// Returns a limited shared slice to this boxed slice. @@ -885,13 +889,15 @@ mod slim_slice { /// /// SAFETY: `slice.len() <= u32::MAX` must hold. pub(super) const unsafe fn from_slice_unchecked(slice: &'a [T]) -> Self { - let len = slice.len(); - let ptr = slice.as_ptr().cast_mut(); - // SAFETY: `&mut [T]` implies that the pointer is non-null. - let raw = SlimRawSlice::from_len_ptr(len, ptr); - // SAFETY: Our length invariant is satisfied by the caller. - let covariant = PhantomData; - Self { raw, covariant } + unsafe { + let len = slice.len(); + let ptr = slice.as_ptr().cast_mut(); + // SAFETY: `&mut [T]` implies that the pointer is non-null. + let raw = SlimRawSlice::from_len_ptr(len, ptr); + // SAFETY: Our length invariant is satisfied by the caller. + let covariant = PhantomData; + Self { raw, covariant } + } } } @@ -1067,12 +1073,14 @@ impl<'a, T> SlimSliceMut<'a, T> { /// SAFETY: `slice.len() <= u32::MAX` must hold. #[inline] unsafe fn from_slice_unchecked(slice: &'a mut [T]) -> Self { - // SAFETY: `&mut [T]` implies that the pointer is non-null. - let raw = SlimRawSlice::from_len_ptr(slice.len(), slice.as_mut_ptr()); - // SAFETY: Our invariants are satisfied by the caller - // and that `&mut [T]` implies exclusive access to the data. - let invariant = PhantomData; - Self { raw, invariant } + unsafe { + // SAFETY: `&mut [T]` implies that the pointer is non-null. + let raw = SlimRawSlice::from_len_ptr(slice.len(), slice.as_mut_ptr()); + // SAFETY: Our invariants are satisfied by the caller + // and that `&mut [T]` implies exclusive access to the data. + let invariant = PhantomData; + Self { raw, invariant } + } } } diff --git a/crates/data-structures/src/small_map.rs b/crates/data-structures/src/small_map.rs index 502362952b2..1ea85220260 100644 --- a/crates/data-structures/src/small_map.rs +++ b/crates/data-structures/src/small_map.rs @@ -91,11 +91,11 @@ impl SmallHashMap { #[inline] fn maybe_convert_to_large(&mut self) { - if let Self::Small(list) = self { - if list.len() > M { - let list = mem::take(list); - self.convert_to_large(list); - } + if let Self::Small(list) = self + && list.len() > M + { + let list = mem::take(list); + self.convert_to_large(list); } } diff --git a/crates/datastore/src/locking_tx_datastore/committed_state.rs b/crates/datastore/src/locking_tx_datastore/committed_state.rs index 089b47e68f9..5864c5d3155 100644 --- a/crates/datastore/src/locking_tx_datastore/committed_state.rs +++ b/crates/datastore/src/locking_tx_datastore/committed_state.rs @@ -148,7 +148,7 @@ impl CommittedState { } /// Returns the views that perform a full scan of this table - pub(super) fn views_for_table_scan(&self, table_id: &TableId) -> impl Iterator { + pub(super) fn views_for_table_scan(&self, table_id: &TableId) -> impl Iterator + use<'_> { self.read_sets.views_for_table_scan(table_id) } @@ -157,7 +157,7 @@ impl CommittedState { &'a self, table_id: &TableId, row_ref: RowRef<'a>, - ) -> impl Iterator { + ) -> impl Iterator + use<'a> { self.read_sets.views_for_index_seek(table_id, row_ref) } } diff --git a/crates/datastore/src/locking_tx_datastore/datastore.rs b/crates/datastore/src/locking_tx_datastore/datastore.rs index 7741b6e319f..a8423dd9352 100644 --- a/crates/datastore/src/locking_tx_datastore/datastore.rs +++ b/crates/datastore/src/locking_tx_datastore/datastore.rs @@ -1206,14 +1206,13 @@ impl spacetimedb_commitlog::payload::txdata::Visitor for ReplayVi // TODO: avoid clone Ok(schema) => schema.table_name.clone(), - Err(_) => { - if let Some(name) = self.dropped_table_names.remove(&table_id) { - name - } else { + Err(_) => match self.dropped_table_names.remove(&table_id) { + Some(name) => name, + _ => { return self .process_error(anyhow!("Error looking up name for truncated table {table_id:?}").into()); } - } + }, }; if let Err(e) = self.committed_state.replay_truncate(table_id).with_context(|| { diff --git a/crates/datastore/src/locking_tx_datastore/delete_table.rs b/crates/datastore/src/locking_tx_datastore/delete_table.rs index 67a96830072..4d62bd49f5e 100644 --- a/crates/datastore/src/locking_tx_datastore/delete_table.rs +++ b/crates/datastore/src/locking_tx_datastore/delete_table.rs @@ -206,7 +206,7 @@ mod test { self.check_state(); dt } - fn iter(&self) -> impl Iterator { + fn iter(&self) -> impl Iterator + use<> { let dt = self.dt.iter().collect::>(); let bs = self.bs.iter().copied().collect::>(); assert_eq!(dt, bs); diff --git a/crates/datastore/src/locking_tx_datastore/mut_tx.rs b/crates/datastore/src/locking_tx_datastore/mut_tx.rs index 101a5feb753..d227b6c3805 100644 --- a/crates/datastore/src/locking_tx_datastore/mut_tx.rs +++ b/crates/datastore/src/locking_tx_datastore/mut_tx.rs @@ -108,7 +108,7 @@ impl ViewReadSets { } /// Returns the views that perform a full scan of this table - pub fn views_for_table_scan(&self, table_id: &TableId) -> impl Iterator { + pub fn views_for_table_scan(&self, table_id: &TableId) -> impl Iterator + use<'_> { self.tables .get(table_id) .into_iter() @@ -146,7 +146,7 @@ impl ViewReadSets { &'a self, table_id: &TableId, row_ptr: RowRef<'a>, - ) -> impl Iterator { + ) -> impl Iterator + use<'a> { self.tables .get(table_id) .into_iter() @@ -298,11 +298,11 @@ impl MutTxId { upper: Bound, ) { // Check for precise index seek. - if let (Bound::Included(low_val), Bound::Included(up_val)) = (&lower, &upper) { - if low_val == up_val { - self.record_index_scan_point_inner(view, table_id, index_id, low_val.clone()); - return; - } + if let (Bound::Included(low_val), Bound::Included(up_val)) = (&lower, &upper) + && low_val == up_val + { + self.record_index_scan_point_inner(view, table_id, index_id, low_val.clone()); + return; } // Everything else is treated as a table scan. @@ -2515,7 +2515,9 @@ impl MutTxId { ) { // This is possible on restart if the database was previously running a version // before this system table was added. - log::error!("[{database_identity}]: delete_st_client_credentials: attempting to delete credentials for missing connection id ({connection_id}), error: {e}"); + log::error!( + "[{database_identity}]: delete_st_client_credentials: attempting to delete credentials for missing connection id ({connection_id}), error: {e}" + ); } Ok(()) } @@ -2530,7 +2532,7 @@ impl MutTxId { identity: identity.into(), connection_id: connection_id.into(), }; - if let Some(ptr) = self + match self .iter_by_col_eq( ST_CLIENT_ID, // TODO(perf, minor, centril): consider a `const_col_list([x, ..])` @@ -2541,9 +2543,12 @@ impl MutTxId { .next() .map(|row| row.pointer()) { - self.delete(ST_CLIENT_ID, ptr).map(drop)? - } else { - log::error!("[{database_identity}]: delete_st_client: attempting to delete client ({identity}, {connection_id}), but no st_client row for that client is resident"); + Some(ptr) => self.delete(ST_CLIENT_ID, ptr).map(drop)?, + _ => { + log::error!( + "[{database_identity}]: delete_st_client: attempting to delete client ({identity}, {connection_id}), but no st_client row for that client is resident" + ); + } } self.delete_st_client_credentials(database_identity, connection_id) } @@ -2918,7 +2923,7 @@ impl MutTxId { commit_table.check_unique_constraints( tx_row_ref, // Don't check this index since we'll do a 1-1 old/new replacement. - |ixs| ixs.filter(|(&id, _)| id != index_id), + |ixs| ixs.filter(|&(&id, _)| id != index_id), is_deleted, ) } { diff --git a/crates/durability/src/imp/local.rs b/crates/durability/src/imp/local.rs index e3a8afa34ac..059701071bf 100644 --- a/crates/durability/src/imp/local.rs +++ b/crates/durability/src/imp/local.rs @@ -151,7 +151,7 @@ impl Local { } /// Obtain a read-only copy of the durable state that implements [History]. - pub fn as_history(&self) -> impl History> { + pub fn as_history(&self) -> impl History> + use { self.clog.clone() } } @@ -164,7 +164,7 @@ impl Local { } /// Obtain an iterator over the [`Commit`]s in the underlying log. - pub fn commits_from(&self, offset: TxOffset) -> impl Iterator> { + pub fn commits_from(&self, offset: TxOffset) -> impl Iterator> + use { self.clog.commits_from(offset).map_ok(Commit::from) } @@ -288,10 +288,10 @@ impl Actor { #[instrument(skip_all)] async fn flush_and_sync(&self) -> io::Result> { // Skip if nothing changed. - if let Some((committed, durable)) = self.clog.max_committed_offset().zip(*self.durable_offset.borrow()) { - if committed == durable { - return Ok(None); - } + if let Some((committed, durable)) = self.clog.max_committed_offset().zip(*self.durable_offset.borrow()) + && committed == durable + { + return Ok(None); } let clog = self.clog.clone(); diff --git a/crates/expr/src/check.rs b/crates/expr/src/check.rs index 58093e97df2..01e151f4357 100644 --- a/crates/expr/src/check.rs +++ b/crates/expr/src/check.rs @@ -99,11 +99,11 @@ pub trait TypeChecker { vars.insert(rhs.alias.clone(), rhs.schema.clone()); if let Some(on) = on { - if let Expr::BinOp(BinOp::Eq, a, b) = type_expr(vars, on, Some(&AlgebraicType::Bool))? { - if let (Expr::Field(a), Expr::Field(b)) = (*a, *b) { - join = RelExpr::EqJoin(LeftDeepJoin { lhs, rhs }, a, b); - continue; - } + if let Expr::BinOp(BinOp::Eq, a, b) = type_expr(vars, on, Some(&AlgebraicType::Bool))? + && let (Expr::Field(a), Expr::Field(b)) = (*a, *b) + { + join = RelExpr::EqJoin(LeftDeepJoin { lhs, rhs }, a, b); + continue; } unreachable!("Unreachability guaranteed by parser") } diff --git a/crates/expr/src/expr.rs b/crates/expr/src/expr.rs index cf5688d537c..c9753e5c195 100644 --- a/crates/expr/src/expr.rs +++ b/crates/expr/src/expr.rs @@ -264,10 +264,10 @@ pub struct Relvar { impl CollectViews for RelExpr { fn collect_views(&self, views: &mut HashSet) { self.visit(&mut |expr| { - if let Self::RelVar(Relvar { schema, .. }) = expr { - if let Some(info) = &schema.view_info { - views.insert(info.view_id); - } + if let Self::RelVar(Relvar { schema, .. }) = expr + && let Some(info) = &schema.view_info + { + views.insert(info.view_id); } }); } diff --git a/crates/expr/src/lib.rs b/crates/expr/src/lib.rs index 3a461957df6..d82cba3b382 100644 --- a/crates/expr/src/lib.rs +++ b/crates/expr/src/lib.rs @@ -106,10 +106,10 @@ fn _type_expr(vars: &Relvars, expr: SqlExpr, expected: Option<&AlgebraicType>, d .get_column_by_name(&field) .ok_or_else(|| Unresolved::var(&field))?; - if let Some(ty) = expected { - if col_type != ty { - return Err(UnexpectedType::new(col_type, ty).into()); - } + if let Some(ty) = expected + && col_type != ty + { + return Err(UnexpectedType::new(col_type, ty).into()); } Ok(Expr::Field(FieldProject { diff --git a/crates/fs-utils/src/dir_trie.rs b/crates/fs-utils/src/dir_trie.rs index 03b93eda13c..14e6aa7bdeb 100644 --- a/crates/fs-utils/src/dir_trie.rs +++ b/crates/fs-utils/src/dir_trie.rs @@ -167,11 +167,11 @@ impl DirTrie { return Ok(()); } - if let Some(src_repo) = src_repo { - if self.try_hardlink_from(src_repo, file_id)? { - counter.objects_hardlinked += 1; - return Ok(()); - } + if let Some(src_repo) = src_repo + && self.try_hardlink_from(src_repo, file_id)? + { + counter.objects_hardlinked += 1; + return Ok(()); } let mut file = self.open_entry_writer(file_id)?; diff --git a/crates/guard/src/lib.rs b/crates/guard/src/lib.rs index 9942d7436aa..f61244d7706 100644 --- a/crates/guard/src/lib.rs +++ b/crates/guard/src/lib.rs @@ -313,11 +313,11 @@ impl SpacetimeDbGuard { let deadline = Instant::now() + Duration::from_secs(10); while Instant::now() < deadline { let url = format!("{}/v1/ping", host_url); - if let Ok(resp) = client.get(&url).send() { - if resp.status().is_success() { - eprintln!("[SPAWN-{:03}] HTTP ready at {}", spawn_id, host_url); - return (child, logs, host_url, reader_threads); - } + if let Ok(resp) = client.get(&url).send() + && resp.status().is_success() + { + eprintln!("[SPAWN-{:03}] HTTP ready at {}", spawn_id, host_url); + return (child, logs, host_url, reader_threads); } sleep(Duration::from_millis(50)); } @@ -477,13 +477,13 @@ impl Drop for SpacetimeDbGuard { self.kill_process(); // Only print logs if the test is currently panicking - if std::thread::panicking() { - if let Ok(logs) = self.logs.lock() { - eprintln!( + if std::thread::panicking() + && let Ok(logs) = self.logs.lock() + { + eprintln!( "\n===== SpacetimeDB child logs (only on failure) =====\n{}\n====================================================", *logs ); - } } } } diff --git a/crates/paths/src/lib.rs b/crates/paths/src/lib.rs index bd41c0bc629..3ae55eed685 100644 --- a/crates/paths/src/lib.rs +++ b/crates/paths/src/lib.rs @@ -282,9 +282,11 @@ mod tests { } fn maybe_set_var(var: &str, val: Option>) { if let Some(val) = val { - std::env::set_var(var, val); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { std::env::set_var(var, val) }; } else { - std::env::remove_var(var); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { std::env::remove_var(var) }; } } pub(super) fn with_vars(vars: [(&str, Option<&str>); N], f: impl FnOnce() -> R) -> R { diff --git a/crates/pg/src/encoder.rs b/crates/pg/src/encoder.rs index e2fd8601bf6..e57196ac61d 100644 --- a/crates/pg/src/encoder.rs +++ b/crates/pg/src/encoder.rs @@ -147,13 +147,12 @@ impl TypedWriter for PsqlFormatter<'_> { value: ValueWithType, ) -> Result<(), Self::Error> { // Is a simple enum? - if let AlgebraicType::Sum(sum) = &ty.field.algebraic_type { - if sum.is_simple_enum() { - if let Some(variant_name) = name { - self.encoder.encode_field(&variant_name)?; - return Ok(()); - } - } + if let AlgebraicType::Sum(sum) = &ty.field.algebraic_type + && sum.is_simple_enum() + && let Some(variant_name) = name + { + self.encoder.encode_field(&variant_name)?; + return Ok(()); } let PsqlChars { start, sep, end, quote } = ty.client.format_chars(); diff --git a/crates/pg/src/pg_server.rs b/crates/pg/src/pg_server.rs index 860df156f25..6195df28732 100644 --- a/crates/pg/src/pg_server.rs +++ b/crates/pg/src/pg_server.rs @@ -246,10 +246,13 @@ impl { + log::info!("PG: Connecting to database: {database}, by {application_name}",); + } + _ => { + log::info!("PG: Connecting to database: {database}"); + } } let name = database::NameOrIdentity::Name(DatabaseName(database.clone())); diff --git a/crates/physical-plan/src/plan.rs b/crates/physical-plan/src/plan.rs index d284c2f76ff..50bb06fc2b9 100644 --- a/crates/physical-plan/src/plan.rs +++ b/crates/physical-plan/src/plan.rs @@ -769,10 +769,10 @@ impl PhysicalPlan { match self { Self::Filter(input, expr) => { expr.visit(&mut |expr| { - if let PhysicalExpr::Field(TupleField { label: var, .. }) = expr { - if !reqs.contains(var) { - reqs.push(*var); - } + if let PhysicalExpr::Field(TupleField { label: var, .. }) = expr + && !reqs.contains(var) + { + reqs.push(*var); } }); Self::Filter(Box::new(input.introduce_semijoins(reqs)), expr) @@ -951,12 +951,11 @@ impl PhysicalPlan { Self::Filter(input, expr) => { let mut cols: Vec<_> = cols.iter().collect(); expr.visit(&mut |plan| { - if let PhysicalExpr::BinOp(BinOp::Eq, expr, value) = plan { - if let (PhysicalExpr::Field(proj), PhysicalExpr::Value(..)) = (&**expr, &**value) { - if proj.label == *label { - cols.push(proj.field_pos.into()); - } - } + if let PhysicalExpr::BinOp(BinOp::Eq, expr, value) = plan + && let (PhysicalExpr::Field(proj), PhysicalExpr::Value(..)) = (&**expr, &**value) + && proj.label == *label + { + cols.push(proj.field_pos.into()); } }); input.returns_distinct_values(label, &ColSet::from_iter(cols)) diff --git a/crates/physical-plan/src/rules.rs b/crates/physical-plan/src/rules.rs index 98bc5fef4af..2fd9f58a92e 100644 --- a/crates/physical-plan/src/rules.rs +++ b/crates/physical-plan/src/rules.rs @@ -272,10 +272,10 @@ impl RewriteRule for PushConstEq { let is_filter = |plan: &PhysicalPlan| { !plan.any(&|plan| !matches!(plan, PhysicalPlan::TableScan(..) | PhysicalPlan::Filter(..))) }; - if let PhysicalPlan::Filter(input, PhysicalExpr::BinOp(_, expr, value)) = plan { - if let (PhysicalExpr::Field(TupleField { label, .. }), PhysicalExpr::Value(_)) = (&**expr, &**value) { - return (input.has_table_scan(Some(label)) && !is_filter(input)).then_some(*label); - } + if let PhysicalPlan::Filter(input, PhysicalExpr::BinOp(_, expr, value)) = plan + && let (PhysicalExpr::Field(TupleField { label, .. }), PhysicalExpr::Value(_)) = (&**expr, &**value) + { + return (input.has_table_scan(Some(label)) && !is_filter(input)).then_some(*label); } None } @@ -340,11 +340,10 @@ impl RewriteRule for PushConstAnd { }; if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, exprs)) = plan { return exprs.iter().find_map(|expr| { - if let PhysicalExpr::BinOp(_, expr, value) = expr { - if let (PhysicalExpr::Field(TupleField { label, .. }), PhysicalExpr::Value(_)) = (&**expr, &**value) - { - return (input.has_table_scan(Some(label)) && !is_filter(input)).then_some(*label); - } + if let PhysicalExpr::BinOp(_, expr, value) = expr + && let (PhysicalExpr::Field(TupleField { label, .. }), PhysicalExpr::Value(_)) = (&**expr, &**value) + { + return (input.has_table_scan(Some(label)) && !is_filter(input)).then_some(*label); } None }); @@ -358,15 +357,13 @@ impl RewriteRule for PushConstAnd { let mut leaf_exprs = vec![]; let mut root_exprs = vec![]; for expr in exprs { - if let PhysicalExpr::BinOp(_, lhs, value) = &expr { - if let (PhysicalExpr::Field(TupleField { label: var, .. }), PhysicalExpr::Value(_)) = + if let PhysicalExpr::BinOp(_, lhs, value) = &expr + && let (PhysicalExpr::Field(TupleField { label: var, .. }), PhysicalExpr::Value(_)) = (&**lhs, &**value) - { - if var == &relvar { - leaf_exprs.push(expr); - continue; - } - } + && var == &relvar + { + leaf_exprs.push(expr); + continue; } root_exprs.push(expr); } @@ -421,8 +418,8 @@ impl RewriteRule for IxScanEq { type Info = (IndexId, ColId); fn matches(plan: &PhysicalPlan) -> Option { - if let PhysicalPlan::Filter(input, PhysicalExpr::BinOp(BinOp::Eq, expr, value)) = plan { - if let PhysicalPlan::TableScan( + if let PhysicalPlan::Filter(input, PhysicalExpr::BinOp(BinOp::Eq, expr, value)) = plan + && let PhysicalPlan::TableScan( TableScan { schema, limit: None, @@ -430,48 +427,44 @@ impl RewriteRule for IxScanEq { }, _, ) = &**input - { - if let (PhysicalExpr::Field(TupleField { field_pos: pos, .. }), PhysicalExpr::Value(_)) = - (&**expr, &**value) - { - return schema.indexes.iter().find_map( - |IndexSchema { - index_id, - index_algorithm, - .. - }| { - // TODO: Support prefix scans. - // Remember to consider non-ranged indices. - if index_algorithm.columns().len() == 1 { - Some((*index_id, index_algorithm.find_col_index(*pos)?)) - } else { - None - } - }, - ); - } - } + && let (PhysicalExpr::Field(TupleField { field_pos: pos, .. }), PhysicalExpr::Value(_)) = + (&**expr, &**value) + { + return schema.indexes.iter().find_map( + |IndexSchema { + index_id, + index_algorithm, + .. + }| { + // TODO: Support prefix scans. + // Remember to consider non-ranged indices. + if index_algorithm.columns().len() == 1 { + Some((*index_id, index_algorithm.find_col_index(*pos)?)) + } else { + None + } + }, + ); } None } fn rewrite(plan: PhysicalPlan, (index_id, col_id): Self::Info) -> Result { - if let PhysicalPlan::Filter(input, PhysicalExpr::BinOp(BinOp::Eq, _, value)) = plan { - if let PhysicalPlan::TableScan(TableScan { schema, limit, delta }, var) = *input { - if let PhysicalExpr::Value(v) = *value { - return Ok(PhysicalPlan::IxScan( - IxScan { - schema, - limit, - delta, - index_id, - prefix: vec![], - arg: Sarg::Eq(col_id, v), - }, - var, - )); - } - } + if let PhysicalPlan::Filter(input, PhysicalExpr::BinOp(BinOp::Eq, _, value)) = plan + && let PhysicalPlan::TableScan(TableScan { schema, limit, delta }, var) = *input + && let PhysicalExpr::Value(v) = *value + { + return Ok(PhysicalPlan::IxScan( + IxScan { + schema, + limit, + delta, + index_id, + prefix: vec![], + arg: Sarg::Eq(col_id, v), + }, + var, + )); } bail!("{INVARIANT_VIOLATION}: Failed to create single column index scan from equality condition") } @@ -493,8 +486,8 @@ impl RewriteRule for IxScanAnd { type Info = (IndexId, usize, ColId); fn matches(plan: &PhysicalPlan) -> Option { - if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, exprs)) = plan { - if let PhysicalPlan::TableScan( + if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, exprs)) = plan + && let PhysicalPlan::TableScan( TableScan { schema, limit: None, @@ -502,60 +495,56 @@ impl RewriteRule for IxScanAnd { }, _, ) = &**input - { - return exprs.iter().enumerate().find_map(|(i, expr)| { - if let PhysicalExpr::BinOp(BinOp::Eq, lhs, value) = expr { - if let (PhysicalExpr::Field(TupleField { field_pos: pos, .. }), PhysicalExpr::Value(_)) = - (&**lhs, &**value) - { - return schema.indexes.iter().find_map( - |IndexSchema { - index_id, - index_algorithm, - .. - }| { - index_algorithm - .columns() - // TODO: Support prefix scans - .as_singleton() - .filter(|col_id| col_id.idx() == *pos) - .map(|col_id| (*index_id, i, col_id)) - }, - ); - } - } - None - }); - } + { + return exprs.iter().enumerate().find_map(|(i, expr)| { + if let PhysicalExpr::BinOp(BinOp::Eq, lhs, value) = expr + && let (PhysicalExpr::Field(TupleField { field_pos: pos, .. }), PhysicalExpr::Value(_)) = + (&**lhs, &**value) + { + return schema.indexes.iter().find_map( + |IndexSchema { + index_id, + index_algorithm, + .. + }| { + index_algorithm + .columns() + // TODO: Support prefix scans + .as_singleton() + .filter(|col_id| col_id.idx() == *pos) + .map(|col_id| (*index_id, i, col_id)) + }, + ); + } + None + }); } None } fn rewrite(plan: PhysicalPlan, (index_id, i, col_id): Self::Info) -> Result { - if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, mut exprs)) = plan { - if let PhysicalPlan::TableScan(TableScan { schema, limit, delta }, label) = *input { - if let PhysicalExpr::BinOp(BinOp::Eq, _, value) = exprs.swap_remove(i) { - if let PhysicalExpr::Value(v) = *value { - return Ok(PhysicalPlan::Filter( - Box::new(PhysicalPlan::IxScan( - IxScan { - schema, - limit, - delta, - index_id, - prefix: vec![], - arg: Sarg::Eq(col_id, v), - }, - label, - )), - match exprs.len() { - 1 => exprs.swap_remove(0), - _ => PhysicalExpr::LogOp(LogOp::And, exprs), - }, - )); - } - } - } + if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, mut exprs)) = plan + && let PhysicalPlan::TableScan(TableScan { schema, limit, delta }, label) = *input + && let PhysicalExpr::BinOp(BinOp::Eq, _, value) = exprs.swap_remove(i) + && let PhysicalExpr::Value(v) = *value + { + return Ok(PhysicalPlan::Filter( + Box::new(PhysicalPlan::IxScan( + IxScan { + schema, + limit, + delta, + index_id, + prefix: vec![], + arg: Sarg::Eq(col_id, v), + }, + label, + )), + match exprs.len() { + 1 => exprs.swap_remove(0), + _ => PhysicalExpr::LogOp(LogOp::And, exprs), + }, + )); } bail!("{INVARIANT_VIOLATION}: Failed to create single column index scan from conjunction") } @@ -637,84 +626,79 @@ impl RewriteRule for IxScanEq2Col { fn rewrite(plan: PhysicalPlan, info: Self::Info) -> Result { match info.cols.as_slice() { [(i, a), (j, b)] => { - if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, exprs)) = plan { - if let PhysicalPlan::TableScan(TableScan { schema, limit, delta }, label) = *input { - if let ( - Some(PhysicalExpr::BinOp(BinOp::Eq, _, u)), - Some(PhysicalExpr::BinOp(BinOp::Eq, _, v)), - ) = (exprs.get(*i), exprs.get(*j)) - { - if let (PhysicalExpr::Value(u), PhysicalExpr::Value(v)) = (&**u, &**v) { - return Ok(match exprs.len() { - n @ 0 | n @ 1 => { - bail!("{INVARIANT_VIOLATION}: Cannot create 2-column index scan from {n} conditions") - } - // If there are only 2 conditions in this filter, - // we replace the filter with an index scan. - 2 => PhysicalPlan::IxScan( - IxScan { - schema, - limit, - delta, - index_id: info.index_id, - prefix: vec![(*a, u.clone())], - arg: Sarg::Eq(*b, v.clone()), - }, - label, - ), - // If there are 3 conditions in this filter, - // we create an index scan from 2 of them. - // The original conjunction is no longer well defined, - // because it only has a single operand now. - // Hence we must replace it with its operand. - 3 => PhysicalPlan::Filter( - Box::new(PhysicalPlan::IxScan( - IxScan { - schema, - limit, - delta, - index_id: info.index_id, - prefix: vec![(*a, u.clone())], - arg: Sarg::Eq(*b, v.clone()), - }, - label, - )), - exprs - .into_iter() - .enumerate() - .find(|(pos, _)| pos != i && pos != j) - .map(|(_, expr)| expr) - .unwrap(), - ), - // If there are more than 3 conditions in this filter, - // we remove the 2 conditions used in the index scan. - // The remaining conditions still form a conjunction. - _ => PhysicalPlan::Filter( - Box::new(PhysicalPlan::IxScan( - IxScan { - schema, - limit, - delta, - index_id: info.index_id, - prefix: vec![(*a, u.clone())], - arg: Sarg::Eq(*b, v.clone()), - }, - label, - )), - PhysicalExpr::LogOp( - LogOp::And, - exprs - .into_iter() - .enumerate() - .filter(|(pos, _)| pos != i && pos != j) - .map(|(_, expr)| expr) - .collect(), - ), - ), - }); - } + if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, exprs)) = plan + && let PhysicalPlan::TableScan(TableScan { schema, limit, delta }, label) = *input + && let (Some(PhysicalExpr::BinOp(BinOp::Eq, _, u)), Some(PhysicalExpr::BinOp(BinOp::Eq, _, v))) = + (exprs.get(*i), exprs.get(*j)) + && let (PhysicalExpr::Value(u), PhysicalExpr::Value(v)) = (&**u, &**v) + { + return Ok(match exprs.len() { + n @ 0 | n @ 1 => { + bail!("{INVARIANT_VIOLATION}: Cannot create 2-column index scan from {n} conditions") } - } + // If there are only 2 conditions in this filter, + // we replace the filter with an index scan. + 2 => PhysicalPlan::IxScan( + IxScan { + schema, + limit, + delta, + index_id: info.index_id, + prefix: vec![(*a, u.clone())], + arg: Sarg::Eq(*b, v.clone()), + }, + label, + ), + // If there are 3 conditions in this filter, + // we create an index scan from 2 of them. + // The original conjunction is no longer well defined, + // because it only has a single operand now. + // Hence we must replace it with its operand. + 3 => PhysicalPlan::Filter( + Box::new(PhysicalPlan::IxScan( + IxScan { + schema, + limit, + delta, + index_id: info.index_id, + prefix: vec![(*a, u.clone())], + arg: Sarg::Eq(*b, v.clone()), + }, + label, + )), + exprs + .into_iter() + .enumerate() + .find(|(pos, _)| pos != i && pos != j) + .map(|(_, expr)| expr) + .unwrap(), + ), + // If there are more than 3 conditions in this filter, + // we remove the 2 conditions used in the index scan. + // The remaining conditions still form a conjunction. + _ => PhysicalPlan::Filter( + Box::new(PhysicalPlan::IxScan( + IxScan { + schema, + limit, + delta, + index_id: info.index_id, + prefix: vec![(*a, u.clone())], + arg: Sarg::Eq(*b, v.clone()), + }, + label, + )), + PhysicalExpr::LogOp( + LogOp::And, + exprs + .into_iter() + .enumerate() + .filter(|(pos, _)| pos != i && pos != j) + .map(|(_, expr)| expr) + .collect(), + ), + ), + }); } bail!("{INVARIANT_VIOLATION}: Failed to create 2-column index scan") } @@ -817,87 +801,82 @@ impl RewriteRule for IxScanEq3Col { fn rewrite(plan: PhysicalPlan, info: Self::Info) -> Result { match info.cols.as_slice() { [(i, a), (j, b), (k, c)] => { - if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, exprs)) = plan { - if let PhysicalPlan::TableScan(TableScan { schema, limit, delta }, label) = *input { - if let ( - Some(PhysicalExpr::BinOp(BinOp::Eq, _, u)), - Some(PhysicalExpr::BinOp(BinOp::Eq, _, v)), - Some(PhysicalExpr::BinOp(BinOp::Eq, _, w)), - ) = (exprs.get(*i), exprs.get(*j), exprs.get(*k)) - { - if let (PhysicalExpr::Value(u), PhysicalExpr::Value(v), PhysicalExpr::Value(w)) = - (&**u, &**v, &**w) - { - return Ok(match exprs.len() { - n @ 0 | n @ 1 | n @ 2 => { - bail!("{INVARIANT_VIOLATION}: Cannot create 3-column index scan from {n} conditions") - } - // If there are only 3 conditions in this filter, - // we replace the filter with an index scan. - 3 => PhysicalPlan::IxScan( - IxScan { - schema, - limit, - delta, - index_id: info.index_id, - prefix: vec![(*a, u.clone()), (*b, v.clone())], - arg: Sarg::Eq(*c, w.clone()), - }, - label, - ), - // If there are 4 conditions in this filter, - // we create an index scan from 3 of them. - // The original conjunction is no longer well defined, - // because it only has a single operand now. - // Hence we must replace it with its operand. - 4 => PhysicalPlan::Filter( - Box::new(PhysicalPlan::IxScan( - IxScan { - schema, - limit, - delta, - index_id: info.index_id, - prefix: vec![(*a, u.clone()), (*b, v.clone())], - arg: Sarg::Eq(*c, w.clone()), - }, - label, - )), - exprs - .into_iter() - .enumerate() - .find(|(pos, _)| pos != i && pos != j && pos != k) - .map(|(_, expr)| expr) - .unwrap(), - ), - // If there are more than 4 conditions in this filter, - // we remove the 3 conditions used in the index scan. - // The remaining conditions still form a conjunction. - _ => PhysicalPlan::Filter( - Box::new(PhysicalPlan::IxScan( - IxScan { - schema, - limit, - delta, - index_id: info.index_id, - prefix: vec![(*a, u.clone()), (*b, v.clone())], - arg: Sarg::Eq(*c, w.clone()), - }, - label, - )), - PhysicalExpr::LogOp( - LogOp::And, - exprs - .into_iter() - .enumerate() - .filter(|(pos, _)| pos != i && pos != j && pos != k) - .map(|(_, expr)| expr) - .collect(), - ), - ), - }); - } + if let PhysicalPlan::Filter(input, PhysicalExpr::LogOp(LogOp::And, exprs)) = plan + && let PhysicalPlan::TableScan(TableScan { schema, limit, delta }, label) = *input + && let ( + Some(PhysicalExpr::BinOp(BinOp::Eq, _, u)), + Some(PhysicalExpr::BinOp(BinOp::Eq, _, v)), + Some(PhysicalExpr::BinOp(BinOp::Eq, _, w)), + ) = (exprs.get(*i), exprs.get(*j), exprs.get(*k)) + && let (PhysicalExpr::Value(u), PhysicalExpr::Value(v), PhysicalExpr::Value(w)) = (&**u, &**v, &**w) + { + return Ok(match exprs.len() { + n @ 0 | n @ 1 | n @ 2 => { + bail!("{INVARIANT_VIOLATION}: Cannot create 3-column index scan from {n} conditions") } - } + // If there are only 3 conditions in this filter, + // we replace the filter with an index scan. + 3 => PhysicalPlan::IxScan( + IxScan { + schema, + limit, + delta, + index_id: info.index_id, + prefix: vec![(*a, u.clone()), (*b, v.clone())], + arg: Sarg::Eq(*c, w.clone()), + }, + label, + ), + // If there are 4 conditions in this filter, + // we create an index scan from 3 of them. + // The original conjunction is no longer well defined, + // because it only has a single operand now. + // Hence we must replace it with its operand. + 4 => PhysicalPlan::Filter( + Box::new(PhysicalPlan::IxScan( + IxScan { + schema, + limit, + delta, + index_id: info.index_id, + prefix: vec![(*a, u.clone()), (*b, v.clone())], + arg: Sarg::Eq(*c, w.clone()), + }, + label, + )), + exprs + .into_iter() + .enumerate() + .find(|(pos, _)| pos != i && pos != j && pos != k) + .map(|(_, expr)| expr) + .unwrap(), + ), + // If there are more than 4 conditions in this filter, + // we remove the 3 conditions used in the index scan. + // The remaining conditions still form a conjunction. + _ => PhysicalPlan::Filter( + Box::new(PhysicalPlan::IxScan( + IxScan { + schema, + limit, + delta, + index_id: info.index_id, + prefix: vec![(*a, u.clone()), (*b, v.clone())], + arg: Sarg::Eq(*c, w.clone()), + }, + label, + )), + PhysicalExpr::LogOp( + LogOp::And, + exprs + .into_iter() + .enumerate() + .filter(|(pos, _)| pos != i && pos != j && pos != k) + .map(|(_, expr)| expr) + .collect(), + ), + ), + }); } bail!("{INVARIANT_VIOLATION}: Failed to create 3-column index scan") } @@ -1041,41 +1020,39 @@ impl RewriteRule for PullFilterAboveHashJoin { }, Semi::All, ) = plan + && let PhysicalPlan::Filter(input, _) = &**rhs + && let PhysicalPlan::TableScan(TableScan { schema, .. }, _) = &**input { - if let PhysicalPlan::Filter(input, _) = &**rhs { - if let PhysicalPlan::TableScan(TableScan { schema, .. }, _) = &**input { - return ((lhs.is_delta_scan() - || matches!(**lhs, PhysicalPlan::Filter(..)) - || matches!(**lhs, PhysicalPlan::IxScan(..))) - && schema.indexes.iter().any(|schema| { - schema - .index_algorithm - .columns() - .as_singleton() - .is_some_and(|col_id| col_id.idx() == rhs_field.field_pos) - })) - .then_some(()); - } - } + return ((lhs.is_delta_scan() + || matches!(**lhs, PhysicalPlan::Filter(..)) + || matches!(**lhs, PhysicalPlan::IxScan(..))) + && schema.indexes.iter().any(|schema| { + schema + .index_algorithm + .columns() + .as_singleton() + .is_some_and(|col_id| col_id.idx() == rhs_field.field_pos) + })) + .then_some(()); } None } fn rewrite(plan: Self::Plan, _: Self::Info) -> Result { - if let PhysicalPlan::HashJoin(join, semi) = plan { - if let PhysicalPlan::Filter(rhs, expr) = *join.rhs { - return Ok(PhysicalPlan::Filter( - Box::new(PhysicalPlan::HashJoin( - HashJoin { - lhs: join.lhs, - rhs, - ..join - }, - semi, - )), - expr, - )); - } + if let PhysicalPlan::HashJoin(join, semi) = plan + && let PhysicalPlan::Filter(rhs, expr) = *join.rhs + { + return Ok(PhysicalPlan::Filter( + Box::new(PhysicalPlan::HashJoin( + HashJoin { + lhs: join.lhs, + rhs, + ..join + }, + semi, + )), + expr, + )); } bail!("{INVARIANT_VIOLATION}: Failed to pull filter above hash join") } @@ -1123,8 +1100,8 @@ impl RewriteRule for HashToIxJoin { } fn rewrite(plan: PhysicalPlan, (rhs_index, rhs_field): Self::Info) -> Result { - if let PhysicalPlan::HashJoin(join, semi) = plan { - if let PhysicalPlan::TableScan( + if let PhysicalPlan::HashJoin(join, semi) = plan + && let PhysicalPlan::TableScan( TableScan { schema: rhs, limit: None, @@ -1132,21 +1109,20 @@ impl RewriteRule for HashToIxJoin { }, rhs_label, ) = *join.rhs - { - return Ok(PhysicalPlan::IxJoin( - IxJoin { - lhs: join.lhs, - rhs, - rhs_label, - rhs_index, - rhs_field, - rhs_delta, - unique: false, - lhs_field: join.lhs_field, - }, - semi, - )); - } + { + return Ok(PhysicalPlan::IxJoin( + IxJoin { + lhs: join.lhs, + rhs, + rhs_label, + rhs_index, + rhs_field, + rhs_delta, + unique: false, + lhs_field: join.lhs_field, + }, + semi, + )); } bail!("{INVARIANT_VIOLATION}: Failed to rewrite hash join as index join") } diff --git a/crates/primitives/src/col_list.rs b/crates/primitives/src/col_list.rs index b763cfeafad..6145a4dc294 100644 --- a/crates/primitives/src/col_list.rs +++ b/crates/primitives/src/col_list.rs @@ -724,7 +724,7 @@ impl Clone for ColListVec { fn is_sorted_and_deduped(data: &[ColId]) -> bool { match data { [] => true, - [mut prev, rest @ ..] => !rest.iter().any(|elem| { + &[mut prev, ref rest @ ..] => !rest.iter().any(|elem| { let bad = prev >= *elem; prev = *elem; bad diff --git a/crates/sats/src/de.rs b/crates/sats/src/de.rs index 5b5b0b118c5..8ef760f5a13 100644 --- a/crates/sats/src/de.rs +++ b/crates/sats/src/de.rs @@ -189,10 +189,9 @@ pub trait Error: Sized { ProductKind::Normal => "field", ProductKind::ReducerArgs => "reducer argument", }; - if let Some(one_of) = one_of_names(|| expected.field_names()) { - Self::custom(format_args!("unknown {el_ty} `{field_name}`, expected {one_of}")) - } else { - Self::custom(format_args!("unknown {el_ty} `{field_name}`, there are no {el_ty}s")) + match one_of_names(|| expected.field_names()) { + Some(one_of) => Self::custom(format_args!("unknown {el_ty} `{field_name}`, expected {one_of}")), + _ => Self::custom(format_args!("unknown {el_ty} `{field_name}`, there are no {el_ty}s")), } } @@ -206,10 +205,9 @@ pub trait Error: Sized { /// The `name` is not that of a variant of the sum type. fn unknown_variant_name<'de, T: VariantVisitor<'de>>(name: &str, expected: &T) -> Self { - if let Some(one_of) = one_of_names(|| expected.variant_names().map(Some)) { - Self::custom(format_args!("unknown variant `{name}`, expected {one_of}",)) - } else { - Self::custom(format_args!("unknown variant `{name}`, there are no variants")) + match one_of_names(|| expected.variant_names().map(Some)) { + Some(one_of) => Self::custom(format_args!("unknown variant `{name}`, expected {one_of}",)), + _ => Self::custom(format_args!("unknown variant `{name}`, there are no variants")), } } } diff --git a/crates/sats/src/de/serde.rs b/crates/sats/src/de/serde.rs index fe928de5712..ea322cc15b3 100644 --- a/crates/sats/src/de/serde.rs +++ b/crates/sats/src/de/serde.rs @@ -206,10 +206,11 @@ impl<'de, V: super::FieldNameVisitor<'de>> serde::Visitor<'de> for FieldNameVisi type Value = V::Output; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(one_of) = super::one_of_names(|| self.visitor.field_names()) { - write!(f, "a tuple field ({one_of})") - } else { - f.write_str("a tuple field, but there are no fields") + match super::one_of_names(|| self.visitor.field_names()) { + Some(one_of) => { + write!(f, "a tuple field ({one_of})") + } + _ => f.write_str("a tuple field, but there are no fields"), } } diff --git a/crates/sats/src/product_value.rs b/crates/sats/src/product_value.rs index 25c3576e58e..634b4a935cc 100644 --- a/crates/sats/src/product_value.rs +++ b/crates/sats/src/product_value.rs @@ -189,7 +189,7 @@ impl ProductValue { } impl<'a> ValueWithType<'a, ProductValue> { - pub fn elements(&self) -> impl ExactSizeIterator> { + pub fn elements(&self) -> impl ExactSizeIterator> + use<'a> { self.ty_s().with_values(self.value()) } } diff --git a/crates/schema/src/type_for_generate.rs b/crates/schema/src/type_for_generate.rs index 94666642e8b..edeabdadd99 100644 --- a/crates/schema/src/type_for_generate.rs +++ b/crates/schema/src/type_for_generate.rs @@ -521,7 +521,7 @@ impl TypespaceForGenerateBuilder<'_> { .get(ref_) .ok_or_else(|| ErrorStream::from(ClientCodegenError::TypeRefError(TypeRefError::InvalidTypeRef(ref_))))?; - let result = match def { + match def { AlgebraicType::Product(product) => product .elements .iter() @@ -565,9 +565,7 @@ impl TypespaceForGenerateBuilder<'_> { ty: PrettyAlgebraicType(def.clone()), } .into()), - }; - - result + } } /// Process an element/variant of a product/sum type. diff --git a/crates/smoketests/tests/namespaces.rs b/crates/smoketests/tests/namespaces.rs index 79cc396955f..3d632edd7e2 100644 --- a/crates/smoketests/tests/namespaces.rs +++ b/crates/smoketests/tests/namespaces.rs @@ -19,10 +19,10 @@ fn count_matches(dir: &Path, needle: &str) -> usize { let path = entry.path(); if path.is_dir() { count += count_matches(&path, needle); - } else if path.extension().is_some_and(|ext| ext == "cs") { - if let Ok(contents) = fs::read_to_string(&path) { - count += contents.matches(needle).count(); - } + } else if path.extension().is_some_and(|ext| ext == "cs") + && let Ok(contents) = fs::read_to_string(&path) + { + count += contents.matches(needle).count(); } } } diff --git a/crates/snapshot/src/lib.rs b/crates/snapshot/src/lib.rs index ddff813809a..6606d22f9e4 100644 --- a/crates/snapshot/src/lib.rs +++ b/crates/snapshot/src/lib.rs @@ -954,7 +954,7 @@ impl SnapshotRepository { .max()) } - pub fn all_snapshots(&self) -> Result, SnapshotError> { + pub fn all_snapshots(&self) -> Result + use<>, SnapshotError> { Ok(self .root // Item = Result @@ -984,7 +984,9 @@ impl SnapshotRepository { } /// Return an interator of [`ArchivedSnapshotDirPath`] for all the archived snapshot directories on disk - pub fn all_archived_snapshots(&self) -> Result, SnapshotError> { + pub fn all_archived_snapshots( + &self, + ) -> Result + use<>, SnapshotError> { Ok(self .root // Item = Result @@ -1093,17 +1095,17 @@ impl SnapshotRepository { if read.is_compressed() { return Ok(()); // Already compressed } - if let Some(hash) = hash { - if let Some(old_path) = old.get(&hash) { - let old_file = CompressReader::new(o_rdonly().open(old_path)?)?; - if old_file.is_compressed() { - std::fs::hard_link(old_path, src.with_extension("_tmp"))?; - std::fs::rename(src.with_extension("_tmp"), src)?; - if let Some(stats) = stats { - stats.hardlinked += 1; - } - return Ok(()); + if let Some(hash) = hash + && let Some(old_path) = old.get(&hash) + { + let old_file = CompressReader::new(o_rdonly().open(old_path)?)?; + if old_file.is_compressed() { + std::fs::hard_link(old_path, src.with_extension("_tmp"))?; + std::fs::rename(src.with_extension("_tmp"), src)?; + if let Some(stats) = stats { + stats.hardlinked += 1; } + return Ok(()); } } diff --git a/crates/snapshot/src/remote.rs b/crates/snapshot/src/remote.rs index 28e8170b325..ba3c6bb8707 100644 --- a/crates/snapshot/src/remote.rs +++ b/crates/snapshot/src/remote.rs @@ -757,7 +757,7 @@ impl BufPool { /// /// The buffer is returned to the pool when the returned [`ScopeGuard`] /// goes out of scope. - pub fn get(&self) -> ScopeGuard { + pub fn get(&self) -> ScopeGuard> { let this = self.clone(); scopeguard::guard( this.inner.pop().unwrap_or_else(|| BytesMut::with_capacity(PAGE_SIZE)), diff --git a/crates/sql-parser/src/ast/sql.rs b/crates/sql-parser/src/ast/sql.rs index 567b5ec5328..be7b753f395 100644 --- a/crates/sql-parser/src/ast/sql.rs +++ b/crates/sql-parser/src/ast/sql.rs @@ -88,10 +88,10 @@ impl SqlSelect { if self.project.has_unqualified_vars() { return Err(SqlUnsupported::UnqualifiedNames.into()); } - if let Some(expr) = &self.filter { - if expr.has_unqualified_vars() { - return Err(SqlUnsupported::UnqualifiedNames.into()); - } + if let Some(expr) = &self.filter + && expr.has_unqualified_vars() + { + return Err(SqlUnsupported::UnqualifiedNames.into()); } Ok(self) } diff --git a/crates/sql-parser/src/ast/sub.rs b/crates/sql-parser/src/ast/sub.rs index bd6fde0d98c..fb1168176e5 100644 --- a/crates/sql-parser/src/ast/sub.rs +++ b/crates/sql-parser/src/ast/sub.rs @@ -31,10 +31,10 @@ impl SqlSelect { if self.project.has_unqualified_vars() { return Err(SqlUnsupported::UnqualifiedNames.into()); } - if let Some(expr) = &self.filter { - if expr.has_unqualified_vars() { - return Err(SqlUnsupported::UnqualifiedNames.into()); - } + if let Some(expr) = &self.filter + && expr.has_unqualified_vars() + { + return Err(SqlUnsupported::UnqualifiedNames.into()); } Ok(self) } diff --git a/crates/standalone/src/control_db.rs b/crates/standalone/src/control_db.rs index b6d9f2821ac..8333695a42a 100644 --- a/crates/standalone/src/control_db.rs +++ b/crates/standalone/src/control_db.rs @@ -246,12 +246,12 @@ impl ControlDb { // Remove all existing names. if let Some(value) = rev_tx.get(database_identity_bytes)? { for domain in decode_domain_names(&value)? { - if let Some(ref owner) = domain_owner(tld_tx, &domain)? { - if owner != owner_identity { - transaction::abort(AbortWith::Domain(SetDomainsResult::PermissionDenied { - domain: domain.clone(), - }))?; - } + if let Some(ref owner) = domain_owner(tld_tx, &domain)? + && owner != owner_identity + { + transaction::abort(AbortWith::Domain(SetDomainsResult::PermissionDenied { + domain: domain.clone(), + }))?; } dns_tx.remove(domain.to_lowercase().as_bytes())?; } @@ -260,12 +260,12 @@ impl ControlDb { // Insert the new names. for domain in domain_names { - if let Some(ref owner) = domain_owner(tld_tx, domain)? { - if owner != owner_identity { - transaction::abort(AbortWith::Domain(SetDomainsResult::PermissionDenied { - domain: domain.clone(), - }))?; - } + if let Some(ref owner) = domain_owner(tld_tx, domain)? + && owner != owner_identity + { + transaction::abort(AbortWith::Domain(SetDomainsResult::PermissionDenied { + domain: domain.clone(), + }))?; } tld_tx.insert(domain.tld().to_lowercase().as_bytes(), &owner_identity.to_byte_array())?; dns_tx.insert(domain.to_lowercase().as_bytes(), &database_identity_bytes)?; diff --git a/crates/standalone/src/main.rs b/crates/standalone/src/main.rs index 10665ff8a09..06114d63b8d 100644 --- a/crates/standalone/src/main.rs +++ b/crates/standalone/src/main.rs @@ -56,7 +56,7 @@ static GLOBAL: Jemalloc = Jemalloc; // We export this symbol so that the jemalloc library can find it. // See https://github.com/polarsignals/rust-jemalloc-pprof?tab=readme-ov-file#usage #[allow(non_upper_case_globals)] -#[export_name = "_rjem_malloc_conf"] +#[unsafe(export_name = "_rjem_malloc_conf")] pub static _rjem_malloc_conf: &[u8] = b"prof:true,prof_active:false,lg_prof_sample:19\0"; fn main() -> anyhow::Result<()> { diff --git a/crates/subscription/src/lib.rs b/crates/subscription/src/lib.rs index ca0ef5b63e3..00ac42ec1c9 100644 --- a/crates/subscription/src/lib.rs +++ b/crates/subscription/src/lib.rs @@ -33,7 +33,7 @@ struct Fragments { impl Fragments { /// Returns the index ids from which this fragment reads. - fn index_ids(&self) -> impl Iterator { + fn index_ids(&self) -> impl Iterator + use<> { let mut index_ids = HashSet::new(); for plan in self.insert_plans.iter().chain(self.delete_plans.iter()) { plan.visit(&mut |plan| match plan { @@ -384,7 +384,7 @@ impl SubscriptionPlan { } /// From which indexes does this plan read? - pub fn index_ids(&self) -> impl Iterator { + pub fn index_ids(&self) -> impl Iterator + use<> { self.fragments.index_ids() } diff --git a/crates/table/src/page.rs b/crates/table/src/page.rs index fafe657cdc9..dc6acacf82f 100644 --- a/crates/table/src/page.rs +++ b/crates/table/src/page.rs @@ -535,7 +535,7 @@ impl<'page> VarView<'page> { /// /// This has to be done due to `page.row_data.split_at_mut(last_fixed)`. #[inline(always)] - fn adjuster(&self) -> impl FnOnce(PageOffset) -> PageOffset { + fn adjuster(&self) -> impl FnOnce(PageOffset) -> PageOffset + use<> { let lf = self.last_fixed; move |offset| offset - lf } diff --git a/crates/table/src/pointer_map.rs b/crates/table/src/pointer_map.rs index 8534e85e9c8..d4a0b05428b 100644 --- a/crates/table/src/pointer_map.rs +++ b/crates/table/src/pointer_map.rs @@ -283,7 +283,7 @@ impl PointerMap { /// /// Returns whether the association was deleted. pub fn remove(&mut self, hash: RowHash, ptr: RowPointer) -> bool { - let ret = 'fun: { + 'fun: { let Entry::Occupied(mut entry) = self.map.entry(hash) else { break 'fun false; }; @@ -314,9 +314,7 @@ impl PointerMap { } true - }; - - ret + } } /// Returns an iterator over all row hash x row pointer pairs. diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs index 01dd9f6bf69..13cb9872b96 100644 --- a/crates/testing/src/lib.rs +++ b/crates/testing/src/lib.rs @@ -28,25 +28,26 @@ pub fn invoke_cli(paths: &SpacetimePaths, args: &[&str]) { .map(|v| v.eq_ignore_ascii_case("true")) .unwrap_or(false); - if use_custom && cmd == "generate" { - if let Ok(custom_path) = env::var("CUSTOM_SPACETIMEDB_PATH") { - // Call the dev CLI exactly like the manual command: - // cargo run --bin spacetimedb-cli -- generate ... - let status = Command::new("cargo") - .current_dir(&custom_path) // Ensure we run in the custom path directory - .arg("run") - .arg("--bin") - .arg("spacetimedb-cli") - .arg("--") - .args(args) // `args` are like ["generate", "--lang", ...] - .status() - .expect("Failed to run custom SpacetimeDB CLI via cargo"); + if use_custom + && cmd == "generate" + && let Ok(custom_path) = env::var("CUSTOM_SPACETIMEDB_PATH") + { + // Call the dev CLI exactly like the manual command: + // cargo run --bin spacetimedb-cli -- generate ... + let status = Command::new("cargo") + .current_dir(&custom_path) // Ensure we run in the custom path directory + .arg("run") + .arg("--bin") + .arg("spacetimedb-cli") + .arg("--") + .args(args) // `args` are like ["generate", "--lang", ...] + .status() + .expect("Failed to run custom SpacetimeDB CLI via cargo"); - assert!(status.success(), "Custom SpacetimeDB CLI failed"); - return; - } - // If CUSTOM_SPACETIMEDB_PATH is missing, fall through to the default behavior. + assert!(status.success(), "Custom SpacetimeDB CLI failed"); + return; } + // If CUSTOM_SPACETIMEDB_PATH is missing, fall through to the default behavior. // Default: run in-process CLI (fast/path-friendly for tests). let config = Config::new_with_localhost(paths.cli_config_dir.cli_toml()); diff --git a/crates/update/src/cli/install.rs b/crates/update/src/cli/install.rs index bc02273ee29..4ddf8289f98 100644 --- a/crates/update/src/cli/install.rs +++ b/crates/update/src/cli/install.rs @@ -125,10 +125,10 @@ pub(super) async fn download_and_install( .await? .error_for_status() .map_err(|e| { - if e.status() == Some(reqwest::StatusCode::NOT_FOUND) { - if let Some(version) = &version { - return anyhow::anyhow!(e).context(format!("No release found for version {version}")); - } + if e.status() == Some(reqwest::StatusCode::NOT_FOUND) + && let Some(version) = &version + { + return anyhow::anyhow!(e).context(format!("No release found for version {version}")); } anyhow::anyhow!(e).context("Could not fetch release info") })? diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs index 886982ae02e..b3d4ef5020f 100644 --- a/crates/vm/src/expr.rs +++ b/crates/vm/src/expr.rs @@ -1929,11 +1929,11 @@ impl QueryExpr { query: Vec::with_capacity(self.query.len()), }; - if matches!(&*self.query, [Query::IndexJoin(_)]) { - if let Some(Query::IndexJoin(join)) = self.query.pop() { - q.query.push(Query::IndexJoin(join.reorder(row_count))); - return q; - } + if matches!(&*self.query, [Query::IndexJoin(_)]) + && let Some(Query::IndexJoin(join)) = self.query.pop() + { + q.query.push(Query::IndexJoin(join.reorder(row_count))); + return q; } for query in self.query { diff --git a/crates/vm/src/rel_ops.rs b/crates/vm/src/rel_ops.rs index 47250b71d60..088049f33bd 100644 --- a/crates/vm/src/rel_ops.rs +++ b/crates/vm/src/rel_ops.rs @@ -224,12 +224,11 @@ where // If we can relate `KeyLhs` and `KeyRhs`, we have candidate. // If that candidate still has rhs elements, test against the predicate and yield. - if let Some(rvv) = self.map.get_mut(&k) { - if let Some(rhs) = rvv.pop() { - if (self.predicate)(lhs, &rhs) { - return Some((self.projection)(lhs.clone(), rhs)); - } - } + if let Some(rvv) = self.map.get_mut(&k) + && let Some(rhs) = rvv.pop() + && (self.predicate)(lhs, &rhs) + { + return Some((self.projection)(lhs.clone(), rhs)); } self.left = None; continue; diff --git a/demo/Blackholio/server-rust/Cargo.toml b/demo/Blackholio/server-rust/Cargo.toml index 1acb7c7f811..d8217e1ffe1 100644 --- a/demo/Blackholio/server-rust/Cargo.toml +++ b/demo/Blackholio/server-rust/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "spacetime-module" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/modules/keynote-benchmarks/src/lib.rs b/modules/keynote-benchmarks/src/lib.rs index 700ee0a3abc..3ba8394089c 100644 --- a/modules/keynote-benchmarks/src/lib.rs +++ b/modules/keynote-benchmarks/src/lib.rs @@ -42,8 +42,8 @@ fn init(ctx: &ReducerContext) { let db = ctx.db(); let mut rng = ctx.rng(); for id in 0..1_000_000 { - let (x, y, z) = rng.gen(); - let (dx, dy, dz) = rng.gen(); + let (x, y, z) = rng.r#gen(); + let (dx, dy, dz) = rng.r#gen(); db.position().insert(Position { id, x, y, z }); db.velocity().insert(Velocity { id, dx, dy, dz }); } diff --git a/modules/sdk-test-procedure/src/lib.rs b/modules/sdk-test-procedure/src/lib.rs index 960b316d958..95ae9b523b1 100644 --- a/modules/sdk-test-procedure/src/lib.rs +++ b/modules/sdk-test-procedure/src/lib.rs @@ -168,10 +168,10 @@ fn sorted_uuids_insert(ctx: &mut ProcedureContext) { // Verify UUIDs are sorted let mut last_uuid = None; for row in ctx.db.pk_uuid().iter() { - if let Some(last) = last_uuid { - if last >= row.u { - panic!("UUIDs are not sorted correctly"); - } + if let Some(last) = last_uuid + && last >= row.u + { + panic!("UUIDs are not sorted correctly"); } last_uuid = Some(row.u); } diff --git a/modules/sdk-test/src/lib.rs b/modules/sdk-test/src/lib.rs index e01a80f7b51..1f40f394bae 100644 --- a/modules/sdk-test/src/lib.rs +++ b/modules/sdk-test/src/lib.rs @@ -892,10 +892,10 @@ fn sorted_uuids_insert(ctx: &ReducerContext) -> anyhow::Result<()> { // Verify UUIDs are sorted let mut last_uuid = None; for row in ctx.db.pk_uuid().iter() { - if let Some(last) = last_uuid { - if last >= row.u { - return Err(anyhow!("UUIDs are not sorted correctly")); - } + if let Some(last) = last_uuid + && last >= row.u + { + return Err(anyhow!("UUIDs are not sorted correctly")); } last_uuid = Some(row.u); } diff --git a/sdks/rust/src/client_cache.rs b/sdks/rust/src/client_cache.rs index 22d9b4b69b2..7c4b511c72a 100644 --- a/sdks/rust/src/client_cache.rs +++ b/sdks/rust/src/client_cache.rs @@ -418,7 +418,7 @@ impl TableHandle { } /// Called by the autogenerated implementation of the [`crate::Table`] method of the same name. - pub fn iter(&self) -> impl Iterator { + pub fn iter(&self) -> impl Iterator + use { self.with_table_cache(|table| table.entries.values().map(|e| e.row.clone()).collect::>()) .into_iter() } diff --git a/sdks/rust/src/db_connection.rs b/sdks/rust/src/db_connection.rs index 3aff9776977..b5e74383adf 100644 --- a/sdks/rust/src/db_connection.rs +++ b/sdks/rust/src/db_connection.rs @@ -111,7 +111,7 @@ impl DbContextImpl { /// Process a parsed WebSocket message, /// applying its mutations to the client cache and invoking callbacks. fn process_message(&self, msg: ParsedMessage) -> crate::Result<()> { - let res = match msg { + match msg { // Error: treat this as an erroneous disconnect. ParsedMessage::Error(e) => { let disconnect_ctx = self.make_event_ctx(Some(e.clone())); @@ -260,9 +260,7 @@ impl DbContextImpl { .resolve(&ctx, request_id, result); Ok(()) } - }; - - res + } } fn apply_update( diff --git a/sdks/rust/src/subscription.rs b/sdks/rust/src/subscription.rs index f4df1542565..710ec78220a 100644 --- a/sdks/rust/src/subscription.rs +++ b/sdks/rust/src/subscription.rs @@ -96,10 +96,13 @@ impl SubscriptionManager { // This means that the subscription was cancelled before it was started. // We skip sending the subscription start message. self.subscriptions.remove(&query_set_id); - if let Some(callback) = sub.on_ended() { - return PendingUnsubscribeResult::RunCallback(callback); - } else { - return PendingUnsubscribeResult::DoNothing; + match sub.on_ended() { + Some(callback) => { + return PendingUnsubscribeResult::RunCallback(callback); + } + _ => { + return PendingUnsubscribeResult::DoNothing; + } } } if sub.is_ended() { diff --git a/sdks/rust/tests/connect_disconnect_client/src/main.rs b/sdks/rust/tests/connect_disconnect_client/src/main.rs index d5ab3cc889d..9b17f1bf9c1 100644 --- a/sdks/rust/tests/connect_disconnect_client/src/main.rs +++ b/sdks/rust/tests/connect_disconnect_client/src/main.rs @@ -33,10 +33,13 @@ fn main() { .on_applied(move |ctx| { let check = || { anyhow::ensure!(ctx.db.connected().count() == 1); - if let Some(_row) = ctx.db.connected().iter().next() { - // TODO: anyhow::ensure!(row.identity == ctx.identity().unwrap()); - } else { - anyhow::bail!("Expected one row but Connected::iter().next() returned None"); + match ctx.db.connected().iter().next() { + Some(_row) => { + // TODO: anyhow::ensure!(row.identity == ctx.identity().unwrap()); + } + _ => { + anyhow::bail!("Expected one row but Connected::iter().next() returned None"); + } } Ok(()) }; @@ -85,10 +88,13 @@ fn main() { .on_applied(move |ctx| { let check = || { anyhow::ensure!(ctx.db.disconnected().count() == 1); - if let Some(_row) = ctx.db.disconnected().iter().next() { - // TODO: anyhow::ensure!(row.identity == ctx.identity().unwrap()); - } else { - anyhow::bail!("Expected one row but Disconnected::iter().next() returned None"); + match ctx.db.disconnected().iter().next() { + Some(_row) => { + // TODO: anyhow::ensure!(row.identity == ctx.identity().unwrap()); + } + _ => { + anyhow::bail!("Expected one row but Disconnected::iter().next() returned None"); + } } Ok(()) }; diff --git a/sdks/unreal/Cargo.toml b/sdks/unreal/Cargo.toml index cfee1f430d2..4a22316d11b 100644 --- a/sdks/unreal/Cargo.toml +++ b/sdks/unreal/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "sdk-unreal-test-harness" #version = "0.1.0" -#edition = "2021" +#edition = "2024" #publish = false version.workspace = true diff --git a/templates/basic-cpp/Cargo.toml b/templates/basic-cpp/Cargo.toml index 5d1fabdc702..902a2dfda7f 100644 --- a/templates/basic-cpp/Cargo.toml +++ b/templates/basic-cpp/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "spacetimedb-client" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] spacetimedb-sdk = "1.11.*" diff --git a/templates/basic-rs/spacetimedb/Cargo.toml b/templates/basic-rs/spacetimedb/Cargo.toml index 408a33ee7f0..5aef9971709 100644 --- a/templates/basic-rs/spacetimedb/Cargo.toml +++ b/templates/basic-rs/spacetimedb/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "basic-rs-template-module" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tools/ci/src/main.rs b/tools/ci/src/main.rs index 240814f3287..25a765d56e9 100644 --- a/tools/ci/src/main.rs +++ b/tools/ci/src/main.rs @@ -109,11 +109,11 @@ fn overlay_unity_meta_skeleton(pkg_id: &str) -> Result<()> { // Copy spacetimedb..meta let pkg_root_meta = skeleton_base.join(format!("{pkg_id}.meta")); - if pkg_root_meta.exists() { - if let Some(parent) = pkg_root.parent() { - let pkg_meta_dst = parent.join(format!("{pkg_id}.meta")); - fs::copy(&pkg_root_meta, &pkg_meta_dst)?; - } + if pkg_root_meta.exists() + && let Some(parent) = pkg_root.parent() + { + let pkg_meta_dst = parent.join(format!("{pkg_id}.meta")); + fs::copy(&pkg_root_meta, &pkg_meta_dst)?; } let versioned_dir = match find_only_subdir(&pkg_root) { @@ -126,14 +126,14 @@ fn overlay_unity_meta_skeleton(pkg_id: &str) -> Result<()> { // If version.meta exists under the skeleton package, rename it to match the restored version dir. let version_meta_template = skeleton_root.join("version.meta"); - if version_meta_template.exists() { - if let Some(parent) = versioned_dir.parent() { - let version_name = versioned_dir - .file_name() - .expect("versioned directory should have a file name"); - let version_meta_dst = parent.join(format!("{}.meta", version_name.to_string_lossy())); - fs::copy(&version_meta_template, &version_meta_dst)?; - } + if version_meta_template.exists() + && let Some(parent) = versioned_dir.parent() + { + let version_name = versioned_dir + .file_name() + .expect("versioned directory should have a file name"); + let version_meta_dst = parent.join(format!("{}.meta", version_name.to_string_lossy())); + fs::copy(&version_meta_template, &version_meta_dst)?; } copy_overlay_dir(&skeleton_root, &versioned_dir) diff --git a/tools/gen-bindings/Cargo.toml b/tools/gen-bindings/Cargo.toml index 343564fba45..c0aec0d512c 100644 --- a/tools/gen-bindings/Cargo.toml +++ b/tools/gen-bindings/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "gen-bindings" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] anyhow = "1" diff --git a/tools/generate-client-api/Cargo.toml b/tools/generate-client-api/Cargo.toml index e6645aa15b0..c73b4607300 100644 --- a/tools/generate-client-api/Cargo.toml +++ b/tools/generate-client-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "generate-client-api" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] tempfile = "3" diff --git a/tools/license-check/Cargo.toml b/tools/license-check/Cargo.toml index b8485f164e7..b38b103e95a 100644 --- a/tools/license-check/Cargo.toml +++ b/tools/license-check/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "check-license-symlinks" version = "0.1.0" -edition = "2021" +edition = "2024" [[bin]] name = "license-check" diff --git a/tools/replace-spacetimedb/Cargo.toml b/tools/replace-spacetimedb/Cargo.toml index 9cb80ef0282..ef4fc11e572 100644 --- a/tools/replace-spacetimedb/Cargo.toml +++ b/tools/replace-spacetimedb/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "replace-spacetimedb" version = "0.1.0" -edition = "2021" +edition = "2024" [lib] name = "replace_spacetimedb" diff --git a/tools/xtask-llm-benchmark/src/bench/runner.rs b/tools/xtask-llm-benchmark/src/bench/runner.rs index c71a7192a52..8d7726f2829 100644 --- a/tools/xtask-llm-benchmark/src/bench/runner.rs +++ b/tools/xtask-llm-benchmark/src/bench/runner.rs @@ -513,22 +513,22 @@ pub async fn run_selected_for_model_async_for_lang(cfg: &BenchRunContext<'_>) -> } pub async fn run_selected_or_all_for_model_async_for_lang(ctx: &BenchRunContext<'_>) -> Result> { - if let Some(sels) = ctx.selectors { - if !sels.is_empty() { - let sel_cfg = BenchRunContext { - bench_root: ctx.bench_root, - mode: ctx.mode, - hash: ctx.hash, - route: ctx.route, - context: ctx.context, - llm: ctx.llm, - lang: ctx.lang, - selectors: Option::from(sels), - host: ctx.host.clone(), - details_path: ctx.details_path.clone(), - }; - return run_selected_for_model_async_for_lang(&sel_cfg).await; - } + if let Some(sels) = ctx.selectors + && !sels.is_empty() + { + let sel_cfg = BenchRunContext { + bench_root: ctx.bench_root, + mode: ctx.mode, + hash: ctx.hash, + route: ctx.route, + context: ctx.context, + llm: ctx.llm, + lang: ctx.lang, + selectors: Option::from(sels), + host: ctx.host.clone(), + details_path: ctx.details_path.clone(), + }; + return run_selected_for_model_async_for_lang(&sel_cfg).await; } run_all_for_model_async_for_lang(ctx).await diff --git a/tools/xtask-llm-benchmark/src/bin/llm_benchmark.rs b/tools/xtask-llm-benchmark/src/bin/llm_benchmark.rs index 535b579af27..61d1b23f804 100644 --- a/tools/xtask-llm-benchmark/src/bin/llm_benchmark.rs +++ b/tools/xtask-llm-benchmark/src/bin/llm_benchmark.rs @@ -859,12 +859,12 @@ fn filter_routes(config: &RunConfig) -> Vec { .iter() .filter(|r| config.providers_filter.as_ref().is_none_or(|f| f.contains(&r.vendor))) .filter(|r| { - if let Some(map) = &config.model_filter { - if let Some(allowed) = map.get(&r.vendor) { - let api = r.api_model.to_ascii_lowercase(); - let dn = r.display_name.to_ascii_lowercase(); - return allowed.contains(&api) || allowed.contains(&dn); - } + if let Some(map) = &config.model_filter + && let Some(allowed) = map.get(&r.vendor) + { + let api = r.api_model.to_ascii_lowercase(); + let dn = r.display_name.to_ascii_lowercase(); + return allowed.contains(&api) || allowed.contains(&dn); } true }) @@ -991,14 +991,12 @@ fn collect_task_numbers_in_categories(bench_root: &Path, cats: &HashSet) continue; } let name = entry.file_name().to_string_lossy().into_owned(); - if let Some(rest) = name.strip_prefix("t_") { - if let Some((num_str, _)) = rest.split_once('_') { - if num_str.len() == 3 { - if let Ok(n) = num_str.parse::() { - nums.insert(n); - } - } - } + if let Some(rest) = name.strip_prefix("t_") + && let Some((num_str, _)) = rest.split_once('_') + && num_str.len() == 3 + && let Ok(n) = num_str.parse::() + { + nums.insert(n); } } } @@ -1081,10 +1079,10 @@ fn cmd_analyze(args: AnalyzeArgs) -> Result<()> { for lang_entry in &results.languages { // Skip if filtering by language - if let Some(filter_lang) = &args.lang { - if lang_entry.lang != filter_lang.as_str() { - continue; - } + if let Some(filter_lang) = &args.lang + && lang_entry.lang != filter_lang.as_str() + { + continue; } let golden_answers = &lang_entry.golden_answers; diff --git a/tools/xtask-llm-benchmark/src/context/combine.rs b/tools/xtask-llm-benchmark/src/context/combine.rs index de281e3308e..c4d776b0055 100644 --- a/tools/xtask-llm-benchmark/src/context/combine.rs +++ b/tools/xtask-llm-benchmark/src/context/combine.rs @@ -183,10 +183,10 @@ struct Row { } fn belongs_to_crate(paths: &serde_json::Map, id: &str, crate_name: &str) -> bool { - if let Some(p) = paths.get(id).and_then(Value::as_object) { - if let Some(arr) = p.get("path").and_then(Value::as_array) { - return arr.first().and_then(Value::as_str) == Some(crate_name); - } + if let Some(p) = paths.get(id).and_then(Value::as_object) + && let Some(arr) = p.get("path").and_then(Value::as_array) + { + return arr.first().and_then(Value::as_str) == Some(crate_name); } false } @@ -197,14 +197,14 @@ fn full_path( id: &str, crate_name: &str, ) -> String { - if let Some(p) = paths.get(id).and_then(Value::as_object) { - if let Some(arr) = p.get("path").and_then(Value::as_array) { - let mut segs: Vec = arr.iter().filter_map(Value::as_str).map(|s| s.to_string()).collect(); - if let Some(name) = index.get(id).and_then(|it| it.get("name")).and_then(Value::as_str) { - segs.push(name.to_string()); - } - return segs.join("::"); + if let Some(p) = paths.get(id).and_then(Value::as_object) + && let Some(arr) = p.get("path").and_then(Value::as_array) + { + let mut segs: Vec = arr.iter().filter_map(Value::as_str).map(|s| s.to_string()).collect(); + if let Some(name) = index.get(id).and_then(|it| it.get("name")).and_then(Value::as_str) { + segs.push(name.to_string()); } + return segs.join("::"); } let nm = index .get(id) @@ -218,10 +218,10 @@ fn item_kind(item: &Value) -> String { if let Some(k) = item.get("kind").and_then(Value::as_str) { return k.to_string(); } - if let Some(inner) = item.get("inner").and_then(Value::as_object) { - if let Some((k, _)) = inner.iter().next() { - return k.to_string(); - } + if let Some(inner) = item.get("inner").and_then(Value::as_object) + && let Some((k, _)) = inner.iter().next() + { + return k.to_string(); } "unknown".to_string() } @@ -232,10 +232,10 @@ fn item_docs(item: &Value) -> String { } if let Some(inner) = item.get("inner").and_then(Value::as_object) { for (_k, v) in inner { - if let Some(m) = v.as_object() { - if let Some(d) = m.get("docs").and_then(Value::as_str) { - return d.to_string(); - } + if let Some(m) = v.as_object() + && let Some(d) = m.get("docs").and_then(Value::as_str) + { + return d.to_string(); } } } diff --git a/tools/xtask-llm-benchmark/src/eval/types.rs b/tools/xtask-llm-benchmark/src/eval/types.rs index 60013e95281..ffd6e318cdf 100644 --- a/tools/xtask-llm-benchmark/src/eval/types.rs +++ b/tools/xtask-llm-benchmark/src/eval/types.rs @@ -31,33 +31,29 @@ impl ScoreDetails { } // Check for table diff (schema_parity scorer) - if let Some(tables_diff) = notes.get("tables_diff") { - if !tables_diff.is_null() { - if let Ok(diff) = serde_json::from_value::(tables_diff.clone()) { - if !diff.only_golden.is_empty() || !diff.only_llm.is_empty() { - let golden_names: Vec<_> = diff.only_golden.keys().collect(); - let llm_names: Vec<_> = diff.only_llm.keys().collect(); - return Some(format!( - "tables differ - expected {:?}, got {:?}", - golden_names, llm_names - )); - } - } - } + if let Some(tables_diff) = notes.get("tables_diff") + && !tables_diff.is_null() + && let Ok(diff) = serde_json::from_value::(tables_diff.clone()) + && (!diff.only_golden.is_empty() || !diff.only_llm.is_empty()) + { + let golden_names: Vec<_> = diff.only_golden.keys().collect(); + let llm_names: Vec<_> = diff.only_llm.keys().collect(); + return Some(format!( + "tables differ - expected {:?}, got {:?}", + golden_names, llm_names + )); } // Check for reducer diff - if let Some(reducers_diff) = notes.get("reducers_diff") { - if !reducers_diff.is_null() { - if let Ok(diff) = serde_json::from_value::(reducers_diff.clone()) { - if !diff.only_golden.is_empty() || !diff.only_llm.is_empty() { - return Some(format!( - "reducers differ - expected {:?}, got {:?}", - diff.only_golden, diff.only_llm - )); - } - } - } + if let Some(reducers_diff) = notes.get("reducers_diff") + && !reducers_diff.is_null() + && let Ok(diff) = serde_json::from_value::(reducers_diff.clone()) + && (!diff.only_golden.is_empty() || !diff.only_llm.is_empty()) + { + return Some(format!( + "reducers differ - expected {:?}, got {:?}", + diff.only_golden, diff.only_llm + )); } Some("failed".to_string()) diff --git a/tools/xtask-llm-benchmark/src/llm/clients/meta.rs b/tools/xtask-llm-benchmark/src/llm/clients/meta.rs index b71e2863f82..e384d81b7b1 100644 --- a/tools/xtask-llm-benchmark/src/llm/clients/meta.rs +++ b/tools/xtask-llm-benchmark/src/llm/clients/meta.rs @@ -53,13 +53,13 @@ impl MetaLlamaClient { let mut messages: Vec = Vec::new(); - if let Some(sys) = system.as_deref() { - if !sys.is_empty() { - messages.push(Msg { - role: "system", - content: sys, - }); - } + if let Some(sys) = system.as_deref() + && !sys.is_empty() + { + messages.push(Msg { + role: "system", + content: sys, + }); } if !static_prefix.is_empty() { messages.push(Msg { diff --git a/tools/xtask-llm-benchmark/src/llm/clients/openai.rs b/tools/xtask-llm-benchmark/src/llm/clients/openai.rs index 2c58c784ee4..c95a44cedc7 100644 --- a/tools/xtask-llm-benchmark/src/llm/clients/openai.rs +++ b/tools/xtask-llm-benchmark/src/llm/clients/openai.rs @@ -145,34 +145,34 @@ impl OpenAiClient { let parsed: ResponsesPayload = serde_json::from_str(&body).context("parse OpenAI response")?; - if let Some(t) = parsed.output_text.as_ref() { - if !t.is_empty() { - return Ok(t.clone()); - } + if let Some(t) = parsed.output_text.as_ref() + && !t.is_empty() + { + return Ok(t.clone()); } if let Some(items) = parsed.output.as_ref() { for it in items { - if it.r#type.as_deref() == Some("message") { - if let Some(content) = &it.content { - for c in content { - if let Some(txt) = &c.text { - if !txt.is_empty() { - return Ok(txt.clone()); - } - } + if it.r#type.as_deref() == Some("message") + && let Some(content) = &it.content + { + for c in content { + if let Some(txt) = &c.text + && !txt.is_empty() + { + return Ok(txt.clone()); } } } } for it in items { - if it.r#type.as_deref() == Some("reasoning") { - if let Some(summary) = &it.summary { - for c in summary { - if let Some(txt) = &c.text { - if !txt.is_empty() { - return Ok(txt.clone()); - } - } + if it.r#type.as_deref() == Some("reasoning") + && let Some(summary) = &it.summary + { + for c in summary { + if let Some(txt) = &c.text + && !txt.is_empty() + { + return Ok(txt.clone()); } } } diff --git a/tools/xtask-llm-benchmark/src/llm/segmentation.rs b/tools/xtask-llm-benchmark/src/llm/segmentation.rs index b30d58de907..8e2bce7cd14 100644 --- a/tools/xtask-llm-benchmark/src/llm/segmentation.rs +++ b/tools/xtask-llm-benchmark/src/llm/segmentation.rs @@ -243,16 +243,16 @@ pub fn non_context_reserve_tokens_env(vendor: Vendor) -> usize { Vendor::DeepSeek => "DEEPSEEK_RESERVE_TOKENS", Vendor::Meta => "META_RESERVE_TOKENS", }; - if let Ok(v) = std::env::var(key) { - if let Ok(n) = v.parse::() { - return round_500(n.max(2_000)); - } + if let Ok(v) = std::env::var(key) + && let Ok(n) = v.parse::() + { + return round_500(n.max(2_000)); } // global override - if let Ok(v) = std::env::var("LLM_RESERVE_TOKENS") { - if let Ok(n) = v.parse::() { - return round_500(n.max(2_000)); - } + if let Ok(v) = std::env::var("LLM_RESERVE_TOKENS") + && let Ok(n) = v.parse::() + { + return round_500(n.max(2_000)); } // defaults (conservative)