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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
fn_params_layout="Tall"
hard_tabs=true
use_field_init_shorthand=true

max_width=200
fn_params_layout = "Tall"
hard_tabs = true
use_field_init_shorthand = true
use_small_heuristics = "Max"
max_width = 200
5 changes: 1 addition & 4 deletions ruva-core/src/bus_components/contexts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ impl Context {
pub async fn send_internally_notifiable_messages(&mut self) {
// SAFETY: This is safe because we are sure that the context manager is not dropped

self.curr_events
.iter()
.filter(|e| e.internally_notifiable())
.for_each(|e| self.super_ctx.get_mut().push_back(e.clone()));
self.curr_events.iter().filter(|e| e.internally_notifiable()).for_each(|e| self.super_ctx.get_mut().push_back(e.clone()));
}
}

Expand Down
6 changes: 1 addition & 5 deletions ruva-core/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ pub trait TEvent: Sync + Send + Downcast {

fn metadata(&self) -> EventMetadata {
let event_name = std::any::type_name::<Self>().split("::").last().unwrap();
EventMetadata {
aggregate_id: Default::default(),
aggregate_name: Default::default(),
topic: event_name.to_string(),
}
EventMetadata { aggregate_id: Default::default(), aggregate_name: Default::default(), topic: event_name.to_string() }
}
fn outbox(&self) -> OutBox {
let metadata = self.metadata();
Expand Down
10 changes: 1 addition & 9 deletions ruva-core/src/outbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,6 @@ pub struct OutBox {

impl OutBox {
pub fn new(aggregate_id: String, aggregate_name: String, topic: String, state: String) -> Self {
Self {
id: *SnowFlake::generate(),
aggregate_id,
aggregate_name,
topic,
state,
processed: false,
create_dt: Default::default(),
}
Self { id: *SnowFlake::generate(), aggregate_id, aggregate_name, topic, state, processed: false, create_dt: Default::default() }
}
}
12 changes: 2 additions & 10 deletions ruva-core/src/snowflake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,7 @@ impl NumericalUniqueIdGenerator {
fn ts_seq(&self) -> TimeStampSeq {
const MASKING: i64 = 0xFFF;
let ts_seq = self.ts_seq.load(Ordering::Relaxed);
TimeStampSeq {
ts: ts_seq >> 12,
seq: ts_seq & MASKING,
}
TimeStampSeq { ts: ts_seq >> 12, seq: ts_seq & MASKING }
}

/// Constructs a new `NumericalUniqueIdGenerator` using the specified epoch.
Expand All @@ -105,12 +102,7 @@ impl NumericalUniqueIdGenerator {
//TODO:limit the maximum of input args datacenter_id and machine_id
let timestamp = current_time_in_milli(epoch);

NumericalUniqueIdGenerator {
epoch,
datacenter_id,
machine_id,
ts_seq: AtomicI64::new(timestamp << 12),
}
NumericalUniqueIdGenerator { epoch, datacenter_id, machine_id, ts_seq: AtomicI64::new(timestamp << 12) }
}

/// within 64 bits:
Expand Down
8 changes: 3 additions & 5 deletions ruva-macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@ repository = "https://github.com/BeringLab/ruva"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
proc-macro=true
proc-macro = true

[dependencies]
syn = {version="2", features=["full","derive"]}
syn = { version = "2", features = ["full", "derive"] }
quote = "1"
proc-macro2="1"
proc-macro2 = "1"
regex = "1.10.6"


19 changes: 3 additions & 16 deletions ruva-macro/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,11 @@ const COMMAND_CONSTRAINT: [&str; 4] = ["Send", "Sync", "'static", "std::fmt::Deb
fn craete_into_statement_from_struct_command(original_name: &syn::Ident, body_derive: &mut DeriveInput, data_struct: DataStruct) -> proc_macro2::TokenStream {
let body_name = syn::Ident::new(&(original_name.to_string() + "Body"), original_name.span());

let DataStruct {
fields: Fields::Named(syn::FieldsNamed { named, brace_token }),
struct_token,
semi_token,
} = &data_struct
else {
let DataStruct { fields: Fields::Named(syn::FieldsNamed { named, brace_token }), struct_token, semi_token } = &data_struct else {
panic!("Only Struct Allowed!");
};

let input_required_values = named
.iter()
.filter(|f| get_attributes(f).into_iter().any(|ident| ident == *"required_input"))
.cloned()
.collect::<Punctuated<syn::Field, syn::token::Comma>>();
let input_required_values = named.iter().filter(|f| get_attributes(f).into_iter().any(|ident| ident == *"required_input")).cloned().collect::<Punctuated<syn::Field, syn::token::Comma>>();

let mut idents_in_vec: Vec<String> = vec![];
let mut types_in_vec: Vec<String> = vec![];
Expand Down Expand Up @@ -85,11 +76,7 @@ fn craete_into_statement_from_struct_command(original_name: &syn::Ident, body_de

// Convert the generics to a string
add_sync_trait_bounds(&mut body_derive.generics, &COMMAND_CONSTRAINT);
let generics = if body_derive.generics.params.is_empty() {
String::new()
} else {
format!("{}", body_derive.generics.to_token_stream())
};
let generics = if body_derive.generics.params.is_empty() { String::new() } else { format!("{}", body_derive.generics.to_token_stream()) };

// Convert the where clause to a string (if it exists)
let where_clause = match &body_derive.generics.where_clause {
Expand Down
17 changes: 3 additions & 14 deletions ruva-macro/src/domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,7 @@ pub(crate) fn render_entity_token(input: TokenStream, attrs: TokenStream) -> Tok
}

pub(crate) fn set_entity_fields(input_data: &mut syn::Data, for_aggregate: bool) -> proc_macro2::TokenStream {
if let syn::Data::Struct(DataStruct {
fields: syn::Fields::Named(ref mut fields),
..
}) = input_data
{
if let syn::Data::Struct(DataStruct { fields: syn::Fields::Named(ref mut fields), .. }) = input_data {
fields.named.iter_mut().for_each(|f| {
skip_over_attributes(f, "adapter_ignore");
});
Expand Down Expand Up @@ -145,10 +141,7 @@ fn get_setters(data: &Data) -> proc_macro2::TokenStream {
for f in field_idents {
let ident = f.ident.unwrap();
let ty = f.ty.to_token_stream().to_string();
let code = format!(
"pub fn set_{}(&mut self, {}:impl core::convert::Into<{}>){{self.{}={}.into();self.is_updated=true}}",
ident, ident, ty, ident, ident
);
let code = format!("pub fn set_{}(&mut self, {}:impl core::convert::Into<{}>){{self.{}={}.into();self.is_updated=true}}", ident, ident, ty, ident, ident);
quotes.push(code);
}
let joined: proc_macro2::TokenStream = quotes.join(" ").parse().unwrap();
Expand All @@ -167,11 +160,7 @@ pub fn create_struct_adapter_quote(input: &DeriveInput, for_aggregate: bool) ->

let mut fields_to_ignore: Vec<String> = vec![];

if let syn::Data::Struct(DataStruct {
fields: syn::Fields::Named(ref mut fields),
..
}) = &mut adapter_input.data
{
if let syn::Data::Struct(DataStruct { fields: syn::Fields::Named(ref mut fields), .. }) = &mut adapter_input.data {
fields.named.iter_mut().for_each(|f: &mut Field| {
if let Some(ignorable_field) = check_if_field_has_attribute(f, "adapter_ignore") {
// if the field's type is generic, skip over
Expand Down
16 changes: 1 addition & 15 deletions ruva-macro/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,7 @@ use syn::{punctuated::Punctuated, token::Comma, FnArg, Ident, ImplItemFn, ItemFn
#[allow(unused)]
pub fn parse_handler(ast: ItemFn) -> TokenStream {
const OUTPUT_TYPE_NOT_VALID: &str = "#[handler] fn must have valid output type";
let ItemFn {
sig: Signature {
ident,
output: ReturnType::Type(_, var),
inputs,
generics,
asyncness,
..
},
block,
..
} = ast
else {
panic!("{}", OUTPUT_TYPE_NOT_VALID)
};
let ItemFn { sig: Signature { ident, output: ReturnType::Type(_, var), inputs, generics, asyncness, .. }, block, .. } = ast else { panic!("{}", OUTPUT_TYPE_NOT_VALID) };

if inputs.is_empty() {
panic!("There must be message argument!");
Expand Down
12 changes: 2 additions & 10 deletions ruva-macro/src/helpers/generic_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,8 @@ pub fn add_aggregate_generic_defaults(generics: &mut Generics) {
.iter()
.filter_map(|param| {
if let GenericParam::Type(ty) = param {
let bounded_ty = Type::Path(TypePath {
qself: None,
path: ty.ident.clone().into(),
});
Some(WherePredicate::Type(PredicateType {
bounded_ty,
colon_token: Default::default(),
bounds: Punctuated::new(),
lifetimes: None,
}))
let bounded_ty = Type::Path(TypePath { qself: None, path: ty.ident.clone().into() });
Some(WherePredicate::Type(PredicateType { bounded_ty, colon_token: Default::default(), bounds: Punctuated::new(), lifetimes: None }))
} else {
None
}
Expand Down
2 changes: 1 addition & 1 deletion ruva-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ mod result;
mod utils;

#[proc_macro_derive(TEvent, attributes(internally_notifiable, externally_notifiable, identifier))]
pub fn message_derive(attr: TokenStream) -> TokenStream {
pub fn derive_tevent(attr: TokenStream) -> TokenStream {
let mut ast: DeriveInput = syn::parse(attr.clone()).unwrap();
let externally_notifiable_event_req = extract_externally_notifiable_event_req(&mut ast);
let visibilities = render_event_visibility(&ast);
Expand Down
5 changes: 1 addition & 4 deletions ruva-macro/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,7 @@ pub(crate) fn generate_event_metadata(ast: &DeriveInput, aggregate_metadata: Str
let crates = locate_crate_on_derive_macro(ast);

match &ast.data {
Data::Struct(DataStruct {
fields: Fields::Named(FieldsNamed { named, .. }),
..
}) => {
Data::Struct(DataStruct { fields: Fields::Named(FieldsNamed { named, .. }), .. }) => {
let identifier = named.iter().filter(|f| get_attributes(f).into_iter().any(|ident| ident == *"identifier")).collect::<Vec<_>>();
if identifier.len() != 1 {
panic!("One identifier Must Be Given To TEvent!")
Expand Down
26 changes: 3 additions & 23 deletions ruva-macro/src/message_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ fn raise_impl_counter(key: &str) {
fn impl_generator(trait_info: &syn::Path, redeined_methods: &[String]) -> TokenStream2 {
(2..6)
.map(|order| {
let redefiend_methods = redeined_methods
.iter()
.map(|method| syn::parse_str::<syn::ItemFn>(method).expect("Error occurred while generating impl!"))
.collect::<Vec<_>>();
let redefiend_methods = redeined_methods.iter().map(|method| syn::parse_str::<syn::ItemFn>(method).expect("Error occurred while generating impl!")).collect::<Vec<_>>();

let idents: Vec<_> = (2..order + 1).map(|i| syn::Ident::new(&format!("D{}", i), proc_macro2::Span::call_site())).collect();

Expand Down Expand Up @@ -90,19 +87,7 @@ pub(crate) fn render_inject(input: TokenStream, _attrs: TokenStream) -> TokenStr
}

fn render_tuplified_dependencies(input: &ItemFn) -> FnArg {
let dependencies = input
.sig
.inputs
.iter()
.skip(1)
.flat_map(|arg| {
if let FnArg::Typed(pat_type) = arg {
Some((pat_type.pat.clone(), pat_type.ty.clone()))
} else {
None
}
})
.collect::<Vec<_>>();
let dependencies = input.sig.inputs.iter().skip(1).flat_map(|arg| if let FnArg::Typed(pat_type) = arg { Some((pat_type.pat.clone(), pat_type.ty.clone())) } else { None }).collect::<Vec<_>>();
let params = dependencies.iter().map(|(pat, _)| pat).collect::<Vec<_>>();
let types = dependencies.iter().map(|(_, ty)| ty).collect::<Vec<_>>();

Expand Down Expand Up @@ -151,12 +136,7 @@ fn render_proxy_handler(input: &ItemFn, tuple_dep: &FnArg) -> ItemFn {

// ! Optimization - change body so it internally calls original method
let original_name = &input.sig.ident;
let token = format!(
"{}({}){}",
original_name,
dedupled_args.iter().map(|d| d.to_string()).collect::<Vec<_>>().join(","),
if asyncness.is_some() { ".await" } else { "" }
);
let token = format!("{}({}){}", original_name, dedupled_args.iter().map(|d| d.to_string()).collect::<Vec<_>>().join(","), if asyncness.is_some() { ".await" } else { "" });

let expr = syn::parse_str::<syn::Expr>(&token).expect("Expression parsing failed!");

Expand Down
31 changes: 7 additions & 24 deletions ruva-macro/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ use syn::DeriveInput;
use crate::utils::{find_enum_variant, locate_crate_on_derive_macro};

pub(crate) fn render_response_token(ast: &DeriveInput) -> TokenStream {
let syn::Data::Enum(_data) = &ast.data else {
panic!("Only Enum type is supported by #[derive(ApplicationError)].")
};
let syn::Data::Enum(_data) = &ast.data else { panic!("Only Enum type is supported by #[derive(ApplicationError)].") };
let name = &ast.ident;
let crates = locate_crate_on_derive_macro(ast);

Expand Down Expand Up @@ -41,11 +39,7 @@ pub(crate) fn render_error_token(ast: &DeriveInput) -> TokenStream {
panic!("#[stop_sentinel] expects unit.")
}
}
let stop_sentinel = if let Some(stop_sentinel) = stop_sentinel {
stop_sentinel.ident.clone()
} else {
syn::Ident::new("StopSentinel", proc_macro2::Span::call_site())
};
let stop_sentinel = if let Some(stop_sentinel) = stop_sentinel { stop_sentinel.ident.clone() } else { syn::Ident::new("StopSentinel", proc_macro2::Span::call_site()) };

/* \#\[stop_sentinel_with_event\] */
let stop_sentinel_with_event = find_variant("stop_sentinel_with_event");
Expand All @@ -55,17 +49,10 @@ pub(crate) fn render_error_token(ast: &DeriveInput) -> TokenStream {
panic!("#[stop_sentinel_with_event] expects Field(TEvent).")
}
}
let stop_sentinel_with_event = if let Some(stop_sentinel_with_event) = stop_sentinel_with_event {
stop_sentinel_with_event.ident.clone()
} else {
syn::Ident::new("StopSentinelWithEvent", proc_macro2::Span::call_site())
};
let stop_sentinel_with_event_type = if let syn::Fields::Unnamed(field) = &data_enum
.variants
.iter()
.find(|x| x.ident == stop_sentinel_with_event)
.expect("#[stop_sentinel_with_event] and StopSentinelWithEvent field not found.")
.fields
let stop_sentinel_with_event =
if let Some(stop_sentinel_with_event) = stop_sentinel_with_event { stop_sentinel_with_event.ident.clone() } else { syn::Ident::new("StopSentinelWithEvent", proc_macro2::Span::call_site()) };
let stop_sentinel_with_event_type = if let syn::Fields::Unnamed(field) =
&data_enum.variants.iter().find(|x| x.ident == stop_sentinel_with_event).expect("#[stop_sentinel_with_event] and StopSentinelWithEvent field not found.").fields
{
if field.unnamed.len() == 1 {
field.unnamed[0].ty.clone()
Expand All @@ -84,11 +71,7 @@ pub(crate) fn render_error_token(ast: &DeriveInput) -> TokenStream {
panic!("#[database_error] expects Field(Box<AnyError>).")
}
}
let database_error = if let Some(database_error) = database_error {
database_error.ident.clone()
} else {
syn::Ident::new("DatabaseError", proc_macro2::Span::call_site())
};
let database_error = if let Some(database_error) = database_error { database_error.ident.clone() } else { syn::Ident::new("DatabaseError", proc_macro2::Span::call_site()) };

quote!(
impl #crates::ApplicationError for #name {}
Expand Down
26 changes: 5 additions & 21 deletions ruva-macro/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@ use syn::{parse_quote, punctuated::Punctuated, token::Comma, DataEnum, DeriveInp

pub(crate) fn locate_crate_on_derive_macro(ast: &DeriveInput) -> Ident {
let crates = ast.attrs.iter().find(|x| x.path().is_ident("crates"));
let crates = if let Some(crates) = crates {
crates.parse_args::<syn::ExprPath>().unwrap().path.get_ident().expect("#[crates(...)] expects path.").to_string()
} else {
"ruva".to_owned()
};
let crates = if let Some(crates) = crates { crates.parse_args::<syn::ExprPath>().unwrap().path.get_ident().expect("#[crates(...)] expects path.").to_string() } else { "ruva".to_owned() };
syn::Ident::new(&crates, proc_macro2::Span::call_site())
}

Expand All @@ -33,26 +29,16 @@ pub(crate) fn check_if_field_has_attribute(field: &Field, attribute_name: &str)

pub(crate) fn extract_field_names(ast: &DeriveInput) -> Vec<String> {
match &ast.data {
syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(fields), ..
}) => fields.named.iter().filter_map(|f| f.ident.as_ref().map(|ident| ident.to_string())).collect(),
syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(fields), .. }) => fields.named.iter().filter_map(|f| f.ident.as_ref().map(|ident| ident.to_string())).collect(),
_ => panic!("Only Struct is supported"),
}
}

pub(crate) fn remove_fields_based_on_field_name(given_fields: &mut syn::FieldsNamed, fields_to_remove: impl Borrow<Vec<String>>) {
let fields_to_remove = fields_to_remove.borrow();
let new_fields: Punctuated<Field, Comma> = given_fields
.named
.iter()
.filter(|f| f.ident.as_ref().map_or(true, |ident| !fields_to_remove.contains(&ident.to_string())))
.cloned()
.collect();
let new_fields: Punctuated<Field, Comma> = given_fields.named.iter().filter(|f| f.ident.as_ref().map_or(true, |ident| !fields_to_remove.contains(&ident.to_string()))).cloned().collect();

*given_fields = FieldsNamed {
brace_token: syn::token::Brace::default(),
named: new_fields,
};
*given_fields = FieldsNamed { brace_token: syn::token::Brace::default(), named: new_fields };
}

pub(crate) fn skip_over_attributes(field: &mut Field, attribute_name: &str) -> bool {
Expand All @@ -63,9 +49,7 @@ pub(crate) fn skip_over_attributes(field: &mut Field, attribute_name: &str) -> b
}
pub(crate) fn skip_given_attribute(ast: &mut DeriveInput, attribute_name: &str) {
match &mut ast.data {
syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(fields), ..
}) => {
syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(fields), .. }) => {
fields.named.iter_mut().for_each(|f| {
skip_over_attributes(f, attribute_name);
});
Expand Down
Loading
Loading