diff --git a/.gitignore b/.gitignore index 186ed11a6a9..fe8a0aa9183 100644 --- a/.gitignore +++ b/.gitignore @@ -279,3 +279,6 @@ nul # Generated when testing or publishing the TypeScript module test utilities. /crates/bindings-typescript/src/server/test-utils/portable-datastore-wasm/ /crates/bindings-typescript/src/server/test-utils/.portable-datastore-wasm-*/ + +# Local IDC manual testing fixture. +/manual/idc-two-modules/ diff --git a/crates/bindings-macro/src/lib.rs b/crates/bindings-macro/src/lib.rs index 7f30fc22372..e2f7016f88e 100644 --- a/crates/bindings-macro/src/lib.rs +++ b/crates/bindings-macro/src/lib.rs @@ -159,6 +159,10 @@ mod sym { symbol!(repr); symbol!(sats); symbol!(scheduled); + symbol!(outbox); + symbol!(on_result); + symbol!(param); + symbol!(target); symbol!(unique); symbol!(update); symbol!(default); @@ -229,7 +233,10 @@ fn derive_table_helper_attr() -> Attribute { /// /// Provides helper attributes for `#[spacetimedb::table]`, so that we don't get unknown attribute errors. #[doc(hidden)] -#[proc_macro_derive(__TableHelper, attributes(sats, unique, auto_inc, primary_key, index, default))] +#[proc_macro_derive( + __TableHelper, + attributes(sats, unique, auto_inc, primary_key, target, index, default, param) +)] pub fn table_helper(input: StdTokenStream) -> StdTokenStream { schema_type(input) } diff --git a/crates/bindings-macro/src/reducer.rs b/crates/bindings-macro/src/reducer.rs index 0193f2033dd..159e5acbfaf 100644 --- a/crates/bindings-macro/src/reducer.rs +++ b/crates/bindings-macro/src/reducer.rs @@ -10,6 +10,7 @@ use syn::{FnArg, Ident, ItemFn, LitStr, PatType}; pub(crate) struct ReducerArgs { name: Option, lifecycle: Option, + on_result: Option, } enum LifecycleReducer { @@ -51,6 +52,12 @@ impl ReducerArgs { check_duplicate(&args.name, &meta)?; args.name = Some(meta.value()?.parse()?); } + sym::on_result => { + check_duplicate(&args.on_result, &meta)?; + let content; + syn::parenthesized!(content in meta.input); + args.on_result = Some(content.parse()?); + } }); Ok(()) }) @@ -101,6 +108,19 @@ pub(crate) fn reducer_impl(args: ReducerArgs, original_function: &ItemFn) -> syn assert_only_lifetime_generics(original_function, "reducers")?; let lifecycle = args.lifecycle.iter().filter_map(|lc| lc.to_lifecycle_value()); + let on_result_outbox = args.on_result.as_ref().map(|path| { + let accessor = &path.segments.last().unwrap().ident; + quote!( + const ON_RESULT_OUTBOX: Option<&'static str> = + Some(spacetimedb::rt::on_result_outbox(#path::#accessor)); + ) + }); + let on_result_typecheck = args.on_result.as_ref().map(|path| { + let accessor = &path.segments.last().unwrap().ident; + quote! { + spacetimedb::rt::on_result_typecheck(#func_name, #path::#accessor); + } + }); let typed_args = extract_typed_args(original_function)?; @@ -156,6 +176,7 @@ pub(crate) fn reducer_impl(args: ReducerArgs, original_function: &ItemFn) -> syn #(let _ = <#first_arg_ty as spacetimedb::rt::ReducerContextArg>::_ITEM;)* #(let _ = <#rest_arg_tys as spacetimedb::rt::ReducerArg>::_ITEM;)* #(let _ = <#ret_ty as spacetimedb::rt::IntoReducerResult>::into_result;)* + #on_result_typecheck } }; impl #func_name { @@ -170,6 +191,7 @@ pub(crate) fn reducer_impl(args: ReducerArgs, original_function: &ItemFn) -> syn type FnKind = spacetimedb::rt::FnKindReducer; const NAME: &'static str = #reducer_name; #(const LIFECYCLE: Option = Some(#lifecycle);)* + #on_result_outbox const ARG_NAMES: &'static [Option<&'static str>] = &[#(#opt_arg_names),*]; const INVOKE: Self::Invoke = #func_name::invoke; } diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs index e1ff4edec8a..0ec8a13ad25 100644 --- a/crates/bindings-macro/src/table.rs +++ b/crates/bindings-macro/src/table.rs @@ -19,6 +19,7 @@ pub(crate) struct TableArgs { access: Option, name: Option, scheduled: Option, + outbox: Option, accessor: Ident, indices: Vec, event: Option, @@ -47,6 +48,10 @@ struct ScheduledArg { at: Option, } +struct OutboxArg { + receiver_reducer: Path, +} + struct IndexArg { accessor: Ident, canonical_name: Option, @@ -78,6 +83,7 @@ impl TableArgs { pub(crate) fn parse(input: TokenStream, struct_ident: &Ident) -> syn::Result { let mut access = None; let mut scheduled = None; + let mut outbox = None; let mut accessor = None; let mut name: Option = None; let mut indices = Vec::new(); @@ -145,6 +151,10 @@ If you're migrating from SpacetimeDB 1.*, replace `name = {sym}` with `accessor check_duplicate(&scheduled, &meta)?; scheduled = Some(ScheduledArg::parse_meta(meta)?); } + sym::outbox => { + check_duplicate(&outbox, &meta)?; + outbox = Some(OutboxArg::parse_meta(meta)?); + } sym::event => { check_duplicate(&event, &meta)?; event = Some(meta.path.span()); @@ -184,6 +194,7 @@ If you're migrating from SpacetimeDB 1.*, replace `name = {name_str_value:?}` wi Ok(TableArgs { access, scheduled, + outbox, accessor, indices, name, @@ -192,6 +203,22 @@ If you're migrating from SpacetimeDB 1.*, replace `name = {name_str_value:?}` wi } } +impl OutboxArg { + fn parse_meta(meta: ParseNestedMeta) -> syn::Result { + let mut receiver_reducer = None; + + meta.parse_nested_meta(|meta| { + check_duplicate_msg(&receiver_reducer, &meta, "can only specify one outbox receiver reducer")?; + receiver_reducer = Some(meta.path); + Ok(()) + })?; + + let receiver_reducer = receiver_reducer + .ok_or_else(|| meta.error("must specify outbox receiver reducer: outbox(receiver::reducer)"))?; + Ok(Self { receiver_reducer }) + } +} + impl ScheduledArg { fn parse_meta(meta: ParseNestedMeta) -> syn::Result { let span = meta.path.span(); @@ -740,6 +767,7 @@ struct Column<'a> { vis: &'a syn::Visibility, ident: &'a syn::Ident, ty: &'a syn::Type, + param_name: String, default_value: Option, } @@ -769,8 +797,10 @@ enum ColumnAttr { Unique(Span), AutoInc(Span), PrimaryKey(Span), + Target(Span), Index(IndexArg), Default(syn::Expr, Span), + ParamName(Ident), } impl ColumnAttr { @@ -790,6 +820,11 @@ impl ColumnAttr { } else if ident == sym::primary_key { attr.meta.require_path_only()?; Some(ColumnAttr::PrimaryKey(ident.span())) + } else if ident == sym::target { + attr.meta.require_path_only()?; + Some(ColumnAttr::Target(ident.span())) + } else if ident == sym::param { + Some(ColumnAttr::ParamName(parse_param_attr(attr)?)) } else if ident == sym::default { Some(parse_default_attr(attr, ident)?) } else { @@ -798,6 +833,20 @@ impl ColumnAttr { } } +fn parse_param_attr(attr: &syn::Attribute) -> syn::Result { + let mut name = None; + attr.parse_nested_meta(|meta| { + match_meta!(match meta { + sym::name => { + check_duplicate(&name, &meta)?; + name = Some(meta.value()?.parse()?); + } + }); + Ok(()) + })?; + name.ok_or_else(|| syn::Error::new_spanned(&attr.meta, "expected `#[param(name = parameter_name)]`")) +} + fn parse_default_attr(attr: &syn::Attribute, ident: &Ident) -> syn::Result { if let Ok(expr) = attr.parse_args::() { return Ok(ColumnAttr::Default(expr, ident.span())); @@ -869,6 +918,7 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R let mut unique_columns = vec![]; let mut sequenced_columns = vec![]; let mut primary_key_column = None; + let mut outbox_target_column = None; for (i, field) in fields.iter().enumerate() { let col_num = i as u16; @@ -877,7 +927,9 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R let mut unique = None; let mut auto_inc = None; let mut primary_key = None; + let mut target = None; let mut default_value = None; + let mut param_name = None; for attr in field.original_attrs { let Some(attr) = ColumnAttr::parse(attr, field_ident)? else { continue; @@ -895,11 +947,19 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R check_duplicate(&primary_key, span)?; primary_key = Some(span); } + ColumnAttr::Target(span) => { + check_duplicate(&target, span)?; + target = Some(span); + } ColumnAttr::Index(index_arg) => args.indices.push(index_arg), ColumnAttr::Default(expr, span) => { check_duplicate(&default_value, span)?; default_value = Some(expr); } + ColumnAttr::ParamName(name) => { + check_duplicate(¶m_name, name.span())?; + param_name = Some(name); + } } } @@ -917,6 +977,7 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R ident: field_ident, vis: field.vis, ty: field.ty, + param_name: param_name.as_ref().unwrap_or(field_ident).unraw().to_string(), default_value, }; @@ -930,6 +991,14 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R check_duplicate_msg(&primary_key_column, span, "can only have one primary key per table")?; primary_key_column = Some(column.clone()); } + if let Some(span) = target { + check_duplicate_msg( + &outbox_target_column, + span, + "can only have one target column per outbox table", + )?; + outbox_target_column = Some((column.clone(), span)); + } columns.push(column.clone()); } @@ -1102,7 +1171,7 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R `scheduled(my_reducer, at = custom_scheduled_at)`", ) })?; - let primary_key_column = primary_key_column.ok_or_else(|| { + let primary_key_column = primary_key_column.clone().ok_or_else(|| { syn::Error::new( sched.span, "scheduled tables must have a `#[primary_key] #[auto_inc] scheduled_id: u64` column", @@ -1133,6 +1202,106 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R .unzip(); let schedule = schedule.into_iter(); + if let Some(outbox) = &args.outbox { + if let Some(scheduled) = &args.scheduled { + return Err(syn::Error::new( + scheduled.span, + "outbox tables cannot also be scheduled tables", + )); + } + let primary_key_column = primary_key_column.as_ref().ok_or_else(|| { + syn::Error::new_spanned( + &outbox.receiver_reducer, + "outbox tables must have a `#[primary_key] #[auto_inc]` column of type `u64`", + ) + })?; + if !sequenced_columns + .iter() + .any(|col| col.index == primary_key_column.index) + { + return Err(syn::Error::new_spanned( + primary_key_column.ident, + "outbox tables must have a `#[primary_key] #[auto_inc]` column of type `u64`", + )); + } + } + + let mut outbox_arg_columns = None; + let outbox_typecheck = args + .outbox + .iter() + .map(|outbox| { + let receiver_reducer = &outbox.receiver_reducer; + let Some((target_column, _)) = &outbox_target_column else { + return Err(syn::Error::new_spanned( + receiver_reducer, + "outbox tables must have a `#[target]` column", + )); + }; + let target_ty = target_column.ty; + let mut receiver_module = receiver_reducer.clone(); + receiver_module.segments.pop(); + receiver_module.segments.pop_punct(); + if receiver_module.segments.is_empty() { + return Err(syn::Error::new_spanned( + receiver_reducer, + "outbox receiver reducer must be qualified, e.g. `outbox(receiver::reducer)`", + )); + } + let mut receiver_identity = receiver_module.clone(); + receiver_identity.segments.push(parse_quote!(Identity)); + let mut receiver_outbox_typecheck = receiver_module.clone(); + let reducer_ident = receiver_reducer + .segments + .last() + .expect("receiver reducer path checked above") + .ident + .unraw(); + receiver_outbox_typecheck + .segments + .push(parse_quote!(__spacetimedb_typecheck_outbox)); + let reducer_name = receiver_outbox_typecheck + .segments + .last_mut() + .expect("receiver reducer path checked above"); + reducer_name.ident = format_ident!("__spacetimedb_typecheck_outbox_{}", reducer_ident); + let outbox_columns = columns.iter().map(|col| { + let ident = col.ident; + let ty = col.ty; + let param = Ident::new(&col.param_name, ident.span()); + let index = col.index; + quote!((#index, #ident: #ty as #param),) + }); + outbox_arg_columns = Some(quote! { + #receiver_outbox_typecheck!(#receiver_module, { #(#outbox_columns)* }) + }); + let primary_key_typecheck = primary_key_column.as_ref().map(|col| { + let ty = col.ty; + quote!(spacetimedb::rt::assert_outbox_table_primary_key::<#ty>();) + }); + Ok(quote! { + let _ = |x: #target_ty| { let _: #receiver_identity = x; }; + #primary_key_typecheck + }) + }) + .collect::>>()?; + + let outbox_desc = match (&args.outbox, &outbox_target_column) { + (Some(outbox), Some((target_column, _))) => { + let receiver_reducer = &outbox.receiver_reducer; + let target_col = target_column.index; + quote! { + const OUTBOX: Option> = Some(spacetimedb::table::OutboxDesc { + remote_reducer_name: <#receiver_reducer as spacetimedb::rt::RemoteReducer>::NAME, + arg_columns: #outbox_arg_columns, + target_column: #target_col, + signature_hash: <#receiver_reducer as spacetimedb::rt::RemoteReducer>::SIGNATURE_HASH, + }); + } + } + _ => quote! {}, + }; + let unique_err = if !unique_columns.is_empty() { quote!(spacetimedb::UniqueConstraintViolation) } else { @@ -1145,8 +1314,13 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R }; let field_types = fields.iter().map(|f| f.ty).collect::>(); - + let mutable_table_impl = args.outbox.is_none().then(|| { + quote! { + impl spacetimedb::table::MutableTable for #tablehandle_ident {} + } + }); let tabletype_impl = quote! { + #mutable_table_impl use spacetimedb::Serialize; impl spacetimedb::Table for #tablehandle_ident { type Row = #row_type; @@ -1166,8 +1340,10 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R #(const PRIMARY_KEY: Option = Some(#primary_col_id);)* const SEQUENCES: &'static [u16] = &[#(#sequence_col_ids),*]; #(const SCHEDULE: Option> = Some(#schedule);)* + #outbox_desc #table_id_from_name_func + fn __backend(&self) -> &spacetimedb::table::TableHandleBackend { &self.__backend } @@ -1337,6 +1513,7 @@ pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::R const _: () = { #(let _ = <#field_types as spacetimedb::rt::TableColumn>::_ITEM;)* #schedule_typecheck + #(#outbox_typecheck)* #default_type_check }; diff --git a/crates/bindings/src/rt.rs b/crates/bindings/src/rt.rs index b946487cdc0..80fb0a21523 100644 --- a/crates/bindings/src/rt.rs +++ b/crates/bindings/src/rt.rs @@ -170,6 +170,9 @@ pub trait FnInfo: ExplicitNames { /// Currently only views use this metadata. const VIEW_PRIMARY_KEY_COLUMNS: &'static [&'static str] = &[]; + /// The source name of the outbox table whose results this reducer handles. + const ON_RESULT_OUTBOX: Option<&'static str> = None; + /// The function to invoke. const INVOKE: Self::Invoke; @@ -180,6 +183,22 @@ pub trait FnInfo: ExplicitNames { } } +/// Metadata for a reducer handle generated from a remote module schema. +/// +/// Unlike FnInfo, this does not describe a locally exported callable and +/// therefore has no invocation function. It is used by module-side macros to +/// typecheck calls into another database. +pub trait RemoteReducer { + /// The reducer name in the remote module schema. + const NAME: &'static str; + + /// Hash of the reducer signature as seen by the generated receiver bindings. + const SIGNATURE_HASH: &'static str; + + /// Reducer argument tuple, excluding the reducer context. + type Args; +} + pub trait Procedure<'de, A: Args<'de>, Ret: IntoProcedureResult> { fn invoke(&self, ctx: &mut ProcedureContext, args: A) -> Ret; } @@ -499,6 +518,20 @@ where core::mem::forget(_x); } +/// Resolve an outbox accessor to its registered table source name. +pub const fn on_result_outbox(_table: fn(&crate::Local) -> T) -> &'static str { + T::TABLE_NAME +} + +/// Assert that an `on_result` reducer accepts the outbox row and delivery result. +pub fn on_result_typecheck(_f: F, _table: fn(&crate::Local) -> T) +where + T: crate::Table, + F: Fn(&ReducerContext, T::Row, Result<(), String>) -> Ret, + Ret: IntoReducerResult, +{ +} + /// Tacit marker argument to [`ExportFunctionForScheduledTable`] for reducers. pub struct FnKindReducer { _never: Infallible, @@ -577,6 +610,9 @@ impl TableColumn for T {} /// Assert that the primary_key column of a scheduled table is a u64. pub const fn assert_scheduled_table_primary_key() {} +/// Assert that the primary_key column of an outbox table is a u64. +pub const fn assert_outbox_table_primary_key() {} + mod sealed { pub trait Sealed {} } @@ -588,6 +624,13 @@ pub trait ScheduledTablePrimaryKey: sealed::Sealed {} impl sealed::Sealed for u64 {} impl ScheduledTablePrimaryKey for u64 {} +#[diagnostic::on_unimplemented( + message = "outbox table primary key must be a `u64`", + label = "should be `u64`, not `{Self}`" +)] +pub trait OutboxTablePrimaryKey: sealed::Sealed {} +impl OutboxTablePrimaryKey for u64 {} + /// Used in the last type parameter of `Reducer` to indicate that the /// context argument *should* be passed to the reducer logic. pub struct ContextArg; @@ -806,6 +849,18 @@ pub fn register_table() { table.finish(); + if let Some(outbox) = T::OUTBOX { + module.inner.add_outbox( + T::TABLE_NAME, + outbox.remote_reducer_name, + outbox.target_column, + outbox.arg_columns.iter().copied().map(Into::into), + None::<&str>, + spacetimedb_lib::Hash::from_hex(outbox.signature_hash) + .expect("generated outbox signature hash must be valid hex"), + ); + } + module.inner.add_explicit_names(T::explicit_names()); }) } @@ -833,6 +888,9 @@ pub fn register_reducer<'a, A: Args<'a>, I: FnInfo>(_: impl } else { module.inner.add_reducer(I::NAME, params); } + if let Some(outbox_table) = I::ON_RESULT_OUTBOX { + module.on_result_reducers.push((outbox_table, I::NAME)); + } module.reducers.push(I::INVOKE); module.inner.add_explicit_names(I::explicit_names()); @@ -1114,6 +1172,7 @@ pub struct ModuleBuilder { views: Vec, /// The anonymous views of the module. views_anon: Vec, + on_result_reducers: Vec<(&'static str, &'static str)>, } // Not actually a mutex; because WASM is single-threaded this basically just turns into a refcell. @@ -1173,6 +1232,10 @@ extern "C" fn __describe_module__(description: BytesSink) { describer(&mut module) } + for (outbox_table, reducer) in module.on_result_reducers { + module.inner.set_outbox_on_result(outbox_table, reducer); + } + // Serialize the module to bsatn. let module_def = module.inner.finish(); let module_def = RawModuleDef::V10(module_def); diff --git a/crates/bindings/src/table.rs b/crates/bindings/src/table.rs index aaa678b40db..f1cd009730e 100644 --- a/crates/bindings/src/table.rs +++ b/crates/bindings/src/table.rs @@ -318,9 +318,15 @@ impl TableHandleBackend { } } +/// A table whose existing rows can be updated or deleted. +/// +/// The [`table`](macro@crate::table) macro implements this for ordinary tables. +/// Outbox tables are insert-only and do not implement this trait. +pub trait MutableTable: Table {} + /// Implemented for every `TableHandle` struct generated by the [`table`](macro@crate::table) macro. -/// Contains methods that are present for every table, regardless of what unique constraints -/// and indexes are present. +/// Provides common table operations, regardless of what unique constraints and indexes +/// are present. Deleting rows requires [`MutableTable`]. /// /// To get a `TableHandle` // TODO: should we rename this `TableHandle`? Documenting this, I think that's much clearer. @@ -437,7 +443,10 @@ pub trait Table: TableInternal + ExplicitNames { /// No analogue to auto-increment placeholders exists for deletions. /// /// May panic if deleting the row violates any constraints. - fn delete(&self, row: Self::Row) -> bool { + fn delete(&self, row: Self::Row) -> bool + where + Self: MutableTable, + { // Note that as of writing deletion is infallible, but future work may define new constraints, // e.g. foreign keys, which cause deletion to fail in some cases. // If and when these new constraints are added, @@ -454,7 +463,10 @@ pub trait Table: TableInternal + ExplicitNames { /// /// Returns the number of rows that were deleted, /// i.e., the value of [`self.count()`](Table::count) before this call. - fn clear(&self) -> u64 { + fn clear(&self) -> u64 + where + Self: MutableTable, + { sys::datastore_clear(Self::table_id()).expect("datastore_clear() call failed") } @@ -478,6 +490,7 @@ pub trait TableInternal: Sized { const PRIMARY_KEY: Option = None; const SEQUENCES: &'static [u16]; const SCHEDULE: Option> = None; + const OUTBOX: Option> = None; const IS_EVENT: bool = false; /// Returns the ID of this table. @@ -504,6 +517,14 @@ pub enum IndexAlgo<'a> { Direct { column: u16 }, } +pub struct OutboxDesc<'a> { + pub remote_reducer_name: &'a str, + /// Outbox column positions in remote reducer parameter order. + pub arg_columns: &'a [u16], + pub target_column: u16, + pub signature_hash: &'a str, +} + pub struct ScheduleDesc<'a> { pub reducer_or_procedure_name: &'a str, pub scheduled_at_column: u16, @@ -707,7 +728,10 @@ impl> UniqueColumn) -> bool { + pub fn delete(&self, col_val: impl Borrow) -> bool + where + Tbl: MutableTable, + { self._delete(col_val.borrow()).0 } @@ -747,6 +771,7 @@ impl> UniqueColumn Tbl::Row where + Tbl: MutableTable, Col: PrimaryKey, { if Tbl::IS_EVENT { @@ -771,7 +796,10 @@ impl> UniqueColumn Result> { + pub fn try_insert_or_update(&self, new_row: Tbl::Row) -> Result> + where + Tbl: MutableTable, + { let col_val = Col::get_field(&new_row); // If the row doesn't exist, delete will return false, which we ignore. let _ = self.delete(col_val); @@ -789,7 +817,10 @@ impl> UniqueColumn Tbl::Row { + pub fn insert_or_update(&self, new_row: Tbl::Row) -> Tbl::Row + where + Tbl: MutableTable, + { self.try_insert_or_update(new_row).unwrap_or_else(|e| panic!("{e}")) } } @@ -1036,6 +1067,7 @@ impl PointIndex /// though at present no such constraints exist. pub fn delete(&self, point: P) -> u64 where + Tbl: MutableTable, P: WithPointArg, { if Tbl::IS_EVENT { @@ -1374,6 +1406,7 @@ impl RangedIndex /// though at present no such constraints exist. pub fn delete(&self, b: B) -> u64 where + Tbl: MutableTable, B: IndexScanRangeBounds, { if Tbl::IS_EVENT { diff --git a/crates/bindings/tests/fixtures/idc_receiver/lib.rs b/crates/bindings/tests/fixtures/idc_receiver/lib.rs new file mode 100644 index 00000000000..b04f5fe39ca --- /dev/null +++ b/crates/bindings/tests/fixtures/idc_receiver/lib.rs @@ -0,0 +1,122 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] + +use spacetimedb::spacetimedb_lib as __lib; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct Identity(pub spacetimedb::Identity); + +impl spacetimedb::SpacetimeType for Identity { + fn make_type( + typespace: &mut S, + ) -> spacetimedb::spacetimedb_lib::AlgebraicType { + ::make_type(typespace) + } +} + +impl spacetimedb::Serialize for Identity { + fn serialize(&self, serializer: S) -> Result { + ::serialize(&self.0, serializer) + } +} + +impl<'de> spacetimedb::Deserialize<'de> for Identity { + fn deserialize>(deserializer: D) -> Result { + ::deserialize(deserializer).map(Self) + } +} + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct ReceivePingArgs { + pub body: String, +} + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as body), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(body), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_ping_body { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(body), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as body), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: String = x; }; + $module::__spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_receive_ping_body!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_ping_body; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_ping { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_receive_ping_body!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_ping; + +#[allow(non_camel_case_types)] +pub struct receive_ping; + +impl spacetimedb::rt::RemoteReducer for receive_ping { + const NAME: &'static str = "wire_ping"; + const SIGNATURE_HASH: &'static str = "386957a94632958d5ae8343e258f3a6f9dce9d7dafc46831050894baa7a4e4e1"; + type Args = ReceivePingArgs; +} + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct NoopArgs {} + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_noop { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_noop; + +#[allow(non_camel_case_types)] +pub struct noop; + +impl spacetimedb::rt::RemoteReducer for noop { + const NAME: &'static str = "noop"; + const SIGNATURE_HASH: &'static str = "bc436888fd947d2bfd49ed6bddad31f0245c34fd42c85f9360fa0b477aa957fc"; + type Args = NoopArgs; +} diff --git a/crates/bindings/tests/pass/outbox_arg_columns.rs b/crates/bindings/tests/pass/outbox_arg_columns.rs new file mode 100644 index 00000000000..8a7261144f2 --- /dev/null +++ b/crates/bindings/tests/pass/outbox_arg_columns.rs @@ -0,0 +1,103 @@ +#[path = "../fixtures/idc_receiver/lib.rs"] +mod receiver; + +mod remote_bindings { + pub(crate) use crate::receiver; +} + +#[spacetimedb::table(accessor = outbound_ping, name = "WireOutbox", outbox(crate::remote_bindings::receiver::receive_ping))] +pub struct OutboundPing { + #[primary_key] + #[auto_inc] + id: u64, + audit: String, + #[param(name = body)] + payload: String, + #[target] + destination: receiver::Identity, +} + +mod outboxes { + use super::receiver; + + #[spacetimedb::table(accessor = plain_ping, outbox(self::receiver::receive_ping))] + pub struct PlainPing { + #[primary_key] + #[auto_inc] + id: u64, + #[target] + target: receiver::Identity, + body: String, + } +} + +#[spacetimedb::table(accessor = empty_ping, outbox(receiver::noop))] +pub struct EmptyPing { + #[primary_key] + #[auto_inc] + id: u64, + #[target] + target: receiver::Identity, +} + +#[spacetimedb::reducer(on_result(self::outbound_ping))] +pub fn on_ping_result(_: &spacetimedb::ReducerContext, _: OutboundPing, _: Result<(), String>) {} + +mod callbacks { + #[spacetimedb::reducer(name = "WireCallback", on_result(super::outboxes::plain_ping))] + pub fn on_plain_result(_: &spacetimedb::ReducerContext, _: super::outboxes::PlainPing, _: Result<(), String>) {} +} + +fn main() { + use spacetimedb::rt::FnInfo; + use spacetimedb::table::TableInternal; + + assert_eq!(on_ping_result::ON_RESULT_OUTBOX, Some("outbound_ping")); + assert_eq!(callbacks::on_plain_result::ON_RESULT_OUTBOX, Some("plain_ping")); + assert_eq!(outbound_ping__TableHandle::OUTBOX.unwrap().arg_columns, &[2]); + assert_eq!(outbound_ping__TableHandle::OUTBOX.unwrap().target_column, 3); + assert_eq!(outboxes::plain_ping__TableHandle::OUTBOX.unwrap().arg_columns, &[2]); + assert!(empty_ping__TableHandle::OUTBOX.unwrap().arg_columns.is_empty()); + assert_eq!( + outboxes::plain_ping__TableHandle::OUTBOX.unwrap().remote_reducer_name, + "wire_ping" + ); +} + +// Outbox tables retain inserts and reads, including primary-key lookups. +fn read_and_insert(ctx: &spacetimedb::ReducerContext, row: OutboundPing) { + use spacetimedb::Table; + let table = ctx.db.outbound_ping(); + let row = table.insert(row); + let _ = table.id().find(row.id); + let _ = table.try_insert(row); + let _ = table.count(); + let _ = table.iter(); +} + +#[spacetimedb::table( + accessor = ordinary, + index(accessor = by_value, btree(columns = [value])), + index(accessor = by_value_hash, hash(columns = [value])), +)] +pub struct Ordinary { + #[primary_key] + id: u64, + value: String, +} + +// Ordinary tables retain all update and delete APIs. +fn mutate_ordinary(ctx: &spacetimedb::ReducerContext, row: Ordinary) { + use spacetimedb::Table; + let table = ctx.db.ordinary(); + let row = table.id().update(row); + #[cfg(feature = "unstable")] + let row = table.id().insert_or_update(row); + #[cfg(feature = "unstable")] + let row = table.id().try_insert_or_update(row).unwrap(); + table.delete(row); + table.id().delete(1); + table.by_value().delete("value"); + table.by_value_hash().delete("value"); + table.clear(); +} diff --git a/crates/bindings/tests/ui/outbox_mutation.rs b/crates/bindings/tests/ui/outbox_mutation.rs new file mode 100644 index 00000000000..3a2cc5c3447 --- /dev/null +++ b/crates/bindings/tests/ui/outbox_mutation.rs @@ -0,0 +1,42 @@ +use spacetimedb::Table; + +#[path = "../fixtures/idc_receiver/lib.rs"] +mod receiver; + +#[spacetimedb::table( + accessor = outbound_ping, + outbox(receiver::receive_ping), + index(accessor = by_body, btree(columns = [body])), + index(accessor = by_body_hash, hash(columns = [body])), +)] +pub struct OutboundPing { + #[primary_key] + #[auto_inc] + id: u64, + #[target] + target: receiver::Identity, + body: String, +} + +fn mutate(ctx: &spacetimedb::ReducerContext, row: OutboundPing) { + let table = ctx.db.outbound_ping(); + table.clear(); + table.id().delete(1); + table.by_body().delete("body"); + table.by_body_hash().delete("body"); + table.id().update(row); +} + +fn delete(ctx: &spacetimedb::ReducerContext, row: OutboundPing) { + ctx.db.outbound_ping().delete(row); +} + +fn upsert(ctx: &spacetimedb::ReducerContext, row: OutboundPing) { + ctx.db.outbound_ping().id().insert_or_update(row); +} + +fn try_upsert(ctx: &spacetimedb::ReducerContext, row: OutboundPing) { + let _ = ctx.db.outbound_ping().id().try_insert_or_update(row); +} + +fn main() {} diff --git a/crates/bindings/tests/ui/outbox_mutation.stderr b/crates/bindings/tests/ui/outbox_mutation.stderr new file mode 100644 index 00000000000..366702daf7e --- /dev/null +++ b/crates/bindings/tests/ui/outbox_mutation.stderr @@ -0,0 +1,175 @@ +error[E0277]: the trait bound `outbound_ping__TableHandle: spacetimedb::table::MutableTable` is not satisfied + --> tests/ui/outbox_mutation.rs:23:11 + | +23 | table.clear(); + | ^^^^^ unsatisfied trait bound + | +help: the trait `spacetimedb::table::MutableTable` is not implemented for `outbound_ping__TableHandle` + --> tests/ui/outbox_mutation.rs:6:1 + | + 6 | / #[spacetimedb::table( + 7 | | accessor = outbound_ping, + | |____________________________^ +note: required by a bound in `clear` + --> src/table.rs + | + | fn clear(&self) -> u64 + | ----- required by a bound in this associated function + | where + | Self: MutableTable, + | ^^^^^^^^^^^^ required by this bound in `Table::clear` + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `outbound_ping__TableHandle: spacetimedb::table::MutableTable` is not satisfied + --> tests/ui/outbox_mutation.rs:24:16 + | +24 | table.id().delete(1); + | ^^^^^^ unsatisfied trait bound + | +help: the trait `spacetimedb::table::MutableTable` is not implemented for `outbound_ping__TableHandle` + --> tests/ui/outbox_mutation.rs:6:1 + | + 6 | / #[spacetimedb::table( + 7 | | accessor = outbound_ping, + | |____________________________^ +note: required by a bound in `UniqueColumn::::ColType, Col>::delete` + --> src/table.rs + | + | pub fn delete(&self, col_val: impl Borrow) -> bool + | ------ required by a bound in this associated function + | where + | Tbl: MutableTable, + | ^^^^^^^^^^^^ required by this bound in `UniqueColumn::::ColType, Col>::delete` + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `outbound_ping__TableHandle: spacetimedb::table::MutableTable` is not satisfied + --> tests/ui/outbox_mutation.rs:25:21 + | +25 | table.by_body().delete("body"); + | ^^^^^^ unsatisfied trait bound + | +help: the trait `spacetimedb::table::MutableTable` is not implemented for `outbound_ping__TableHandle` + --> tests/ui/outbox_mutation.rs:6:1 + | + 6 | / #[spacetimedb::table( + 7 | | accessor = outbound_ping, + | |____________________________^ +note: required by a bound in `RangedIndex::::delete` + --> src/table.rs + | + | pub fn delete(&self, b: B) -> u64 + | ------ required by a bound in this associated function + | where + | Tbl: MutableTable, + | ^^^^^^^^^^^^ required by this bound in `RangedIndex::::delete` + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `outbound_ping__TableHandle: spacetimedb::table::MutableTable` is not satisfied + --> tests/ui/outbox_mutation.rs:26:26 + | +26 | table.by_body_hash().delete("body"); + | ^^^^^^ unsatisfied trait bound + | +help: the trait `spacetimedb::table::MutableTable` is not implemented for `outbound_ping__TableHandle` + --> tests/ui/outbox_mutation.rs:6:1 + | + 6 | / #[spacetimedb::table( + 7 | | accessor = outbound_ping, + | |____________________________^ +note: required by a bound in `PointIndex::::delete` + --> src/table.rs + | + | pub fn delete(&self, point: P) -> u64 + | ------ required by a bound in this associated function + | where + | Tbl: MutableTable, + | ^^^^^^^^^^^^ required by this bound in `PointIndex::::delete` + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `outbound_ping__TableHandle: spacetimedb::table::MutableTable` is not satisfied + --> tests/ui/outbox_mutation.rs:27:16 + | +27 | table.id().update(row); + | ^^^^^^ unsatisfied trait bound + | +help: the trait `spacetimedb::table::MutableTable` is not implemented for `outbound_ping__TableHandle` + --> tests/ui/outbox_mutation.rs:6:1 + | + 6 | / #[spacetimedb::table( + 7 | | accessor = outbound_ping, + | |____________________________^ +note: required by a bound in `UniqueColumn::::ColType, Col>::update` + --> src/table.rs + | + | pub fn update(&self, new_row: Tbl::Row) -> Tbl::Row + | ------ required by a bound in this associated function + | where + | Tbl: MutableTable, + | ^^^^^^^^^^^^ required by this bound in `UniqueColumn::::ColType, Col>::update` + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `outbound_ping__TableHandle: spacetimedb::table::MutableTable` is not satisfied + --> tests/ui/outbox_mutation.rs:31:28 + | +31 | ctx.db.outbound_ping().delete(row); + | ^^^^^^ unsatisfied trait bound + | +help: the trait `spacetimedb::table::MutableTable` is not implemented for `outbound_ping__TableHandle` + --> tests/ui/outbox_mutation.rs:6:1 + | + 6 | / #[spacetimedb::table( + 7 | | accessor = outbound_ping, + | |____________________________^ +note: required by a bound in `spacetimedb::Table::delete` + --> src/table.rs + | + | fn delete(&self, row: Self::Row) -> bool + | ------ required by a bound in this associated function + | where + | Self: MutableTable, + | ^^^^^^^^^^^^ required by this bound in `Table::delete` + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `outbound_ping__TableHandle: spacetimedb::table::MutableTable` is not satisfied + --> tests/ui/outbox_mutation.rs:35:33 + | +35 | ctx.db.outbound_ping().id().insert_or_update(row); + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `spacetimedb::table::MutableTable` is not implemented for `outbound_ping__TableHandle` + --> tests/ui/outbox_mutation.rs:6:1 + | + 6 | / #[spacetimedb::table( + 7 | | accessor = outbound_ping, + | |____________________________^ +note: required by a bound in `UniqueColumn::::ColType, Col>::insert_or_update` + --> src/table.rs + | + | pub fn insert_or_update(&self, new_row: Tbl::Row) -> Tbl::Row + | ---------------- required by a bound in this associated function + | where + | Tbl: MutableTable, + | ^^^^^^^^^^^^ required by this bound in `UniqueColumn::::ColType, Col>::insert_or_update` + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `outbound_ping__TableHandle: spacetimedb::table::MutableTable` is not satisfied + --> tests/ui/outbox_mutation.rs:39:41 + | +39 | let _ = ctx.db.outbound_ping().id().try_insert_or_update(row); + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `spacetimedb::table::MutableTable` is not implemented for `outbound_ping__TableHandle` + --> tests/ui/outbox_mutation.rs:6:1 + | + 6 | / #[spacetimedb::table( + 7 | | accessor = outbound_ping, + | |____________________________^ +note: required by a bound in `UniqueColumn::::ColType, Col>::try_insert_or_update` + --> src/table.rs + | + | pub fn try_insert_or_update(&self, new_row: Tbl::Row) -> Result> + | -------------------- required by a bound in this associated function + | where + | Tbl: MutableTable, + | ^^^^^^^^^^^^ required by this bound in `UniqueColumn::::ColType, Col>::try_insert_or_update` + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/bindings/tests/ui/outbox_receiver_typecheck.rs b/crates/bindings/tests/ui/outbox_receiver_typecheck.rs new file mode 100644 index 00000000000..55cb1e0d732 --- /dev/null +++ b/crates/bindings/tests/ui/outbox_receiver_typecheck.rs @@ -0,0 +1,56 @@ +#[path = "../fixtures/idc_receiver/lib.rs"] +mod receiver; +#[spacetimedb::table(accessor = outbound_ping, outbox(receiver::receive_ping))] +pub struct OutboundPing { + #[primary_key] + #[auto_inc] + id: u64, + body: String, + #[target] + target: u8, +} + +#[spacetimedb::table(accessor = wrong_body, outbox(receiver::receive_ping))] +pub struct WrongBody { + #[primary_key] + #[auto_inc] + id: u64, + body: u64, + #[target] + target: receiver::Identity, +} + +#[spacetimedb::table(accessor = missing_body, outbox(receiver::receive_ping))] +pub struct MissingBody { + #[primary_key] + #[auto_inc] + id: u64, + #[target] + target: receiver::Identity, + payload: String, +} + +#[spacetimedb::table(accessor = duplicate_body, outbox(receiver::receive_ping))] +pub struct DuplicateBody { + #[primary_key] + #[auto_inc] + id: u64, + #[target] + target: receiver::Identity, + body: String, + #[param(name = body)] + payload: String, +} + +#[spacetimedb::table(accessor = canonical_param_name, outbox(receiver::receive_ping))] +pub struct CanonicalParamName { + #[primary_key] + #[auto_inc] + id: u64, + #[target] + target: receiver::Identity, + #[param(name = Body)] + payload: String, +} + +fn main() {} diff --git a/crates/bindings/tests/ui/outbox_receiver_typecheck.stderr b/crates/bindings/tests/ui/outbox_receiver_typecheck.stderr new file mode 100644 index 00000000000..7d0e4512f20 --- /dev/null +++ b/crates/bindings/tests/ui/outbox_receiver_typecheck.stderr @@ -0,0 +1,77 @@ +error: outbox has no column matching remote reducer parameter `body` + --> tests/ui/../fixtures/idc_receiver/lib.rs + | + | / compile_error!(concat!( + | | "outbox has no column matching remote reducer parameter `", + | | stringify!(body), + | | "`" + | | )); + | |__________^ + | + ::: tests/ui/outbox_receiver_typecheck.rs:45:1 + | +45 | #[spacetimedb::table(accessor = canonical_param_name, outbox(receiver::receive_ping))] + | -------------------------------------------------------------------------------------- in this attribute macro expansion + | + = note: this error originates in the macro `__outbox_receiver::__spacetimedb_typecheck_outbox_receive_ping_body` which comes from the expansion of the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: outbox has multiple columns matching remote reducer parameter `body` + --> tests/ui/../fixtures/idc_receiver/lib.rs + | + | / compile_error!(concat!( + | | "outbox has multiple columns matching remote reducer parameter `", + | | stringify!(body), + | | "`" + | | )); + | |__________^ + | + ::: tests/ui/outbox_receiver_typecheck.rs:33:1 + | +33 | #[spacetimedb::table(accessor = duplicate_body, outbox(receiver::receive_ping))] + | -------------------------------------------------------------------------------- in this attribute macro expansion + | + = note: this error originates in the macro `__outbox_receiver::__spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate` which comes from the expansion of the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: outbox has no column matching remote reducer parameter `body` + --> tests/ui/../fixtures/idc_receiver/lib.rs + | + | / compile_error!(concat!( + | | "outbox has no column matching remote reducer parameter `", + | | stringify!(body), + | | "`" + | | )); + | |__________^ + | + ::: tests/ui/outbox_receiver_typecheck.rs:23:1 + | +23 | #[spacetimedb::table(accessor = missing_body, outbox(receiver::receive_ping))] + | ------------------------------------------------------------------------------ in this attribute macro expansion + | + = note: this error originates in the macro `__outbox_receiver::__spacetimedb_typecheck_outbox_receive_ping_body` which comes from the expansion of the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0308]: mismatched types + --> tests/ui/outbox_receiver_typecheck.rs:3:1 + | +3 | #[spacetimedb::table(accessor = outbound_ping, outbox(receiver::receive_ping))] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Identity`, found `u8` + | + = note: this error originates in the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0308]: mismatched types + --> tests/ui/../fixtures/idc_receiver/lib.rs + | + | let _ = |x: $ty| { let _: String = x; }; + | ------ ^ expected `String`, found `u64` + | | + | expected due to this + | + ::: tests/ui/outbox_receiver_typecheck.rs:13:1 + | +13 | #[spacetimedb::table(accessor = wrong_body, outbox(receiver::receive_ping))] + | ---------------------------------------------------------------------------- in this attribute macro expansion + | + = note: this error originates in the macro `__outbox_receiver::__spacetimedb_typecheck_outbox_receive_ping_body` which comes from the expansion of the attribute macro `spacetimedb::table` (in Nightly builds, run with -Z macro-backtrace for more info) +help: try using a conversion method + | +66 | let _ = |x: $ty| { let _: String = x.to_string(); }; + | ++++++++++++ diff --git a/crates/bindings/tests/ui/outbox_table_shape.rs b/crates/bindings/tests/ui/outbox_table_shape.rs new file mode 100644 index 00000000000..7a79dd71aec --- /dev/null +++ b/crates/bindings/tests/ui/outbox_table_shape.rs @@ -0,0 +1,53 @@ +#[path = "../fixtures/idc_receiver/lib.rs"] +mod receiver; +#[spacetimedb::table(accessor = missing_pk, outbox(receiver::receive_ping))] +pub struct MissingPk { + #[target] + target: receiver::Identity, + body: String, +} + +#[spacetimedb::table(accessor = non_auto_inc_pk, outbox(receiver::receive_ping))] +pub struct NonAutoIncPk { + #[primary_key] + id: u64, + #[target] + target: receiver::Identity, + body: String, +} + +#[spacetimedb::table(accessor = wrong_pk_type, outbox(receiver::receive_ping))] +pub struct WrongPkType { + #[primary_key] + #[auto_inc] + id: u32, + #[target] + target: receiver::Identity, + body: String, +} + +#[spacetimedb::table(accessor = scheduled_and_outbox, scheduled(scheduled), outbox(receiver::receive_ping))] +pub struct ScheduledAndOutbox { + #[primary_key] + #[auto_inc] + id: u64, + scheduled_at: spacetimedb::ScheduleAt, + #[target] + target: receiver::Identity, + body: String, +} + +#[spacetimedb::table(accessor = callback_outbox, outbox(receiver::receive_ping))] +pub struct CallbackOutbox { + #[primary_key] + #[auto_inc] + id: u64, + #[target] + target: receiver::Identity, + body: String, +} + +#[spacetimedb::reducer(on_result(callback_outbox))] +pub fn bad_on_result(_ctx: &spacetimedb::ReducerContext, _row: CallbackOutbox) {} + +fn main() {} diff --git a/crates/bindings/tests/ui/outbox_table_shape.stderr b/crates/bindings/tests/ui/outbox_table_shape.stderr new file mode 100644 index 00000000000..5e89e8a6be4 --- /dev/null +++ b/crates/bindings/tests/ui/outbox_table_shape.stderr @@ -0,0 +1,55 @@ +error: outbox tables must have a `#[primary_key] #[auto_inc]` column of type `u64` + --> tests/ui/outbox_table_shape.rs:3:52 + | +3 | #[spacetimedb::table(accessor = missing_pk, outbox(receiver::receive_ping))] + | ^^^^^^^^^^^^^^^^^^^^^^ + +error: outbox tables must have a `#[primary_key] #[auto_inc]` column of type `u64` + --> tests/ui/outbox_table_shape.rs:13:5 + | +13 | id: u64, + | ^^ + +error: outbox tables cannot also be scheduled tables + --> tests/ui/outbox_table_shape.rs:29:55 + | +29 | #[spacetimedb::table(accessor = scheduled_and_outbox, scheduled(scheduled), outbox(receiver::receive_ping))] + | ^^^^^^^^^ + +error[E0277]: outbox table primary key must be a `u64` + --> tests/ui/outbox_table_shape.rs:23:9 + | +23 | id: u32, + | ^^^ should be `u64`, not `u32` + | + = help: the trait `spacetimedb::rt::OutboxTablePrimaryKey` is not implemented for `u32` +help: the trait `spacetimedb::rt::OutboxTablePrimaryKey` is implemented for `u64` + --> src/rt.rs + | + | impl OutboxTablePrimaryKey for u64 {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `spacetimedb::rt::assert_outbox_table_primary_key` + --> src/rt.rs + | + | pub const fn assert_outbox_table_primary_key() {} + | ^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_outbox_table_primary_key` + +error[E0593]: function is expected to take 3 arguments, but it takes 2 arguments + --> tests/ui/outbox_table_shape.rs:51:8 + | +50 | #[spacetimedb::reducer(on_result(callback_outbox))] + | --------------------------------------------------- required by a bound introduced by this call +51 | pub fn bad_on_result(_ctx: &spacetimedb::ReducerContext, _row: CallbackOutbox) {} + | -------^^^^^^^^^^^^^---------------------------------------------------------- + | | | + | | expected function that takes 3 arguments + | takes 2 arguments + | +note: required by a bound in `spacetimedb::rt::on_result_typecheck` + --> src/rt.rs + | + | pub fn on_result_typecheck(_f: F, _table: fn(&crate::Local) -> T) + | ------------------- required by a bound in this function +... + | F: Fn(&ReducerContext, T::Row, Result<(), String>) -> Ret, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `on_result_typecheck` diff --git a/crates/cli/src/spacetime_config.rs b/crates/cli/src/spacetime_config.rs index 32d3030082a..a19cfa3bb6d 100644 --- a/crates/cli/src/spacetime_config.rs +++ b/crates/cli/src/spacetime_config.rs @@ -196,6 +196,9 @@ impl SpacetimeConfig { if fields.contains_key(key) { continue; } + if key == "dependencies" { + continue; + } // If the child specifies any module source, skip inheriting the others if child_specifies_source && MODULE_SOURCE_KEYS.contains(&key.as_str()) { continue; @@ -2648,6 +2651,25 @@ mod tests { ); } + #[test] + fn test_dependencies_not_inherited_from_parent() { + let json = r#"{ + "database": "parent-db", + "dependencies": [ + { "name": "auth", "database": "auth-db" } + ], + "children": [ + { "database": "child-db" } + ] + }"#; + + let config: SpacetimeConfig = json5::from_str(json).unwrap(); + let targets = config.collect_all_targets_with_inheritance(); + + assert!(targets[0].fields.contains_key("dependencies")); + assert!(!targets[1].fields.contains_key("dependencies")); + } + #[test] fn test_generate_not_inherited_from_parent() { // Generate is never inherited. Children must define their own. diff --git a/crates/cli/src/subcommands/dev.rs b/crates/cli/src/subcommands/dev.rs index d24344b6490..283d8312de3 100644 --- a/crates/cli/src/subcommands/dev.rs +++ b/crates/cli/src/subcommands/dev.rs @@ -486,7 +486,6 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E } let spacetime_config = loaded_config.as_ref().map(|lc| &lc.config); - let using_spacetime_config = spacetime_config.is_some(); let generate_configs_from_file: Vec> = { let mut entries = spacetime_config.and_then(|c| c.generate.clone()).unwrap_or_default(); // Inherit top-level `module-path` into generate entries that don't specify their own. @@ -695,8 +694,13 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E // Use first database for client process let db_name_for_client = &db_names_for_logging[0]; - // Extract watch directories from publish configs - let watch_dirs = extract_watch_dirs(&publish_configs, &spacetimedb_dir, &project_dir); + // Watch published modules and receiver dependencies used for generation. + let watch_dirs = extract_watch_dirs( + &publish_configs, + &spacetimedb_dir, + &project_dir, + if skip_generate { None } else { spacetime_config }, + )?; println!("\n{}", "Starting development mode...".green().bold()); if db_names_for_logging.len() == 1 { @@ -769,7 +773,7 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E clear_database, &publish_configs, &generate_configs_from_file, - using_spacetime_config, + spacetime_config, server_from_cli, force, dotnet_version.as_deref(), @@ -885,7 +889,7 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E clear_database, &publish_configs, &generate_configs_from_file, - using_spacetime_config, + spacetime_config, server_from_cli, force, dotnet_version.as_deref(), @@ -1033,7 +1037,7 @@ async fn generate_build_and_publish( clear_database: ClearMode, publish_configs: &[CommandConfig<'_>], generate_configs: &[HashMap], - using_spacetime_config: bool, + spacetime_config: Option<&SpacetimeConfig>, server: Option<&str>, yes: bool, dotnet_version: Option<&str>, @@ -1041,6 +1045,20 @@ async fn generate_build_and_publish( skip_publish: bool, skip_generate: bool, ) -> Result<(), anyhow::Error> { + // Receiver bindings must exist before compiling the sender, including on rebuilds. + if !skip_generate && let Some(spacetime_config) = spacetime_config { + let targets = spacetime_config.collect_all_targets_with_inheritance(); + // Generate only the root config entry's dependencies. + // Child database entries are included for dependency lookup. + let entries = generate::dependency_generate_entries(&targets[0], &targets)?; + if !entries.is_empty() { + println!("{}", "Generating receiver bindings from spacetime.json...".cyan()); + // Dependencies carry receiver build settings; do not inherit the sender's SDK version. + let entries = with_dotnet_version_for_dev(entries, dotnet_version, &[]); + generate::exec_from_entries(entries, crate::generate::extract_descriptions, yes, config_dir).await?; + } + } + println!("{}", "Building...".cyan()); let (_path_to_program, _host_type) = tasks::build( spacetimedb_dir, @@ -1078,7 +1096,7 @@ async fn generate_build_and_publish( if skip_generate { println!("{}", "Skipping generate step (--skip-generate).".dimmed()); - } else if using_spacetime_config { + } else if spacetime_config.is_some() { if generate_configs.is_empty() { println!( "{}", @@ -1624,12 +1642,13 @@ fn resolve_database_sources(config: &SpacetimeConfig) -> HashMap], default_spacetimedb_dir: &Path, project_dir: &Path, -) -> std::collections::HashSet { + spacetime_config: Option<&SpacetimeConfig>, +) -> anyhow::Result> { use std::collections::HashSet; let mut watch_dirs = HashSet::new(); @@ -1653,7 +1672,19 @@ fn extract_watch_dirs( watch_dirs.insert(canonical_path); } - watch_dirs + if let Some(config) = spacetime_config { + let targets = config.collect_all_targets_with_inheritance(); + for entry in generate::dependency_generate_entries(&targets[0], &targets)? { + for key in ["module-path", "wasm-file", "js-file"] { + if let Some(path) = entry.get(key).and_then(|v| v.as_str()) { + let path = project_dir.join(path); + watch_dirs.insert(path.canonicalize().unwrap_or(path)); + } + } + } + } + + Ok(watch_dirs) } /// Detect client command and save to config (updating existing config if present) @@ -1809,9 +1840,111 @@ fn start_client_process( #[cfg(test)] mod tests { use super::*; + use spacetimedb_paths::FromPathUnchecked; use std::fs; use tempfile::TempDir; + #[test] + fn test_watch_paths_include_root_dependencies_outside_sender() { + let temp = TempDir::new().unwrap(); + let project_dir = temp.path().join("project"); + let sender_dir = project_dir.join("sender"); + let receiver_dir = temp.path().join("receiver"); + let shared_dir = temp.path().join("shared"); + for dir in [&sender_dir, &receiver_dir, &shared_dir] { + fs::create_dir_all(dir).unwrap(); + } + let spacetime_config: SpacetimeConfig = serde_json::from_value(json!({ + "module-path": "sender", + "dependencies": [ + { "name": "receiver", "database": "receiver-db" }, + { "name": "shared", "module-path": "../shared" } + ], + "children": [{ + "database": "receiver-db", + "module-path": "../receiver", + "dependencies": [{ "name": "child_only", "database": "unknown-db" }] + }] + })) + .unwrap(); + let cmd = publish::cli(); + let schema = publish::build_publish_schema(&cmd).unwrap(); + let args = cmd.get_matches_from(vec!["publish"]); + // Publish only the sender; the receiver is still needed for binding generation. + let publish_configs = vec![CommandConfig::new( + &schema, + HashMap::from([("module-path".to_string(), json!("sender"))]), + &args, + ) + .unwrap()]; + + let paths = extract_watch_dirs(&publish_configs, &sender_dir, &project_dir, Some(&spacetime_config)).unwrap(); + assert_eq!( + paths, + [&sender_dir, &receiver_dir, &shared_dir] + .into_iter() + .map(|path| path.canonicalize().unwrap()) + .collect() + ); + + // --skip-generate excludes dependencies, just as it skips their generation. + let paths = extract_watch_dirs(&publish_configs, &sender_dir, &project_dir, None).unwrap(); + assert_eq!(paths, [sender_dir.canonicalize().unwrap()].into_iter().collect()); + } + + #[tokio::test] + async fn test_root_dependencies_run_before_build_unless_skipped() { + let temp = TempDir::new().unwrap(); + let config = Config::new_with_localhost(spacetimedb_paths::cli::CliTomlPath::from_path_unchecked( + temp.path().join("cli.toml"), + )); + // Language detection only needs the sender manifest; no compiler is invoked. + fs::write(temp.path().join("Cargo.toml"), "").unwrap(); + let mut spacetime_config: SpacetimeConfig = serde_json::from_value(json!({ + "module-path": ".", + "dependencies": [{ "name": "receiver", "database": "receiver-db" }], + "children": [{ + "database": "receiver-db", + "bin-path": "receiver.wasm", + "dependencies": [{ "name": "child_only", "database": "unknown-db" }] + }] + })) + .unwrap(); + + // A missing receiver binary exposes dependency generation; the separate missing + // sender build path exposes reaching the build when generation is skipped. + for (has_root_dependencies, skip_generate, expected_error) in [ + (true, false, "could not extract schema"), + (true, true, "Failed to build project"), + (false, false, "Failed to build project"), + ] { + if !has_root_dependencies { + spacetime_config.additional_fields.remove("dependencies"); + } + let error = generate_build_and_publish( + &config, + temp.path(), + Some(temp.path()), + &temp.path().join("sender"), + &temp.path().join("client_bindings"), + None, + ClearMode::OnConflict, + &[], + &[], + Some(&spacetime_config), + None, + true, + None, + false, + true, + skip_generate, + ) + .await + .unwrap_err(); + assert_eq!(error.to_string(), expected_error); + } + } + #[test] fn test_detect_and_save_preserves_existing_config() { let temp = TempDir::new().unwrap(); diff --git a/crates/cli/src/subcommands/generate.rs b/crates/cli/src/subcommands/generate.rs index 7af0db5a063..2e0e525f6e2 100644 --- a/crates/cli/src/subcommands/generate.rs +++ b/crates/cli/src/subcommands/generate.rs @@ -6,8 +6,8 @@ use clap::Arg; use clap::ArgAction::{Set, SetTrue}; use fs_err as fs; use spacetimedb_codegen::{ - generate, private_table_names, CodegenOptions, CodegenVisibility, Csharp, ImportExtension, Lang, OutputFile, Rust, - TypeScript, UnrealCpp, AUTO_GENERATED_PREFIX, + generate, generate_receiver_bindings, private_table_names, CodegenOptions, CodegenVisibility, Csharp, + ImportExtension, Lang, OutputFile, ReceiverLanguage, Rust, TypeScript, UnrealCpp, AUTO_GENERATED_PREFIX, }; use spacetimedb_lib::de::serde::DeserializeWrapper; use spacetimedb_lib::RawModuleDef; @@ -21,7 +21,7 @@ use crate::spacetime_config::{ }; use crate::tasks::csharp::dotnet_format; use crate::tasks::rust::rustfmt; -use crate::util::y_or_n; +use crate::util::{detect_module_language, y_or_n, ModuleLanguage}; use crate::Config; use crate::{build, common_args}; use clap::builder::PossibleValue; @@ -53,6 +53,9 @@ fn build_generate_config_schema(command: &clap::Command) -> Result( glob::Pattern::new(cli_database).with_context(|| format!("Invalid glob pattern: {cli_database}"))?; let matched: Vec<_> = all_targets - .into_iter() + .iter() .filter(|target| { target .fields @@ -100,8 +103,7 @@ fn get_filtered_generate_configs<'a>( anyhow::bail!( "No database target matches '{}'. Available databases: {}", cli_database, - spacetime_config - .collect_all_targets_with_inheritance() + all_targets .iter() .filter_map(|t| t.fields.get("database").and_then(|v| v.as_str())) .collect::>() @@ -111,39 +113,46 @@ fn get_filtered_generate_configs<'a>( matched } else { - all_targets + all_targets.iter().collect() }; - // Collect generate entries from matched targets, inheriting entity fields - // Deduplicate by (module_path, serialized_generate_entry) + // Collect generate entries from matched targets, inheriting entity fields. + // Also synthesize module-binding entries for receiver dependencies. + // Deduplicate by (module_path, serialized_generate_entry). let mut seen = std::collections::HashSet::new(); let mut generate_configs = Vec::new(); for target in &filtered_targets { - let generate_entries = match &target.generate { - Some(entries) if !entries.is_empty() => entries, - _ => continue, - }; - - // Get module_path from the target's entity fields for dedup let module_path = target.fields.get("module-path").and_then(|v| v.as_str()).unwrap_or(""); - - for entry in generate_entries { - // Deduplicate: same module path + same generate entry config = generate once - let dedup_key = format!("{}:{}", module_path, serde_json::to_string(entry).unwrap_or_default()); + let entries = target + .generate + .as_deref() + .unwrap_or(&[]) + .iter() + .cloned() + .chain(dependency_generate_entries(target, &all_targets)?); + + for entry in entries { + // Deduplicate: same module path + same generate entry config = generate once. + let dedup_key = format!("{}:{}", module_path, serde_json::to_string(&entry).unwrap_or_default()); if !seen.insert(dedup_key) { continue; } - // Merge entity-level fields (module-path, etc.) with the generate entry - let mut merged = entry.clone(); - // Inherit module-path from the target entity if not set in the generate entry - if let Some(mp) = target.fields.get("module-path") { - merged.entry("module-path".to_string()).or_insert_with(|| mp.clone()); + // Merge entity-level fields (module-path, etc.) with the generate entry. + let mut merged = entry; + // Inherit module-path from the target entity if the entry has no source of its own. + if !has_module_source(&merged) + && let Some(mp) = target.fields.get("module-path") + { + merged.insert("module-path".to_string(), mp.clone()); } let command_config = CommandConfig::new(schema, merged, args)?; - command_config.validate()?; + // Receiver language and output defaults will be resolved from the sender. + if command_config.get_one::("bindings")? != Some(BindingKind::Module) { + command_config.validate()?; + } generate_configs.push(command_config); } } @@ -167,6 +176,108 @@ fn get_filtered_generate_configs<'a>( Ok(generate_configs) } +pub(super) fn dependency_generate_entries( + target: &crate::spacetime_config::FlatTarget, + all_targets: &[crate::spacetime_config::FlatTarget], +) -> anyhow::Result>> { + let Some(dependencies) = target.fields.get("dependencies") else { + return Ok(vec![]); + }; + let dependencies = dependencies + .as_array() + .ok_or_else(|| anyhow::anyhow!("`dependencies` must be an array"))?; + let sender_module_path = target + .fields + .get("module-path") + .and_then(|v| v.as_str()) + .ok_or_else(|| anyhow::anyhow!("database dependencies require the sender to define `module-path`"))?; + + dependencies + .iter() + .map(|dependency| dependency_generate_entry(dependency, sender_module_path, all_targets)) + .collect() +} + +fn has_module_source(fields: &HashMap) -> bool { + ["module-path", "bin-path", "js-path", "wasm-file", "js-file"] + .iter() + .any(|key| fields.contains_key(*key)) +} + +fn get_module_source(fields: &HashMap) -> Option<(&str, serde_json::Value)> { + ["module-path", "bin-path", "js-path"] + .into_iter() + .find_map(|key| fields.get(key).cloned().map(|value| (key, value))) +} + +fn dependency_generate_entry( + dependency: &serde_json::Value, + sender_module_path: &str, + all_targets: &[crate::spacetime_config::FlatTarget], +) -> anyhow::Result> { + let dependency = dependency + .as_object() + .ok_or_else(|| anyhow::anyhow!("dependency entries must be objects"))?; + let name = dependency + .get("name") + .and_then(|v| v.as_str()) + .ok_or_else(|| anyhow::anyhow!("dependency entries require `name`"))?; + + let (source_key, source_value, build_options, dotnet_version) = if let Some(path) = dependency.get("module-path") { + ( + "module-path", + path.clone(), + dependency.get("build-options"), + dependency.get("dotnet-version"), + ) + } else if let Some(database) = dependency.get("database").and_then(|v| v.as_str()) { + let receiver = all_targets + .iter() + .find(|target| target.fields.get("database").and_then(|v| v.as_str()) == Some(database)) + .ok_or_else(|| { + anyhow::anyhow!( + "dependency `{name}` refers to database `{database}`, which is not defined in this spacetime.json" + ) + })?; + let (key, value) = get_module_source(&receiver.fields).ok_or_else(|| { + anyhow::anyhow!( + "dependency `{name}` refers to database `{database}`, but that database has no module source" + ) + })?; + ( + key, + value, + receiver.fields.get("build-options"), + receiver.fields.get("dotnet-version"), + ) + } else { + anyhow::bail!("dependency `{name}` requires `database` or `module-path`"); + }; + + // Generate's config keys differ from the publish target's source keys. + let source_key = match source_key { + "bin-path" => "wasm-file", + "js-path" => "js-file", + key => key, + }; + let mut entry = HashMap::from([ + ("sender-module-path".to_string(), serde_json::json!(sender_module_path)), + ("bindings".to_string(), serde_json::json!("module")), + ("dependency-name".to_string(), serde_json::json!(name)), + (source_key.to_string(), source_value), + ]); + for (key, value) in [ + ("out-dir", dependency.get("out-dir")), + ("build-options", build_options), + ("dotnet-version", dotnet_version), + ] { + if let Some(value) = value { + entry.insert(key.to_string(), value.clone()); + } + } + Ok(entry) +} + pub fn cli() -> clap::Command { clap::Command::new("generate") .about("Generate client files for a spacetime module.") @@ -255,6 +366,13 @@ pub fn cli() -> clap::Command { .value_parser(clap::value_parser!(Language)) .help("The language to generate"), ) + .arg( + Arg::new("bindings") + .long("bindings") + .value_parser(clap::value_parser!(BindingKind)) + .default_value("client") + .help("The kind of bindings to generate (module bindings are not implemented yet)"), + ) .arg( Arg::new("build_options") .long("build-options") @@ -310,6 +428,8 @@ pub struct GenerateRunConfig { pub out_dir: PathBuf, pub include_private: bool, pub import_extension: Option, + pub bindings: BindingKind, + pub dependency_name: Option, } fn prepare_generate_run_configs<'a>( @@ -320,6 +440,7 @@ fn prepare_generate_run_configs<'a>( let mut runs = Vec::with_capacity(generate_configs.len()); for command_config in generate_configs { + let bindings = command_config.get_one::("bindings")?.unwrap_or_default(); let project_path = command_config .get_resolved_path("module_path", config_dir)? .unwrap_or_else(|| { @@ -328,8 +449,10 @@ fn prepare_generate_run_configs<'a>( .unwrap_or_else(|| PathBuf::from("spacetimedb")) }); - let wasm_file = command_config.get_one::("wasm_file")?; - let js_file = command_config.get_one::("js_file")?; + let wasm_file = command_config.get_resolved_path("wasm_file", config_dir)?; + let js_file = command_config.get_resolved_path("js_file", config_dir)?; + let sender_module_path = command_config.get_resolved_path("sender_module_path", config_dir)?; + let dependency_name = command_config.get_one::("dependency_name")?; let requested_lang = command_config.get_one::("language")?; let namespace = command_config .get_one::("namespace")? @@ -346,6 +469,13 @@ fn prepare_generate_run_configs<'a>( parse_optional_dotnet_version(dotnet_version.as_deref())? }; + if bindings == BindingKind::Module && requested_lang == Some(Language::UnrealCpp) { + anyhow::bail!("Unreal C++ is a client binding target; use --lang cpp for module bindings"); + } + if bindings == BindingKind::Client && requested_lang == Some(Language::Cpp) { + anyhow::bail!("--lang cpp requires --bindings module; use --lang unrealcpp for Unreal client bindings"); + } + // Validate Unreal-specific args first to preserve focused errors for this mode. if requested_lang == Some(Language::UnrealCpp) { if command_config.get_one::("uproject_dir")?.is_none() { @@ -368,6 +498,17 @@ fn prepare_generate_run_configs<'a>( let lang = match requested_lang { Some(lang) => lang, + None if bindings == BindingKind::Module => { + let sender_dir = sender_module_path + .as_deref() + .unwrap_or(config_dir.unwrap_or_else(|| Path::new("."))); + match detect_module_language(sender_dir)? { + ModuleLanguage::Rust => Language::Rust, + ModuleLanguage::Javascript => Language::TypeScript, + ModuleLanguage::Csharp => Language::Csharp, + ModuleLanguage::Cpp => Language::Cpp, + } + } None => { let client_project_dir = config_dir.unwrap_or_else(|| Path::new(".")); let detected = detect_default_language(client_project_dir)?; @@ -380,16 +521,32 @@ fn prepare_generate_run_configs<'a>( } }; - let out_dir = command_config - .get_resolved_path("out_dir", config_dir)? - .or_else(|| { - command_config - .get_resolved_path("uproject_dir", config_dir) - .ok() - .flatten() - }) - .or_else(|| default_out_dir_for_language(lang).map(|p| config_dir.map(|d| d.join(&p)).unwrap_or(p))) - .ok_or_else(|| anyhow::anyhow!("Either --out-dir or --uproject-dir is required"))?; + let out_dir = if bindings == BindingKind::Module { + let default_dir = match lang { + Language::Rust | Language::TypeScript => "src/remote_bindings", + Language::Csharp | Language::Cpp => "remote_bindings", + Language::UnrealCpp => unreachable!("Unreal module bindings rejected above"), + }; + command_config + .get_resolved_path("out_dir", config_dir)? + .unwrap_or_else(|| { + sender_module_path + .as_deref() + .unwrap_or(config_dir.unwrap_or_else(|| Path::new("."))) + .join(default_dir) + }) + } else { + command_config + .get_resolved_path("out_dir", config_dir)? + .or_else(|| { + command_config + .get_resolved_path("uproject_dir", config_dir) + .ok() + .flatten() + }) + .or_else(|| default_out_dir_for_language(lang).map(|p| config_dir.map(|d| d.join(&p)).unwrap_or(p))) + .ok_or_else(|| anyhow::anyhow!("Either --out-dir or --uproject-dir is required"))? + }; let include_private = command_config.get_one::("include_private")?.unwrap_or(false); let import_extension = command_config @@ -417,6 +574,8 @@ fn prepare_generate_run_configs<'a>( out_dir, include_private, import_extension, + bindings, + dependency_name, }); } @@ -451,6 +610,7 @@ fn language_cli_name(lang: Language) -> &'static str { Language::Csharp => "csharp", Language::TypeScript => "typescript", Language::UnrealCpp => "unrealcpp", + Language::Cpp => "cpp", } } @@ -458,7 +618,7 @@ pub fn default_out_dir_for_language(lang: Language) -> Option { match lang { Language::Rust | Language::TypeScript => Some(PathBuf::from("src/module_bindings")), Language::Csharp => Some(PathBuf::from("module_bindings")), - Language::UnrealCpp => None, + Language::UnrealCpp | Language::Cpp => None, } } @@ -487,6 +647,56 @@ pub fn build_generate_entry( entry } +fn generate_dependency_module_files(files: Vec, dependency_name: &str) -> Vec { + files + .into_iter() + .map(|OutputFile { filename, code }| { + let filename = if filename == "lib.rs" { + format!("{dependency_name}/mod.rs") + } else { + format!("{dependency_name}/{filename}") + }; + OutputFile { filename, code } + }) + .collect() +} + +fn write_remote_bindings_mod(out_dir: &Path, dependency_name: &str) -> anyhow::Result<()> { + fs::create_dir_all(out_dir)?; + let path = out_dir.join("mod.rs"); + let module_decl = format!("pub mod {dependency_name};"); + + let mut module_decls = if path.exists() { + fs::read_to_string(&path)? + .lines() + .filter(|line| line.starts_with("pub mod ")) + .map(ToOwned::to_owned) + .collect::>() + } else { + Vec::new() + }; + if !module_decls.iter().any(|line| line == &module_decl) { + module_decls.push(module_decl); + module_decls.sort(); + } + + let mut lines = vec![ + AUTO_GENERATED_PREFIX.to_string(), + "// WILL NOT BE SAVED. MODIFY DEPENDENCIES IN SPACETIME.JSON INSTEAD.".to_string(), + String::new(), + "#![allow(unused, clippy::all)]".to_string(), + String::new(), + ]; + lines.extend(module_decls); + + let code = format!("{}\n", lines.join("\n")); + if !path.exists() || fs::read_to_string(&path)? != code { + println!("Writing file {}", path.display()); + fs::write(path, code)?; + } + Ok(()) +} + pub async fn run_prepared_generate_configs( run_configs: Vec, extract_descriptions: ExtractDescriptions, @@ -496,8 +706,9 @@ pub async fn run_prepared_generate_configs( ) -> anyhow::Result<()> { for run in run_configs { println!( - "Generating {} module bindings for module {}", + "Generating {} {} bindings for module {}", run.lang.display_name(), + run.bindings.display_name(), run.project_path.display() ); @@ -536,8 +747,6 @@ pub async fn run_prepared_generate_configs( extract_descriptions(&path).context("could not extract schema")? }; - fs::create_dir_all(&run.out_dir)?; - let mut paths = BTreeSet::new(); let private_tables = private_table_names(&module); if !private_tables.is_empty() && !run.include_private { @@ -548,34 +757,60 @@ pub async fn run_prepared_generate_configs( options.visibility = CodegenVisibility::IncludePrivate; } - let csharp_lang; - let unreal_cpp_lang; - let typescript_lang; - let gen_lang = match run.lang { - Language::Csharp => { - csharp_lang = Csharp { + let generated_files = if run.bindings == BindingKind::Module { + let lang = match run.lang { + Language::Rust => ReceiverLanguage::Rust, + Language::TypeScript => ReceiverLanguage::TypeScript, + Language::Csharp => ReceiverLanguage::Csharp { namespace: &run.namespace, - }; - &csharp_lang as &dyn Lang - } - Language::UnrealCpp => { - unreal_cpp_lang = UnrealCpp { - module_name: run.module_name.as_ref().unwrap(), - uproject_dir: &run.out_dir, - module_prefix: run.module_prefix.as_deref().unwrap_or(""), - }; - &unreal_cpp_lang as &dyn Lang - } - Language::Rust => &Rust, - Language::TypeScript => { - typescript_lang = TypeScript { - import_extension: run.import_extension.unwrap_or_default(), - }; - &typescript_lang as &dyn Lang + }, + Language::Cpp => ReceiverLanguage::Cpp, + Language::UnrealCpp => anyhow::bail!("Unreal C++ is a client binding target"), + }; + let files = generate_receiver_bindings(&module, lang)?; + if run.lang == Language::Rust + && let Some(name) = &run.dependency_name + { + write_remote_bindings_mod(&run.out_dir, name)?; + generate_dependency_module_files(files, name) + } else { + files } + } else { + let csharp_lang; + let unreal_cpp_lang; + let typescript_lang; + let gen_lang = match run.lang { + Language::Csharp => { + csharp_lang = Csharp { + namespace: &run.namespace, + }; + &csharp_lang as &dyn Lang + } + Language::UnrealCpp => { + unreal_cpp_lang = UnrealCpp { + module_name: run.module_name.as_ref().unwrap(), + uproject_dir: &run.out_dir, + module_prefix: run.module_prefix.as_deref().unwrap_or(""), + }; + &unreal_cpp_lang as &dyn Lang + } + Language::Rust => &Rust, + Language::TypeScript => { + typescript_lang = TypeScript { + import_extension: run.import_extension.unwrap_or_default(), + }; + &typescript_lang as &dyn Lang + } + Language::Cpp => { + anyhow::bail!("C++ client bindings are not supported; use --lang unrealcpp for Unreal") + } + }; + generate(&module, gen_lang, &options) }; - for OutputFile { filename, code } in generate(&module, gen_lang, &options) { + fs::create_dir_all(&run.out_dir)?; + for OutputFile { filename, code } in generated_files { let fname = Path::new(&filename); if let Some(parent) = fname.parent().filter(|p| !p.as_os_str().is_empty()) { println!("Creating directory {}", run.out_dir.join(parent).display()); @@ -589,8 +824,9 @@ pub async fn run_prepared_generate_configs( paths.insert(path); } - let cleanup_root = match run.lang { - Language::UnrealCpp => run.out_dir.join("Source").join(run.module_name.as_ref().unwrap()), + let cleanup_root = match (run.bindings, &run.dependency_name, run.lang) { + (BindingKind::Module, Some(name), _) => run.out_dir.join(name), + (_, _, Language::UnrealCpp) => run.out_dir.join("Source").join(run.module_name.as_ref().unwrap()), _ => run.out_dir.clone(), }; @@ -718,7 +954,10 @@ pub async fn exec_from_entries( .into_iter() .map(|entry| { let command_config = CommandConfig::new(&schema, entry, &empty_matches)?; - command_config.validate()?; + // Receiver language and output defaults will be resolved from the sender. + if command_config.get_one::("bindings")? != Some(BindingKind::Module) { + command_config.validate()?; + } Ok(command_config) }) .collect::, anyhow::Error>>()?; @@ -727,25 +966,58 @@ pub async fn exec_from_entries( run_prepared_generate_configs(run_configs, extract_descriptions, None, force, false).await } +#[derive(Debug, Default, Clone, Copy, PartialEq, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum BindingKind { + #[default] + Client, + Module, +} + +impl clap::ValueEnum for BindingKind { + fn value_variants<'a>() -> &'a [Self] { + &[Self::Client, Self::Module] + } + + fn to_possible_value(&self) -> Option { + Some(match self { + Self::Client => PossibleValue::new("client"), + Self::Module => PossibleValue::new("module"), + }) + } +} + +impl BindingKind { + pub fn display_name(&self) -> &'static str { + match self { + BindingKind::Client => "client", + BindingKind::Module => "module", + } + } +} + #[derive(Debug, Clone, Copy, PartialEq, serde::Deserialize)] #[serde(rename_all = "lowercase")] pub enum Language { Csharp, TypeScript, Rust, + #[serde(alias = "c++", alias = "cxx")] + Cpp, #[serde(alias = "uecpp", alias = "ue5cpp", alias = "unreal")] UnrealCpp, } impl clap::ValueEnum for Language { fn value_variants<'a>() -> &'a [Self] { - &[Self::Csharp, Self::TypeScript, Self::Rust, Self::UnrealCpp] + &[Self::Csharp, Self::TypeScript, Self::Rust, Self::Cpp, Self::UnrealCpp] } fn to_possible_value(&self) -> Option { Some(match self { Self::Csharp => clap::builder::PossibleValue::new("csharp").aliases(["c#", "cs"]), Self::TypeScript => clap::builder::PossibleValue::new("typescript").aliases(["ts", "TS"]), Self::Rust => clap::builder::PossibleValue::new("rust").aliases(["rs", "RS"]), + Self::Cpp => PossibleValue::new("cpp").aliases(["c++", "cxx"]), Self::UnrealCpp => PossibleValue::new("unrealcpp").aliases(["uecpp", "ue5cpp", "unreal"]), }) } @@ -759,6 +1031,7 @@ impl Language { Language::Csharp => "C#", Language::TypeScript => "TypeScript", Language::UnrealCpp => "Unreal C++", + Language::Cpp => "C++", } } @@ -769,7 +1042,7 @@ impl Language { Language::TypeScript => { // TODO: implement formatting. } - Language::UnrealCpp => { + Language::UnrealCpp | Language::Cpp => { // TODO: implement formatting. } } @@ -957,6 +1230,160 @@ mod tests { ); } + #[test] + fn test_dependencies_generate_module_bindings_entries() { + let cmd = cli(); + let schema = build_generate_config_schema(&cmd).unwrap(); + + let spacetime_config: SpacetimeConfig = json5::from_str( + r#"{ + database: "game", + "module-path": "./game", + "build-options": "--sender-only", + "dotnet-version": "8", + dependencies: [ + { + name: "inventory", + "module-path": "./inventory", + "build-options": "--features inventory", + "dotnet-version": "9", + }, + { + name: "auth", + "module-path": "./auth", + }, + ], + children: [ + { + database: "game-world", + "module-path": "./game_world", + "build-options": "--features world", + "dotnet-version": "10", + }, + { + database: "lobby", + "module-path": "./lobby", + dependencies: [ + { + name: "game_world", + database: "game-world", + }, + { + name: "auth", + "module-path": "./auth", + "out-dir": "./lobby/src/auth_bindings", + }, + ], + }, + ], + }"#, + ) + .unwrap(); + + // Selecting the root generates only its own dependencies. + let matches = cmd.clone().get_matches_from(vec!["generate", "game"]); + let filtered = get_filtered_generate_configs(&spacetime_config, &cmd, &schema, &matches).unwrap(); + assert_eq!(filtered.len(), 2); + assert_eq!( + filtered[0].get_one::("dependency_name").unwrap(), + Some("inventory".to_string()) + ); + assert_eq!( + filtered[0].get_one::("module_path").unwrap(), + Some(PathBuf::from("./inventory")) + ); + assert_eq!(filtered[0].get_one::("out_dir").unwrap(), None); + assert_eq!( + filtered[1].get_one::("dependency_name").unwrap(), + Some("auth".to_string()) + ); + assert_eq!( + filtered[1].get_one::("module_path").unwrap(), + Some(PathBuf::from("./auth")) + ); + assert_eq!(filtered[1].get_one::("out_dir").unwrap(), None); + + assert_eq!( + filtered[0].get_one::("build_options").unwrap().as_deref(), + Some("--features inventory") + ); + assert_eq!( + filtered[0].get_one::("dotnet_version").unwrap().as_deref(), + Some("9") + ); + assert_eq!(filtered[1].get_one::("build_options").unwrap(), None); + assert_eq!(filtered[1].get_one::("dotnet_version").unwrap(), None); + assert_eq!( + filtered[0].get_one::("sender_module_path").unwrap(), + Some(PathBuf::from("./game")) + ); + + // A child without dependencies does not inherit the root's dependencies. + let matches = cmd.clone().get_matches_from(vec!["generate", "game-world"]); + let filtered = get_filtered_generate_configs(&spacetime_config, &cmd, &schema, &matches).unwrap(); + assert!(filtered.is_empty()); + + // Selecting a child generates its dependencies, including its custom output directory. + let matches = cmd.clone().get_matches_from(vec!["generate", "lobby"]); + let filtered = get_filtered_generate_configs(&spacetime_config, &cmd, &schema, &matches).unwrap(); + assert_eq!(filtered.len(), 2); + assert_eq!( + filtered[0].get_one::("dependency_name").unwrap(), + Some("game_world".to_string()) + ); + assert_eq!( + filtered[0].get_one::("module_path").unwrap(), + Some(PathBuf::from("./game_world")) + ); + assert_eq!(filtered[0].get_one::("out_dir").unwrap(), None); + assert_eq!( + filtered[1].get_one::("dependency_name").unwrap(), + Some("auth".to_string()) + ); + assert_eq!( + filtered[1].get_one::("module_path").unwrap(), + Some(PathBuf::from("./auth")) + ); + assert_eq!( + filtered[1].get_one::("out_dir").unwrap(), + Some(PathBuf::from("./lobby/src/auth_bindings")) + ); + + assert_eq!( + filtered[0].get_one::("build_options").unwrap().as_deref(), + Some("--features world") + ); + assert_eq!( + filtered[0].get_one::("dotnet_version").unwrap().as_deref(), + Some("10") + ); + assert_eq!( + filtered[0].get_one::("sender_module_path").unwrap(), + Some(PathBuf::from("./lobby")) + ); + + // Generating all targets retains both outputs for the shared auth dependency. + let matches = cmd.clone().get_matches_from(vec!["generate"]); + let filtered = get_filtered_generate_configs(&spacetime_config, &cmd, &schema, &matches).unwrap(); + assert_eq!(filtered.len(), 4); + let auth_outputs = filtered + .iter() + .filter(|entry| entry.get_one::("dependency_name").unwrap().as_deref() == Some("auth")) + .map(|entry| entry.get_one::("out_dir").unwrap()) + .collect::>(); + assert_eq!( + auth_outputs, + vec![None, Some(PathBuf::from("./lobby/src/auth_bindings"))] + ); + for entry in filtered { + assert_eq!(entry.get_one::("language").unwrap(), None); + assert_eq!( + entry.get_one::("bindings").unwrap(), + Some(BindingKind::Module) + ); + } + } + #[test] fn test_generate_entry_specific_args_error_with_multiple_entries() { let cmd = cli(); @@ -1032,6 +1459,107 @@ mod tests { assert_eq!(runs[0].project_path, PathBuf::from("spacetimedb")); } + #[tokio::test] + async fn test_receiver_dependencies_prepare_options_and_generate_supported_languages() { + let cmd = cli(); + let schema = build_generate_config_schema(&cmd).unwrap(); + let matches = cmd.clone().get_matches_from(vec!["generate", "sender"]); + for (manifest, lang, default_out_dir) in [ + ("Cargo.toml", Language::Rust, "src/remote_bindings"), + ("package.json", Language::TypeScript, "src/remote_bindings"), + ("Sender.csproj", Language::Csharp, "remote_bindings"), + ("CMakeLists.txt", Language::Cpp, "remote_bindings"), + ] { + let temp = tempfile::TempDir::new().unwrap(); + let sender = temp.path().join("sender"); + fs::create_dir_all(&sender).unwrap(); + fs::write(sender.join(manifest), "").unwrap(); + // The client project has a different language from most senders. + fs::write(temp.path().join("package.json"), "{}").unwrap(); + let config: SpacetimeConfig = serde_json::from_value(serde_json::json!({ + "database": "sender", + "module-path": "sender", + "dependencies": [{ "name": "receiver", "database": "receiver-db" }], + "children": [{ + "database": "receiver-db", + "bin-path": "receiver.wasm", + "build-options": "--features receiver", + "dotnet-version": "10" + }] + })) + .unwrap(); + let configs = get_filtered_generate_configs(&config, &cmd, &schema, &matches).unwrap(); + let runs = prepare_generate_run_configs(configs, true, Some(temp.path())).unwrap(); + assert_eq!(runs.len(), 1); + let run = &runs[0]; + assert_eq!(run.bindings, BindingKind::Module); + assert_eq!(run.lang, lang); + assert_eq!(run.dependency_name.as_deref(), Some("receiver")); + assert_eq!( + run.wasm_file.as_deref(), + Some(temp.path().join("receiver.wasm").as_path()) + ); + assert_eq!(run.build_options, "--features receiver"); + assert_eq!(run.dotnet_version, Some(10)); + assert_eq!(run.out_dir, sender.join(default_out_dir)); + let out_dir = run.out_dir.clone(); + + let result = run_prepared_generate_configs( + runs, + |path| { + assert!(path.is_absolute()); + assert_eq!(path.file_name().unwrap(), "receiver.wasm"); + Ok(spacetimedb_lib::db::raw_def::v10::RawModuleDefV10::default() + .try_into() + .unwrap()) + }, + None, + false, + false, + ) + .await; + if lang == Language::Rust { + result.unwrap(); + assert!(out_dir.join("mod.rs").exists()); + assert!(out_dir.join("receiver/mod.rs").exists()); + } else { + assert_eq!( + result.unwrap_err().to_string(), + format!( + "{} receiver binding generation is not implemented yet", + lang.display_name() + ) + ); + assert!(!out_dir.exists(), "unimplemented generation must not write output"); + } + } + } + + #[test] + fn test_direct_module_generation_preserves_explicit_options() { + let cmd = cli(); + let schema = build_generate_config_schema(&cmd).unwrap(); + for language in ["rust", "typescript", "csharp", "cpp"] { + let args = cmd.clone().get_matches_from([ + "generate", + "--bindings", + "module", + "--lang", + language, + "--bin-path", + "receiver.wasm", + "--out-dir", + "bindings", + ]); + let config = CommandConfig::new(&schema, HashMap::new(), &args).unwrap(); + let runs = prepare_generate_run_configs(vec![config], false, None).unwrap(); + assert_eq!(language_cli_name(runs[0].lang), language); + assert_eq!(runs[0].dependency_name, None); + assert_eq!(runs[0].wasm_file, Some(PathBuf::from("receiver.wasm"))); + assert_eq!(runs[0].out_dir, PathBuf::from("bindings")); + } + } + #[test] fn test_defaults_resolve_relative_to_config_dir_when_config_exists() { let cmd = cli(); diff --git a/crates/cli/src/subcommands/publish.rs b/crates/cli/src/subcommands/publish.rs index b7311745d89..a88919def4a 100644 --- a/crates/cli/src/subcommands/publish.rs +++ b/crates/cli/src/subcommands/publish.rs @@ -95,6 +95,7 @@ pub fn build_publish_schema(command: &clap::Command) -> Result { + Rust, + TypeScript, + Csharp { namespace: &'a str }, + Cpp, +} + +/// Generate receiver binding files without reading or writing the filesystem. +pub fn generate_receiver_bindings(module: &ModuleDef, lang: ReceiverLanguage<'_>) -> anyhow::Result> { + match lang { + ReceiverLanguage::Rust => Ok(rust::generate_rust_module_bindings(module)), + ReceiverLanguage::TypeScript => { + // TODO(idc-typescript): Generate TypeScript receiver types, reducer handles, and dependency exports. + anyhow::bail!("TypeScript receiver binding generation is not implemented yet") + } + ReceiverLanguage::Csharp { .. } => { + // TODO(idc-csharp): Generate C# receiver types and reducer handles in the configured namespace. + anyhow::bail!("C# receiver binding generation is not implemented yet") + } + ReceiverLanguage::Cpp => { + // TODO(idc-cpp): Generate C++ receiver types and reducer handles with the required headers. + anyhow::bail!("C++ receiver binding generation is not implemented yet") + } + } +} + pub fn generate(module: &ModuleDef, lang: &dyn Lang, options: &CodegenOptions) -> Vec { itertools::chain!( util::iter_tables(module, options.visibility).map(|tbl| lang.generate_table_file(module, tbl)), diff --git a/crates/codegen/src/rust.rs b/crates/codegen/src/rust.rs index 5a0f829c636..0bbc277640d 100644 --- a/crates/codegen/src/rust.rs +++ b/crates/codegen/src/rust.rs @@ -27,6 +27,15 @@ const INDENT: &str = " "; pub struct Rust; +pub(super) fn generate_rust_module_bindings(module: &ModuleDef) -> Vec { + // TODO: Generate IDC bindings for submodules. Only root types and reducers are emitted for now. + itertools::chain!( + iter_types(module).map(|typ| generate_module_binding_type_file(module, typ)), + [generate_module_bindings_root_file(module)], + ) + .collect() +} + impl Lang for Rust { fn generate_type_files(&self, module: &ModuleDef, typ: &TypeDef) -> Vec { let type_name = collect_case(Case::Pascal, typ.accessor_name.name_segments()); @@ -1039,6 +1048,75 @@ pub fn type_name(module: &ModuleDef, ty: &AlgebraicTypeUse) -> String { s } +fn write_module_binding_type(module: &ModuleDef, out: &mut W, ty: &AlgebraicTypeUse) -> fmt::Result { + match ty { + AlgebraicTypeUse::Identity => write!(out, "Identity")?, + AlgebraicTypeUse::ConnectionId => write!(out, "spacetimedb::ConnectionId")?, + AlgebraicTypeUse::Timestamp => write!(out, "spacetimedb::Timestamp")?, + AlgebraicTypeUse::TimeDuration => write!(out, "spacetimedb::TimeDuration")?, + AlgebraicTypeUse::Uuid => write!(out, "spacetimedb::Uuid")?, + AlgebraicTypeUse::ScheduleAt => write!(out, "spacetimedb::ScheduleAt")?, + AlgebraicTypeUse::Primitive(PrimitiveType::I256) => write!(out, "spacetimedb::sats::i256")?, + AlgebraicTypeUse::Primitive(PrimitiveType::U256) => write!(out, "spacetimedb::sats::u256")?, + AlgebraicTypeUse::Option(inner_ty) => { + write!(out, "Option::<")?; + write_module_binding_type(module, out, inner_ty)?; + write!(out, ">")?; + } + AlgebraicTypeUse::Result { ok_ty, err_ty } => { + write!(out, "Result::<")?; + write_module_binding_type(module, out, ok_ty)?; + write!(out, ", ")?; + write_module_binding_type(module, out, err_ty)?; + write!(out, ">")?; + } + AlgebraicTypeUse::Array(elem_ty) => { + write!(out, "Vec::<")?; + write_module_binding_type(module, out, elem_ty)?; + write!(out, ">")?; + } + _ => write_type(module, out, ty)?, + } + Ok(()) +} + +fn write_module_binding_type_for_outbox_macro( + module: &ModuleDef, + out: &mut W, + ty: &AlgebraicTypeUse, +) -> fmt::Result { + match ty { + AlgebraicTypeUse::Identity => write!(out, "$module::Identity")?, + AlgebraicTypeUse::ConnectionId => write!(out, "spacetimedb::ConnectionId")?, + AlgebraicTypeUse::Timestamp => write!(out, "spacetimedb::Timestamp")?, + AlgebraicTypeUse::TimeDuration => write!(out, "spacetimedb::TimeDuration")?, + AlgebraicTypeUse::Uuid => write!(out, "spacetimedb::Uuid")?, + AlgebraicTypeUse::ScheduleAt => write!(out, "spacetimedb::ScheduleAt")?, + AlgebraicTypeUse::Primitive(PrimitiveType::I256) => write!(out, "spacetimedb::sats::i256")?, + AlgebraicTypeUse::Primitive(PrimitiveType::U256) => write!(out, "spacetimedb::sats::u256")?, + AlgebraicTypeUse::Option(inner_ty) => { + write!(out, "Option::<")?; + write_module_binding_type_for_outbox_macro(module, out, inner_ty)?; + write!(out, ">")?; + } + AlgebraicTypeUse::Result { ok_ty, err_ty } => { + write!(out, "Result::<")?; + write_module_binding_type_for_outbox_macro(module, out, ok_ty)?; + write!(out, ", ")?; + write_module_binding_type_for_outbox_macro(module, out, err_ty)?; + write!(out, ">")?; + } + AlgebraicTypeUse::Array(elem_ty) => { + write!(out, "Vec::<")?; + write_module_binding_type_for_outbox_macro(module, out, elem_ty)?; + write!(out, ">")?; + } + AlgebraicTypeUse::Ref(r) => write!(out, "$module::{}", type_ref_name(module, *r))?, + _ => write_module_binding_type(module, out, ty)?, + } + Ok(()) +} + /// Arguments to a reducer or procedure pretty-printed in various ways that are convenient to compute together. struct FormattedArglist { /// The arguments as `ident: ty, ident: ty, ident: ty,`, @@ -1244,6 +1322,271 @@ fn define_struct_for_product( out.newline(); } +fn define_module_binding_struct_for_product( + module: &ModuleDef, + out: &mut Indenter, + name: &str, + elements: &[(Identifier, AlgebraicTypeUse)], + vis: &str, +) { + print_struct_derives(out); + write!(out, "{vis} struct {name} "); + out.delimited_block( + "{", + |out| { + for (ident, ty) in elements { + write!(out, "pub {}: ", ident.deref().to_case(Case::Snake)); + write_module_binding_type(module, out, ty).unwrap(); + writeln!(out, ","); + } + }, + "}", + ); + out.newline(); +} + +fn generate_module_binding_type_file(module: &ModuleDef, typ: &TypeDef) -> OutputFile { + let type_name = collect_case(Case::Pascal, typ.accessor_name.name_segments()); + let mut output = CodeIndenter::new(String::new(), INDENT); + let out = &mut output; + + print_auto_generated_file_comment(out); + writeln!(out, "{ALLOW_LINTS}"); + writeln!(out, "use super::Identity;"); + let def = &module.typespace_for_generate()[typ.ty]; + let plain_variants; + let (kind, members): (_, &[(Identifier, AlgebraicTypeUse)]) = match def { + AlgebraicTypeDef::Product(product) => ("struct", &product.elements), + AlgebraicTypeDef::Sum(sum) => ("enum", &sum.variants), + AlgebraicTypeDef::PlainEnum(plain_enum) => { + plain_variants = plain_enum + .variants + .iter() + .cloned() + .map(|variant| (variant, AlgebraicTypeUse::Unit)) + .collect::>(); + ("enum", &plain_variants) + } + }; + gen_and_print_imports(module, out, members, &[typ.ty]); + out.newline(); + writeln!(out, "#[derive(spacetimedb::SpacetimeType, Clone, PartialEq, Debug)]"); + if matches!(def, AlgebraicTypeDef::PlainEnum(_)) { + print_plain_enum_extra_derives(out); + } + write!(out, "pub {kind} {type_name} "); + out.delimited_block( + "{", + |out| { + for (ident, ty) in members { + if matches!(def, AlgebraicTypeDef::Product(_)) { + write!(out, "pub {}: ", ident.deref().to_case(Case::Snake)); + write_module_binding_type(module, out, ty).unwrap(); + } else { + write!(out, "{}", ident.deref().to_case(Case::Pascal)); + if !matches!(ty, AlgebraicTypeUse::Unit) { + write!(out, "("); + write_module_binding_type(module, out, ty).unwrap(); + write!(out, ")"); + } + } + writeln!(out, ","); + } + }, + "}\n", + ); + + OutputFile { + filename: type_module_name(&typ.accessor_name) + ".rs", + code: output.into_inner(), + } +} + +fn generate_module_bindings_root_file(module: &ModuleDef) -> OutputFile { + let mut output = CodeIndenter::new(String::new(), INDENT); + let out = &mut output; + + print_auto_generated_file_comment(out); + writeln!(out, "{ALLOW_LINTS}"); + out.newline(); + writeln!(out, "use spacetimedb::spacetimedb_lib as __lib;"); + out.newline(); + print_module_binding_module_decls(module, out); + out.newline(); + print_module_binding_reexports(module, out); + out.newline(); + print_module_binding_identity(out); + out.newline(); + for reducer in iter_reducers(module, CodegenVisibility::OnlyPublic) { + print_module_binding_reducer_handle(module, out, reducer); + out.newline(); + } + + OutputFile { + filename: "lib.rs".to_owned(), + code: output.into_inner(), + } +} + +fn print_module_binding_module_decls(module: &ModuleDef, out: &mut Indenter) { + for ty in iter_types(module) { + let mod_name = type_module_name(&ty.accessor_name); + writeln!(out, "pub mod {mod_name};"); + } +} + +fn print_module_binding_reexports(module: &ModuleDef, out: &mut Indenter) { + for ty in iter_types(module) { + let mod_name = type_module_name(&ty.accessor_name); + let type_name = collect_case(Case::Pascal, ty.accessor_name.name_segments()); + writeln!(out, "pub use {mod_name}::{type_name};"); + } +} + +fn print_module_binding_identity(out: &mut Indenter) { + writeln!( + out, + " +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct Identity(pub spacetimedb::Identity); + +impl spacetimedb::SpacetimeType for Identity {{ + fn make_type( + typespace: &mut S, + ) -> spacetimedb::spacetimedb_lib::AlgebraicType {{ + ::make_type(typespace) + }} +}} + +impl spacetimedb::Serialize for Identity {{ + fn serialize( + &self, + serializer: S, + ) -> Result {{ + ::serialize(&self.0, serializer) + }} +}} + +impl<'de> spacetimedb::Deserialize<'de> for Identity {{ + fn deserialize>( + deserializer: D, + ) -> Result {{ + ::deserialize(deserializer).map(Self) + }} +}} +" + ); +} + +fn print_module_binding_reducer_handle(module: &ModuleDef, out: &mut Indenter, reducer: &ReducerDef) { + let handle_name = reducer_function_name(reducer); + let outbox_typecheck_macro = format!("__spacetimedb_typecheck_outbox_{handle_name}"); + let reducer_name = rust_string_literal(reducer.name.deref()); + let args_type = function_args_type_name(&reducer.accessor_name); + define_module_binding_struct_for_product(module, out, &args_type, &reducer.params_for_generate.elements, "pub"); + out.newline(); + let signature_hash = rust_string_literal(&reducer_signature_hash(module, reducer)); + let mut outbox_typecheck_calls = Vec::new(); + for (arg, ty) in &reducer.params_for_generate.elements { + let arg_name = arg.deref().to_case(Case::Snake); + let mut ty_name = String::new(); + write_module_binding_type_for_outbox_macro(module, &mut ty_name, ty).unwrap(); + writeln!( + out, + " +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_{handle_name}_{arg_name}_reject_duplicate {{ + ($module:ident;) => {{}}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as {arg_name}), $($rest:tt)*) => {{ + compile_error!(concat!( + \"outbox has multiple columns matching remote reducer parameter `\", + stringify!({arg_name}), + \"`\" + )); + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => {{ + $module::__spacetimedb_typecheck_outbox_{handle_name}_{arg_name}_reject_duplicate!($module; $($rest)*); + }}; +}} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_{handle_name}_{arg_name}_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_{handle_name}_{arg_name} {{ + ($module:ident;) => {{{{ + compile_error!(concat!( + \"outbox has no column matching remote reducer parameter `\", + stringify!({arg_name}), + \"`\" + )); + 0u16 + }}}}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as {arg_name}), $($rest:tt)*) => {{{{ + let _ = |x: $ty| {{ let _: {ty_name} = x; }}; + $module::__spacetimedb_typecheck_outbox_{handle_name}_{arg_name}_reject_duplicate!($module; $($rest)*); + $index + }}}}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => {{ + $module::__spacetimedb_typecheck_outbox_{handle_name}_{arg_name}!($module; $($rest)*) + }}; +}} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_{handle_name}_{arg_name}; +" + ); + outbox_typecheck_calls.push(format!( + "__outbox_receiver::__spacetimedb_typecheck_outbox_{handle_name}_{arg_name}!(__outbox_receiver; $($columns)*)" + )); + } + let outbox_typecheck_calls = outbox_typecheck_calls.join(",\n "); + writeln!( + out, + " +#[doc(hidden)] +macro_rules! {outbox_typecheck_macro} {{ + ($module:path, {{ $($columns:tt)* }}) => {{{{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[{outbox_typecheck_calls}] + }}}}; +}} + +#[doc(hidden)] +pub(crate) use {outbox_typecheck_macro}; +" + ); + writeln!( + out, + " +#[allow(non_camel_case_types)] +pub struct {handle_name}; + +impl spacetimedb::rt::RemoteReducer for {handle_name} {{ + const NAME: &'static str = {reducer_name}; + const SIGNATURE_HASH: &'static str = {signature_hash}; + type Args = {args_type}; +}} +" + ); +} + +fn reducer_signature_hash(module: &ModuleDef, reducer: &ReducerDef) -> String { + spacetimedb_schema::def::reducer_signature_hash( + &reducer.params(), + &reducer.ok_return_type, + &reducer.err_return_type, + module.typespace(), + ) + .to_hex() + .to_string() +} + +fn rust_string_literal(value: &str) -> String { + format!("{value:?}") +} + fn type_ref_module_name(module: &ModuleDef, type_ref: AlgebraicTypeRef) -> String { let (name, _) = module.type_def_from_ref(type_ref).unwrap(); type_module_name(name) diff --git a/crates/codegen/tests/codegen.rs b/crates/codegen/tests/codegen.rs index d485a403d97..939482980ce 100644 --- a/crates/codegen/tests/codegen.rs +++ b/crates/codegen/tests/codegen.rs @@ -1,4 +1,6 @@ -use spacetimedb_codegen::{generate, CodegenOptions, Csharp, ImportExtension, Rust, TypeScript}; +use spacetimedb_codegen::{ + generate, generate_receiver_bindings, CodegenOptions, Csharp, ImportExtension, ReceiverLanguage, Rust, TypeScript, +}; use spacetimedb_data_structures::map::HashMap; use spacetimedb_schema::def::ModuleDef; use spacetimedb_testing::modules::{CompilationMode, CompiledModule}; @@ -45,6 +47,127 @@ declare_tests! { test_codegen_rust => Rust, } +#[test] +fn test_codegen_rust_module_bindings() { + let module = compiled_module(); + let outfiles = generate_receiver_bindings(module, ReceiverLanguage::Rust) + .unwrap() + .into_iter() + .map(|f| (f.filename, f.code)) + .collect::>(); + + assert!(outfiles.contains_key("repeating_test_arg_type.rs")); + assert!(outfiles.contains_key("nonrepeating_test_arg_type.rs")); + assert!(!outfiles.keys().any(|filename| filename.ends_with("_reducer.rs"))); + assert!(!outfiles.keys().any(|filename| filename.ends_with("_procedure.rs"))); + + let root = outfiles + .get("lib.rs") + .expect("rust module bindings should emit a root lib.rs"); + + assert!(root.contains("pub struct Identity(pub spacetimedb::Identity);")); + assert!(root.contains("pub struct add;")); + assert!(root.contains("impl spacetimedb::rt::RemoteReducer for add")); + assert!(root.contains("const NAME: &'static str = \"add\";")); + assert!(!root.contains("ARG_NAMES")); + assert!(root.contains("__spacetimedb_typecheck_outbox_add_name")); + let reducer = module + .reducers() + .find(|reducer| reducer.name.as_ref() == "add") + .unwrap(); + let expected_hash = spacetimedb_schema::def::reducer_signature_hash( + &reducer.params(), + &reducer.ok_return_type, + &reducer.err_return_type, + module.typespace(), + ); + assert!(root.contains(&format!( + "const SIGNATURE_HASH: &'static str = \"{}\";", + expected_hash.to_hex() + ))); + assert!(!root.contains("pub struct init;")); + assert!(!root.contains("pub struct client_connected;")); + assert!(!root.contains("sleep_one_second")); + assert!(!root.contains("RemoteProcedures")); + assert!(!root.contains("DbConnection")); + + insta::assert_snapshot!(root); +} + +#[test] +fn test_codegen_rust_module_bindings_include_all_types() { + use spacetimedb_lib::db::raw_def::v10::RawModuleDefV10Builder; + use spacetimedb_lib::{AlgebraicType, ProductType}; + + let mut builder = RawModuleDefV10Builder::new(); + let state_ref = builder + .build_table_with_new_type("EmpireState", ProductType::from([("id", AlgebraicType::U64)]), true) + .finish(); + builder + .build_table_with_new_type("Unrelated", ProductType::from([("id", AlgebraicType::U64)]), true) + .finish(); + let op_ref = builder.add_algebraic_type( + [], + "EmpireStateOp", + AlgebraicType::sum([("Update", AlgebraicType::option(AlgebraicType::Ref(state_ref)))]), + false, + ); + builder.add_reducer( + "receive", + ProductType::from([("ops", AlgebraicType::array(AlgebraicType::Ref(op_ref)))]), + ); + let module: ModuleDef = builder.finish().try_into().unwrap(); + let files = generate_receiver_bindings(&module, ReceiverLanguage::Rust) + .unwrap() + .into_iter() + .map(|file| (file.filename, file.code)) + .collect::>(); + + assert!(files.contains_key("empire_state_op_type.rs")); + assert!(files.contains_key("empire_state_type.rs")); + assert!(files.contains_key("unrelated_type.rs")); + assert!(files["lib.rs"].contains("pub mod empire_state_type;")); + assert!(files["lib.rs"].contains("pub use empire_state_type::EmpireState;")); + assert!(files["lib.rs"].contains("pub mod unrelated_type;")); + assert!(files["lib.rs"].contains("pub use unrelated_type::Unrelated;")); +} + +#[test] +fn test_codegen_rust_outbox_fixture() { + use spacetimedb_lib::db::raw_def::v10::{CaseConversionPolicy, ExplicitNames, RawModuleDefV10Builder}; + use spacetimedb_lib::{AlgebraicType, ProductType}; + + let mut builder = RawModuleDefV10Builder::new(); + builder.set_case_conversion_policy(CaseConversionPolicy::SnakeCase); + builder.add_reducer("receivePing", ProductType::from([("Body", AlgebraicType::String)])); + // Noop uses case conversion; receivePing uses its explicit wire name. + builder.add_reducer("Noop", ProductType::unit()); + let mut names = ExplicitNames::default(); + names.insert_function("receivePing", "wire_ping"); + builder.add_explicit_names(names); + let module: ModuleDef = builder.finish().try_into().unwrap(); + let files = generate_receiver_bindings(&module, ReceiverLanguage::Rust).unwrap(); + let root = &files.iter().find(|file| file.filename == "lib.rs").unwrap().code; + + // The CLI formats generated bindings, and CI checks the fixture with the repo's rustfmt config. + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("lib.rs"); + fs_err::write(&path, root).unwrap(); + let status = std::process::Command::new("rustfmt") + .arg("--config-path") + .arg(concat!(env!("CARGO_MANIFEST_DIR"), "/../../.rustfmt.toml")) + .arg(&path) + .status() + .unwrap(); + assert!(status.success()); + + // The bindings UI tests compile this generated fixture and check its column mappings. + assert_eq!( + fs_err::read_to_string(path).unwrap().trim_end(), + include_str!("../../bindings/tests/fixtures/idc_receiver/lib.rs").trim_end() + ); +} + #[test] fn test_typescript_table_handles_are_camel_case() { let module = compiled_module(); diff --git a/crates/codegen/tests/snapshots/codegen__codegen_rust_module_bindings.snap b/crates/codegen/tests/snapshots/codegen__codegen_rust_module_bindings.snap new file mode 100644 index 00000000000..e2a0c8ceb80 --- /dev/null +++ b/crates/codegen/tests/snapshots/codegen__codegen_rust_module_bindings.snap @@ -0,0 +1,1018 @@ +--- +source: crates/codegen/tests/codegen.rs +expression: root +--- +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] + +use spacetimedb::spacetimedb_lib as __lib; + +pub mod baz_type; +pub mod foobar_type; +pub mod has_special_stuff_type; +pub mod nonrepeating_test_arg_type; +pub mod person_type; +pub mod pk_multi_identity_type; +pub mod player_type; +pub mod point_type; +pub mod private_table_type; +pub mod remove_table_type; +pub mod repeating_test_arg_type; +pub mod test_a_type; +pub mod test_b_type; +pub mod test_d_type; +pub mod test_e_type; +pub mod test_foobar_type; +pub mod namespace_test_c_type; +pub mod namespace_test_f_type; + +pub use baz_type::Baz; +pub use foobar_type::Foobar; +pub use has_special_stuff_type::HasSpecialStuff; +pub use nonrepeating_test_arg_type::NonrepeatingTestArg; +pub use person_type::Person; +pub use pk_multi_identity_type::PkMultiIdentity; +pub use player_type::Player; +pub use point_type::Point; +pub use private_table_type::PrivateTable; +pub use remove_table_type::RemoveTable; +pub use repeating_test_arg_type::RepeatingTestArg; +pub use test_a_type::TestA; +pub use test_b_type::TestB; +pub use test_d_type::TestD; +pub use test_e_type::TestE; +pub use test_foobar_type::TestFoobar; +pub use namespace_test_c_type::NamespaceTestC; +pub use namespace_test_f_type::NamespaceTestF; + + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct Identity(pub spacetimedb::Identity); + +impl spacetimedb::SpacetimeType for Identity { + fn make_type( + typespace: &mut S, + ) -> spacetimedb::spacetimedb_lib::AlgebraicType { + ::make_type(typespace) + } +} + +impl spacetimedb::Serialize for Identity { + fn serialize( + &self, + serializer: S, + ) -> Result { + ::serialize(&self.0, serializer) + } +} + +impl<'de> spacetimedb::Deserialize<'de> for Identity { + fn deserialize>( + deserializer: D, + ) -> Result { + ::deserialize(deserializer).map(Self) + } +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct AddArgs { + pub name: String, + pub age: u8, +} + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_name_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as name), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(name), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_add_name_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_name_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_name { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(name), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as name), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: String = x; }; + $module::__spacetimedb_typecheck_outbox_add_name_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_add_name!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_name; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_age_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as age), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(age), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_add_age_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_age_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_age { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(age), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as age), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: u8 = x; }; + $module::__spacetimedb_typecheck_outbox_add_age_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_add_age!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_age; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_add_name!(__outbox_receiver; $($columns)*), + __outbox_receiver::__spacetimedb_typecheck_outbox_add_age!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add; + + +#[allow(non_camel_case_types)] +pub struct add; + +impl spacetimedb::rt::RemoteReducer for add { + const NAME: &'static str = "add"; + const SIGNATURE_HASH: &'static str = "99a35dc6bdb6cabe48f524346c1979dfe7e6259304f68fb48595ded5c0737c7f"; + type Args = AddArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct AddPlayerArgs { + pub name: String, +} + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_player_name_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as name), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(name), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_add_player_name_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_player_name_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_player_name { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(name), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as name), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: String = x; }; + $module::__spacetimedb_typecheck_outbox_add_player_name_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_add_player_name!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_player_name; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_player { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_add_player_name!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_player; + + +#[allow(non_camel_case_types)] +pub struct add_player; + +impl spacetimedb::rt::RemoteReducer for add_player { + const NAME: &'static str = "add_player"; + const SIGNATURE_HASH: &'static str = "085a98d187205ddd5cb574208fc8f7aa6728c078ae72865f742a48751056824d"; + type Args = AddPlayerArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct AddPrivateArgs { + pub name: String, +} + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_private_name_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as name), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(name), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_add_private_name_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_private_name_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_private_name { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(name), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as name), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: String = x; }; + $module::__spacetimedb_typecheck_outbox_add_private_name_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_add_private_name!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_private_name; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_add_private { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_add_private_name!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_add_private; + + +#[allow(non_camel_case_types)] +pub struct add_private; + +impl spacetimedb::rt::RemoteReducer for add_private { + const NAME: &'static str = "add_private"; + const SIGNATURE_HASH: &'static str = "085a98d187205ddd5cb574208fc8f7aa6728c078ae72865f742a48751056824d"; + type Args = AddPrivateArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct AssertCallerIdentityIsModuleIdentityArgs { + } + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_assert_caller_identity_is_module_identity { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_assert_caller_identity_is_module_identity; + + +#[allow(non_camel_case_types)] +pub struct assert_caller_identity_is_module_identity; + +impl spacetimedb::rt::RemoteReducer for assert_caller_identity_is_module_identity { + const NAME: &'static str = "assert_caller_identity_is_module_identity"; + const SIGNATURE_HASH: &'static str = "bc436888fd947d2bfd49ed6bddad31f0245c34fd42c85f9360fa0b477aa957fc"; + type Args = AssertCallerIdentityIsModuleIdentityArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct DeletePlayerArgs { + pub id: u64, +} + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_delete_player_id_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as id), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(id), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_delete_player_id_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_delete_player_id_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_delete_player_id { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(id), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as id), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: u64 = x; }; + $module::__spacetimedb_typecheck_outbox_delete_player_id_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_delete_player_id!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_delete_player_id; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_delete_player { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_delete_player_id!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_delete_player; + + +#[allow(non_camel_case_types)] +pub struct delete_player; + +impl spacetimedb::rt::RemoteReducer for delete_player { + const NAME: &'static str = "delete_player"; + const SIGNATURE_HASH: &'static str = "f9843c43d6a007427a042049aa531419e42c5895ecfe92bf30bbd6f7389e9cb0"; + type Args = DeletePlayerArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct DeletePlayersByNameArgs { + pub name: String, +} + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_delete_players_by_name_name_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as name), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(name), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_delete_players_by_name_name_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_delete_players_by_name_name_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_delete_players_by_name_name { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(name), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as name), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: String = x; }; + $module::__spacetimedb_typecheck_outbox_delete_players_by_name_name_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_delete_players_by_name_name!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_delete_players_by_name_name; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_delete_players_by_name { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_delete_players_by_name_name!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_delete_players_by_name; + + +#[allow(non_camel_case_types)] +pub struct delete_players_by_name; + +impl spacetimedb::rt::RemoteReducer for delete_players_by_name { + const NAME: &'static str = "delete_players_by_name"; + const SIGNATURE_HASH: &'static str = "085a98d187205ddd5cb574208fc8f7aa6728c078ae72865f742a48751056824d"; + type Args = DeletePlayersByNameArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct ExpectEnvironmentArgs { + pub key: String, + pub expected: Option::, +} + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_expect_environment_key_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as key), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(key), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_expect_environment_key_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_expect_environment_key_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_expect_environment_key { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(key), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as key), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: String = x; }; + $module::__spacetimedb_typecheck_outbox_expect_environment_key_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_expect_environment_key!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_expect_environment_key; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_expect_environment_expected_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as expected), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(expected), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_expect_environment_expected_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_expect_environment_expected_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_expect_environment_expected { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(expected), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as expected), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: Option:: = x; }; + $module::__spacetimedb_typecheck_outbox_expect_environment_expected_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_expect_environment_expected!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_expect_environment_expected; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_expect_environment { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_expect_environment_key!(__outbox_receiver; $($columns)*), + __outbox_receiver::__spacetimedb_typecheck_outbox_expect_environment_expected!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_expect_environment; + + +#[allow(non_camel_case_types)] +pub struct expect_environment; + +impl spacetimedb::rt::RemoteReducer for expect_environment { + const NAME: &'static str = "expect_environment"; + const SIGNATURE_HASH: &'static str = "92fae346d390625a393c5a4470e5ae4c4111b7d7323984087899d521938ab49b"; + type Args = ExpectEnvironmentArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct ListOverAgeArgs { + pub age: u8, +} + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_list_over_age_age_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as age), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(age), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_list_over_age_age_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_list_over_age_age_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_list_over_age_age { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(age), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as age), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: u8 = x; }; + $module::__spacetimedb_typecheck_outbox_list_over_age_age_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_list_over_age_age!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_list_over_age_age; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_list_over_age { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_list_over_age_age!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_list_over_age; + + +#[allow(non_camel_case_types)] +pub struct list_over_age; + +impl spacetimedb::rt::RemoteReducer for list_over_age { + const NAME: &'static str = "list_over_age"; + const SIGNATURE_HASH: &'static str = "480a4dd20223acbee97594f8957ffae7757bd59f68b8e07a22b8900fb21e0cbd"; + type Args = ListOverAgeArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct LogModuleIdentityArgs { + } + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_log_module_identity { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_log_module_identity; + + +#[allow(non_camel_case_types)] +pub struct log_module_identity; + +impl spacetimedb::rt::RemoteReducer for log_module_identity { + const NAME: &'static str = "log_module_identity"; + const SIGNATURE_HASH: &'static str = "bc436888fd947d2bfd49ed6bddad31f0245c34fd42c85f9360fa0b477aa957fc"; + type Args = LogModuleIdentityArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct QueryPrivateArgs { + } + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_query_private { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_query_private; + + +#[allow(non_camel_case_types)] +pub struct query_private; + +impl spacetimedb::rt::RemoteReducer for query_private { + const NAME: &'static str = "query_private"; + const SIGNATURE_HASH: &'static str = "bc436888fd947d2bfd49ed6bddad31f0245c34fd42c85f9360fa0b477aa957fc"; + type Args = QueryPrivateArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct SayHelloArgs { + } + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_say_hello { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_say_hello; + + +#[allow(non_camel_case_types)] +pub struct say_hello; + +impl spacetimedb::rt::RemoteReducer for say_hello { + const NAME: &'static str = "say_hello"; + const SIGNATURE_HASH: &'static str = "bc436888fd947d2bfd49ed6bddad31f0245c34fd42c85f9360fa0b477aa957fc"; + type Args = SayHelloArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct TestArgs { + pub arg: TestA, + pub arg_2: TestB, + pub arg_3: NamespaceTestC, + pub arg_4: NamespaceTestF, +} + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_arg_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as arg), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(arg), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_test_arg_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_arg_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_arg { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(arg), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as arg), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: $module::TestA = x; }; + $module::__spacetimedb_typecheck_outbox_test_arg_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_test_arg!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_arg; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_arg_2_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as arg_2), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(arg_2), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_test_arg_2_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_arg_2_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_arg_2 { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(arg_2), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as arg_2), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: $module::TestB = x; }; + $module::__spacetimedb_typecheck_outbox_test_arg_2_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_test_arg_2!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_arg_2; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_arg_3_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as arg_3), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(arg_3), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_test_arg_3_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_arg_3_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_arg_3 { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(arg_3), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as arg_3), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: $module::NamespaceTestC = x; }; + $module::__spacetimedb_typecheck_outbox_test_arg_3_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_test_arg_3!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_arg_3; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_arg_4_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as arg_4), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(arg_4), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_test_arg_4_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_arg_4_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_arg_4 { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(arg_4), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as arg_4), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: $module::NamespaceTestF = x; }; + $module::__spacetimedb_typecheck_outbox_test_arg_4_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_test_arg_4!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_arg_4; + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_test_arg!(__outbox_receiver; $($columns)*), + __outbox_receiver::__spacetimedb_typecheck_outbox_test_arg_2!(__outbox_receiver; $($columns)*), + __outbox_receiver::__spacetimedb_typecheck_outbox_test_arg_3!(__outbox_receiver; $($columns)*), + __outbox_receiver::__spacetimedb_typecheck_outbox_test_arg_4!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test; + + +#[allow(non_camel_case_types)] +pub struct test; + +impl spacetimedb::rt::RemoteReducer for test { + const NAME: &'static str = "test"; + const SIGNATURE_HASH: &'static str = "7c5f9ed84b96b24179d63afbe2e4e459cae4cb0b7076f237249d46ea295f698e"; + type Args = TestArgs; +} + + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct TestBtreeIndexArgsArgs { + } + + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_test_btree_index_args { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_test_btree_index_args; + + +#[allow(non_camel_case_types)] +pub struct test_btree_index_args; + +impl spacetimedb::rt::RemoteReducer for test_btree_index_args { + const NAME: &'static str = "test_btree_index_args"; + const SIGNATURE_HASH: &'static str = "bc436888fd947d2bfd49ed6bddad31f0245c34fd42c85f9360fa0b477aa957fc"; + type Args = TestBtreeIndexArgsArgs; +} diff --git a/crates/core/src/host/idc_actor.rs b/crates/core/src/host/idc_actor.rs index 582286e8064..739bd53a926 100644 --- a/crates/core/src/host/idc_actor.rs +++ b/crates/core/src/host/idc_actor.rs @@ -512,7 +512,7 @@ fn load_pending_message( target_identity: stream.target_identity.0, ack_prefix: stream.ack_prefix, target_reducer: outbox.remote_reducer.clone(), - signature_hash: Hash::from_hex(&outbox.signature_hash)?, + signature_hash: outbox.signature_hash, reducer_args, outbox_row, on_result_reducer: outbox.on_result_reducer.clone(), @@ -968,9 +968,7 @@ mod tests { &AlgebraicType::unit(), &AlgebraicType::String, &spacetimedb_sats::Typespace::default(), - ) - .to_hex() - .to_string(), + ), }), ) } @@ -1366,7 +1364,10 @@ mod tests { ); assert_eq!(query["seq"], "1"); assert_eq!(query["ack_prefix"], "0"); - assert_eq!(query["signature_hash"], outbox_schema().outbox.unwrap().signature_hash); + assert_eq!( + query["signature_hash"], + outbox_schema().outbox.unwrap().signature_hash.to_hex().as_str() + ); assert_eq!(body.as_ref(), to_vec(&42u32).unwrap()); (StatusCode::from_u16(status).unwrap(), "receiver detail") } diff --git a/crates/core/src/sql/execute.rs b/crates/core/src/sql/execute.rs index 0f34275f174..340d25e70fe 100644 --- a/crates/core/src/sql/execute.rs +++ b/crates/core/src/sql/execute.rs @@ -454,7 +454,7 @@ pub(crate) mod tests { target_column: ColId(1), arg_columns: vec![], on_result_reducer: None, - signature_hash: "test-signature".into(), + signature_hash: spacetimedb_lib::Hash::ZERO, }); stdb.create_table(tx, schema) })?; diff --git a/crates/datastore/src/locking_tx_datastore/datastore.rs b/crates/datastore/src/locking_tx_datastore/datastore.rs index a88706a506b..0745d56bfab 100644 --- a/crates/datastore/src/locking_tx_datastore/datastore.rs +++ b/crates/datastore/src/locking_tx_datastore/datastore.rs @@ -3133,7 +3133,7 @@ pub(crate) mod tests { target_column: ColId(1), arg_columns: vec![ColId(2)], on_result_reducer: None, - signature_hash: "test-signature".into(), + signature_hash: spacetimedb_lib::Hash::ZERO, }); let datastore = get_datastore()?; @@ -3396,7 +3396,7 @@ pub(crate) mod tests { target_column: ColId(1), arg_columns: vec![], on_result_reducer: None, - signature_hash: "test-signature".into(), + signature_hash: spacetimedb_lib::Hash::ZERO, }; let row = to_vec(&product![1u64, IdentityViaU256(Identity::ONE)]).unwrap(); diff --git a/crates/datastore/src/locking_tx_datastore/state_view.rs b/crates/datastore/src/locking_tx_datastore/state_view.rs index 405d81dedee..b75f2c61e97 100644 --- a/crates/datastore/src/locking_tx_datastore/state_view.rs +++ b/crates/datastore/src/locking_tx_datastore/state_view.rs @@ -18,7 +18,7 @@ use core::ops::RangeBounds; use spacetimedb_lib::ConnectionId; use spacetimedb_primitives::{col_list, ColList, TableId}; use spacetimedb_sats::{product, AlgebraicValue}; -use spacetimedb_schema::schema::{ColumnSchema, IndexSchema, TableSchema, ViewDefInfo}; +use spacetimedb_schema::schema::{ColumnSchema, IndexSchema, OutboxSchema, TableSchema, ViewDefInfo}; use spacetimedb_table::table::IndexScanPointIter; use spacetimedb_table::{ blob_store::HashMapBlobStore, @@ -305,7 +305,12 @@ pub trait StateView { // `st_outbox` is missing until `migrate_system_tables` runs. // Treat that as "no outbox metadata" while reconstructing raw schemas. let outbox = match self.iter_by_col_eq(ST_OUTBOX_ID, StOutboxFields::TableId, value_eq) { - Ok(mut iter) => iter.next().map(StOutboxRow::try_from).transpose()?.map(Into::into), + Ok(mut iter) => iter + .next() + .map(StOutboxRow::try_from) + .transpose()? + .map(OutboxSchema::try_from) + .transpose()?, Err(DatastoreError::Table(TableError::IdNotFound(..))) => None, Err(e) => return Err(e), }; diff --git a/crates/datastore/src/locking_tx_datastore/tx_state.rs b/crates/datastore/src/locking_tx_datastore/tx_state.rs index 5b2f3c385e8..05dedbd21a4 100644 --- a/crates/datastore/src/locking_tx_datastore/tx_state.rs +++ b/crates/datastore/src/locking_tx_datastore/tx_state.rs @@ -188,7 +188,6 @@ impl MemoryUsage for PendingSchemaChange { .as_ref() .map(|name| name.as_ref().heap_usage()) .unwrap_or(0) - + outbox.signature_hash.heap_usage() }) .unwrap_or(0) } diff --git a/crates/datastore/src/system_tables/idc.rs b/crates/datastore/src/system_tables/idc.rs index 136d25f1630..a9d0adea770 100644 --- a/crates/datastore/src/system_tables/idc.rs +++ b/crates/datastore/src/system_tables/idc.rs @@ -260,20 +260,22 @@ impl From<(TableId, OutboxSchema)> for StOutboxRow { target_column: outbox.target_column, arg_columns: outbox.arg_columns, on_result_reducer: outbox.on_result_reducer.map(Into::into), - signature_hash: outbox.signature_hash, + signature_hash: outbox.signature_hash.to_hex().to_string(), } } } -impl From for OutboxSchema { - fn from(row: StOutboxRow) -> Self { - Self { +impl TryFrom for OutboxSchema { + type Error = DatastoreError; + + fn try_from(row: StOutboxRow) -> Result { + Ok(Self { remote_reducer: ReducerName::new(row.remote_reducer), target_column: row.target_column, arg_columns: row.arg_columns, on_result_reducer: row.on_result_reducer.map(ReducerName::new), - signature_hash: row.signature_hash, - } + signature_hash: Hash::from_hex(row.signature_hash).map_err(anyhow::Error::from)?, + }) } } @@ -379,3 +381,31 @@ pub(crate) fn st_inbound_msg_schema() -> TableSchema { pub(crate) fn st_outbox_schema() -> TableSchema { st_schema(ST_OUTBOX_NAME, ST_OUTBOX_ID) } + +#[cfg(test)] +mod tests { + use super::*; + use spacetimedb_lib::bsatn; + + #[test] + fn outbox_signature_hash_uses_legacy_string_encoding() { + // Encode the existing persisted row format independently of StOutboxRow. + let legacy_bytes = bsatn::to_vec(&( + TableId(42), + "receive_ping", + ColId(1), + vec![ColId(2)], + None::<&str>, + "ab".repeat(32), + )) + .unwrap(); + let mut row: StOutboxRow = bsatn::from_slice(&legacy_bytes).unwrap(); + let outbox = OutboxSchema::try_from(row.clone()).unwrap(); + assert_eq!(outbox.signature_hash, Hash::from_byte_array([0xab; 32])); + let stored = StOutboxRow::from((row.table_id, outbox)); + assert_eq!(bsatn::to_vec(&stored).unwrap(), legacy_bytes); + + row.signature_hash = "invalid".into(); + assert!(OutboxSchema::try_from(row).is_err()); + } +} diff --git a/crates/engine/src/update.rs b/crates/engine/src/update.rs index 53e84dec7ff..8b26299d724 100644 --- a/crates/engine/src/update.rs +++ b/crates/engine/src/update.rs @@ -1052,7 +1052,7 @@ mod test { ColId(1), [ColId(2)], Option::<&str>::None, - "test-signature", + spacetimedb_lib::hash_bytes(b"test-signature"), ); } @@ -1103,13 +1103,16 @@ mod test { }; table.finish(); + if let Some(on_result) = on_result { + builder.add_reducer(on_result, ProductType::unit()); + } builder.add_outbox( "outbound_pings", "receive_ping", ColId(1), [ColId(2)], on_result, - "test-signature", + spacetimedb_lib::hash_bytes(b"test-signature"), ); builder diff --git a/crates/lib/src/db/raw_def/v10.rs b/crates/lib/src/db/raw_def/v10.rs index fd70fc77706..1094e1cf8e9 100644 --- a/crates/lib/src/db/raw_def/v10.rs +++ b/crates/lib/src/db/raw_def/v10.rs @@ -6,6 +6,7 @@ //! It allows easier future extensibility to add new kinds of definitions. use crate::db::raw_def::v9::{Lifecycle, RawIndexAlgorithm, TableAccess, TableType}; +use crate::Hash; use core::fmt; use spacetimedb_primitives::{ColId, ColList}; use spacetimedb_sats::raw_identifier::RawIdentifier; @@ -338,6 +339,19 @@ pub struct RawTableDefV10 { pub is_event: bool, } +/// Outbox metadata for a table. +#[derive(Debug, Clone, SpacetimeType)] +#[sats(crate = crate)] +#[cfg_attr(feature = "test", derive(PartialEq, Eq, PartialOrd, Ord))] +pub struct RawOutboxDefV10 { + pub table_source_name: RawIdentifier, + pub remote_reducer: RawIdentifier, + pub target_column: ColId, + pub arg_columns: Vec, + pub on_result_reducer: Option, + pub signature_hash: Hash, +} + /// Marks a particular table column as having a particular default value. #[derive(Debug, Clone, SpacetimeType)] #[sats(crate = crate)] @@ -351,25 +365,6 @@ pub struct RawColumnDefaultValueV10 { pub value: Box<[u8]>, } -/// Marks a table as an IDC outbox table. -#[derive(Debug, Clone, SpacetimeType)] -#[sats(crate = crate)] -#[cfg_attr(feature = "test", derive(PartialEq, Eq, PartialOrd, Ord))] -pub struct RawOutboxDefV10 { - /// The `source_name` of the outbox table. - pub table_name: RawIdentifier, - /// The reducer to call on the target database. - pub remote_reducer: RawIdentifier, - /// Column containing the receiver database identity. - pub target_column: ColId, - /// Columns to encode as reducer arguments, in receiver parameter order. - pub arg_columns: Vec, - /// Optional local reducer called with the delivery result. - pub on_result_reducer: Option, - /// Hash of the receiver reducer signature as seen by sender bindings. - pub signature_hash: String, -} - /// A reducer definition. #[derive(Debug, Clone, SpacetimeType)] #[sats(crate = crate)] @@ -699,6 +694,14 @@ impl RawModuleDefV10 { }) } + /// Get the outboxes section, if present. + pub fn outboxes(&self) -> Option<&Vec> { + self.sections.iter().find_map(|s| match s { + RawModuleDefV10Section::Outboxes(outboxes) => Some(outboxes), + _ => None, + }) + } + /// Get the lifecycle reducers section, if present. pub fn lifecycle_reducers(&self) -> Option<&Vec> { self.sections.iter().find_map(|s| match s { @@ -717,14 +720,6 @@ impl RawModuleDefV10 { .expect("Tables section must exist for tests") } - /// Get the outboxes section, if present. - pub fn outboxes(&self) -> Option<&Vec> { - self.sections.iter().find_map(|s| match s { - RawModuleDefV10Section::Outboxes(outboxes) => Some(outboxes), - _ => None, - }) - } - // Get the row-level security section, if present. pub fn row_level_security(&self) -> Option<&Vec> { self.sections.iter().find_map(|s| match s { @@ -1038,6 +1033,47 @@ impl RawModuleDefV10Builder { } } + pub fn add_outbox( + &mut self, + table_source_name: impl Into, + remote_reducer: impl Into, + target_column: impl Into, + arg_columns: impl IntoIterator, + on_result_reducer: Option>, + signature_hash: Hash, + ) { + self.outboxes_mut().push(RawOutboxDefV10 { + table_source_name: table_source_name.into(), + remote_reducer: remote_reducer.into(), + target_column: target_column.into(), + arg_columns: arg_columns.into_iter().collect(), + on_result_reducer: on_result_reducer.map(Into::into), + signature_hash, + }); + } + + pub fn set_outbox_on_result( + &mut self, + table_source_name: impl Into, + on_result_reducer: impl Into, + ) { + let table_source_name = table_source_name.into(); + let on_result_reducer = Some(on_result_reducer.into()); + if let Some(outbox) = self + .outboxes_mut() + .iter_mut() + .find(|outbox| outbox.table_source_name == table_source_name) + { + assert!( + outbox.on_result_reducer.is_none(), + "outbox table `{table_source_name}` has multiple on_result reducers" + ); + outbox.on_result_reducer = on_result_reducer; + } else { + panic!("on_result reducer references unknown outbox table `{table_source_name}`"); + } + } + /// Get mutable access to the environment section, creating it if missing. fn environment_mut(&mut self) -> &mut Vec { let idx = self @@ -1340,26 +1376,6 @@ impl RawModuleDefV10Builder { self.explicit_names_mut().merge(names); } - /// Register an IDC outbox table. - pub fn add_outbox( - &mut self, - table_name: impl Into, - remote_reducer: impl Into, - target_column: impl Into, - arg_columns: impl IntoIterator, - on_result_reducer: Option>, - signature_hash: impl Into, - ) { - self.outboxes_mut().push(RawOutboxDefV10 { - table_name: table_name.into(), - remote_reducer: remote_reducer.into(), - target_column: target_column.into(), - arg_columns: arg_columns.into_iter().collect(), - on_result_reducer: on_result_reducer.map(Into::into), - signature_hash: signature_hash.into(), - }); - } - pub fn add_submodule(&mut self, namespace: impl Into, module: RawModuleDefV10) { let submodule = RawSubmoduleV10 { namespace: namespace.into(), diff --git a/crates/schema/src/auto_migrate.rs b/crates/schema/src/auto_migrate.rs index 12acc9c8d73..1f449147df3 100644 --- a/crates/schema/src/auto_migrate.rs +++ b/crates/schema/src/auto_migrate.rs @@ -1424,13 +1424,16 @@ mod tests { .finish(); if let Some((remote_reducer, arg_columns, on_result_reducer, signature_hash)) = outbox { + if let Some(on_result_reducer) = on_result_reducer { + builder.add_reducer(on_result_reducer.to_owned(), ProductType::unit()); + } builder.add_outbox( "outbound_pings", remote_reducer.to_owned(), target_column, arg_columns, on_result_reducer.map(str::to_owned), - signature_hash.to_owned(), + hash_bytes(signature_hash.as_bytes()), ); } }) diff --git a/crates/schema/src/def.rs b/crates/schema/src/def.rs index 8b59bb469de..b5c5cf5f6ae 100644 --- a/crates/schema/src/def.rs +++ b/crates/schema/src/def.rs @@ -46,7 +46,7 @@ use spacetimedb_lib::db::raw_def::v9::{ }; use spacetimedb_lib::db::view::{extract_view_return_product_type_ref, ViewKind}; use spacetimedb_lib::environment::EnvironmentSchema; -use spacetimedb_lib::{hash_bytes, ProductType, RawModuleDef}; +use spacetimedb_lib::{hash_bytes, Hash as SpacetimeHash, ProductType, RawModuleDef}; use spacetimedb_primitives::{ ColId, ColList, ColOrCols, ColSet, HttpHandlerId, ProcedureId, ReducerId, TableId, ViewFnPtr, }; @@ -324,6 +324,13 @@ impl ModuleDef { if let Some(schedule) = &mut table.schedule { schedule.namespace = path.clone(); } + if let Some(callback) = table + .outbox + .as_mut() + .and_then(|outbox| outbox.on_result_reducer.as_mut()) + { + *callback = ReducerName::new(path.join(callback.local().clone())); + } } for view in self.views.values_mut() { view.namespace = path.clone(); @@ -1108,7 +1115,11 @@ impl From for RawModuleDefV10 { environment, } = val; - let mut sections = Vec::new(); + // Names are already canonicalized. Disable further case conversion so revalidation + // preserves them. + let mut sections = vec![RawModuleDefV10Section::CaseConversionPolicy( + raw_def::v10::CaseConversionPolicy::None, + )]; if let Some(environment) = environment { sections.push(RawModuleDefV10Section::Environment( environment.into_declarations().into_iter().map(|x| x.into()).collect(), @@ -1158,11 +1169,13 @@ impl From for RawModuleDefV10 { } if let Some(outbox) = td.outbox.clone() { outboxes.push(RawOutboxDefV10 { - table_name: td.accessor_name.clone().into(), + table_source_name: td.accessor_name.clone().into(), remote_reducer: outbox.remote_reducer.into(), target_column: outbox.target_column, arg_columns: outbox.arg_columns, - on_result_reducer: outbox.on_result_reducer.map(Into::into), + on_result_reducer: outbox + .on_result_reducer + .map(|name| reducers[name.local()].accessor_name.clone().into()), signature_hash: outbox.signature_hash, }); } @@ -1262,7 +1275,6 @@ impl From for RawModuleDefV10 { if !schedules.is_empty() { sections.push(RawModuleDefV10Section::Schedules(schedules)); } - if !outboxes.is_empty() { sections.push(RawModuleDefV10Section::Outboxes(outboxes)); } @@ -1406,7 +1418,7 @@ pub struct OutboxDef { /// Local reducer to invoke with the remote result before acknowledging this stream. pub on_result_reducer: Option, /// Hash of the receiver reducer signature as seen by sender bindings. - pub signature_hash: String, + pub signature_hash: SpacetimeHash, } impl TableDef { @@ -1431,6 +1443,7 @@ impl From for RawTableDefV9 { constraints, sequences, schedule, + outbox: _, table_type, table_access, .. @@ -1515,11 +1528,12 @@ impl From for TableDef { constraints: <_>::default(), sequences: <_>::default(), schedule: None, + // V9 view definitions have no IDC outbox metadata. + outbox: None, table_type: TableType::User, table_access: if is_public { Public } else { Private }, is_event: false, accessor_name, - outbox: None, } } } @@ -2342,6 +2356,7 @@ impl From for RawViewDefV10 { is_anonymous, is_public, params, + params_for_generate, return_type, fn_ptr, .. @@ -2351,7 +2366,7 @@ impl From for RawViewDefV10 { index: fn_ptr.into(), is_public, is_anonymous, - params, + params: canonical_params(params, ¶ms_for_generate), return_type, } } @@ -2443,14 +2458,18 @@ pub struct ReducerDef { impl ReducerDef { /// Parameter types with schema names. pub fn params(&self) -> ProductType { - let mut params = self.params.clone(); - for (param, (name, _)) in params.elements.iter_mut().zip(self.params_for_generate.elements.iter()) { - param.name = Some(name.clone().into()); - } - params + canonical_params(self.params.clone(), &self.params_for_generate) } } +fn canonical_params(mut params: ProductType, params_for_generate: &ProductTypeDef) -> ProductType { + assert_eq!(params.elements.len(), params_for_generate.elements.len()); + for (param, (name, _)) in params.elements.iter_mut().zip(params_for_generate.elements.iter()) { + param.name = Some(name.clone().into()); + } + params +} + const REDUCER_SIGNATURE_HASH_DOMAIN: &[u8] = b"spacetimedb:idc:reducer-signature:v1\0"; /// Computes the IDC signature hash from parameter names, order, types, and both return types. @@ -2536,7 +2555,7 @@ impl From for RawReducerDefV10 { fn from(val: ReducerDef) -> Self { RawReducerDefV10 { source_name: val.accessor_name.into(), - params: val.params, + params: canonical_params(val.params, &val.params_for_generate), visibility: val.visibility.into(), ok_return_type: val.ok_return_type, err_return_type: val.err_return_type, @@ -2624,7 +2643,7 @@ impl From for RawProcedureDefV10 { fn from(val: ProcedureDef) -> Self { RawProcedureDefV10 { source_name: val.accessor_name.into(), - params: val.params, + params: canonical_params(val.params, &val.params_for_generate), return_type: val.return_type, visibility: val.visibility.into(), } @@ -2880,6 +2899,60 @@ mod tests { ); } + #[test] + fn v10_roundtrip_preserves_reducer_signature_casing() { + use spacetimedb_lib::db::raw_def::v10::{CaseConversionPolicy, RawModuleDefV10Builder}; + + for policy in [CaseConversionPolicy::None, CaseConversionPolicy::SnakeCase] { + let mut builder = RawModuleDefV10Builder::new(); + builder.set_case_conversion_policy(policy); + let item_ref = builder.add_algebraic_type( + [], + "Message", + AlgebraicType::product([("Item", AlgebraicType::U64)]), + false, + ); + builder.add_reducer( + "receive", + ProductType::from([("MessageBody", AlgebraicType::Ref(item_ref))]), + ); + builder.add_procedure( + "read_message", + ProductType::from([("MessageBody", AlgebraicType::Ref(item_ref))]), + AlgebraicType::Ref(item_ref), + ); + builder.add_view( + "messages", + 0, + true, + true, + ProductType::from([("MessageBody", AlgebraicType::Ref(item_ref))]), + AlgebraicType::array(AlgebraicType::Ref(item_ref)), + ); + let original: ModuleDef = builder.finish().try_into().expect("valid module"); + let roundtrip = + ModuleDef::try_from(RawModuleDefV10::from(original.clone())).expect("valid roundtripped module"); + let signature = |module: &ModuleDef| { + let (_, reducer) = module.reducer_by_name("receive").expect("receiver exists"); + reducer_signature_hash( + &reducer.params(), + &reducer.ok_return_type, + &reducer.err_return_type, + module.typespace(), + ) + }; + + assert_eq!(original.typespace(), roundtrip.typespace()); + assert_eq!(signature(&original), signature(&roundtrip)); + for (original, roundtrip) in original.procedures().zip(roundtrip.procedures()) { + assert_eq!(original.params_for_generate, roundtrip.params_for_generate); + } + for (original, roundtrip) in original.views().zip(roundtrip.views()) { + assert_eq!(original.params_for_generate, roundtrip.params_for_generate); + } + } + } + #[test] fn v10_roundtrip_preserves_column_defaults() { use spacetimedb_lib::db::raw_def::v10::RawModuleDefV10Builder; diff --git a/crates/schema/src/def/validate/v10.rs b/crates/schema/src/def/validate/v10.rs index 8e96422fedb..f8c554bf84e 100644 --- a/crates/schema/src/def/validate/v10.rs +++ b/crates/schema/src/def/validate/v10.rs @@ -279,10 +279,21 @@ pub fn validate(def: RawModuleDefV10) -> Result { schedules, lifecycle_validations, http_handlers_and_routes, + Ok(raw_outboxes), ) .combine_errors() .and_then( - |(mut tables, types, reducers, procedures, views, schedules, lifecycles, http_handlers_and_routes)| { + |( + mut tables, + types, + reducers, + procedures, + views, + schedules, + lifecycles, + http_handlers_and_routes, + raw_outboxes, + )| { let (mut reducers, mut procedures, mut views) = check_function_names_are_unique(reducers, procedures, views)?; // Attach lifecycles to their respective reducers @@ -291,7 +302,7 @@ pub fn validate(def: RawModuleDefV10) -> Result { // Attach schedules to their respective tables attach_schedules_to_tables(&mut tables, schedules)?; - attach_outboxes_to_tables(&mut tables, raw_outboxes)?; + attach_outboxes_to_tables(&mut tables, &mut reducers, raw_outboxes, &mut validator.core)?; check_scheduled_functions_exist(&mut tables, &reducers, &procedures)?; change_scheduled_functions_and_lifetimes_visibility(&tables, &mut reducers, &mut procedures)?; @@ -804,11 +815,11 @@ impl<'a> ModuleValidatorV10<'a> { constraints, sequences, schedule: None, // V10 handles schedules separately + outbox: None, // V10 handles outboxes separately table_type, table_access, is_event, accessor_name: identifier(raw_table_name)?, - outbox: None, }) } @@ -1158,49 +1169,27 @@ fn attach_lifecycles_to_reducers( Ok(()) } -fn attach_schedules_to_tables( +fn attach_outboxes_to_tables( tables: &mut HashMap, - schedules: Vec<(ScheduleDef, Identifier)>, + reducers: &mut IndexMap, + outboxes: Vec, + core: &mut CoreValidator<'_>, ) -> Result<()> { - for schedule in schedules { - let (schedule, table_name) = schedule; - let table = tables.values_mut().find(|t| *t.name == *table_name).ok_or_else(|| { - ValidationError::MissingScheduleTable { - table_name: table_name.as_raw().clone(), - schedule_name: schedule.name.clone(), - } - })?; - - // Enforce invariant: only one schedule per table - if table.schedule.is_some() { - return Err(ValidationError::DuplicateSchedule { - table: table.name.clone(), - } - .into()); - } - - if table.is_event { - return Err(ValidationError::ScheduledEventTable { - table: table.name.clone(), - } - .into()); - } - - table.schedule = Some(schedule); - } - - Ok(()) -} - -fn attach_outboxes_to_tables(tables: &mut HashMap, outboxes: Vec) -> Result<()> { for outbox in outboxes { - let table_ident = identifier(outbox.table_name.clone())?; - let raw_table_name = outbox.table_name.clone(); + let RawOutboxDefV10 { + table_source_name, + remote_reducer, + target_column, + arg_columns, + on_result_reducer, + signature_hash, + } = outbox; + let table = tables .values_mut() - .find(|table| table.accessor_name == table_ident) - .ok_or_else(|| ValidationError::TableNotFound { - table: raw_table_name.clone(), + .find(|table| table.accessor_name.as_raw() == &table_source_name) + .ok_or_else(|| ValidationError::MissingOutboxTable { + table_name: table_source_name.clone(), })?; if table.outbox.is_some() { @@ -1236,7 +1225,7 @@ fn attach_outboxes_to_tables(tables: &mut HashMap, outboxe .into()); } - let Some(target_col) = table.columns.get(outbox.target_column.idx()) else { + let Some(target_col) = table.columns.get(target_column.idx()) else { return Err(ValidationError::OutboxTargetColumnMissing { table: table.name.clone(), } @@ -1249,7 +1238,7 @@ fn attach_outboxes_to_tables(tables: &mut HashMap, outboxe .into()); } - for arg_column in &outbox.arg_columns { + for arg_column in &arg_columns { if table.columns.get(arg_column.idx()).is_none() { return Err(ValidationError::OutboxArgumentColumnNotFound { table: table.name.clone(), @@ -1259,28 +1248,72 @@ fn attach_outboxes_to_tables(tables: &mut HashMap, outboxe } } + let on_result_reducer = on_result_reducer + .map(|name| { + let raw_name = name.clone(); + let name = core.resolve_function_ident(name)?; + if let Some(reducer) = reducers.get_mut(&name) { + reducer.visibility = crate::def::FunctionVisibility::Private; + Ok::<_, ValidationErrors>(name) + } else { + Err(ValidationError::MissingOutboxOnResult { + table: table.name.clone(), + reducer_name: raw_name, + } + .into()) + } + }) + .transpose()?; + table.outbox = Some(OutboxDef { remote_reducer: ReducerName::new( - NamespacedIdentifier::new(&RawNamespacedIdentifier::new(outbox.remote_reducer.into_inner())) + NamespacedIdentifier::new(&RawNamespacedIdentifier::new(remote_reducer.into_inner())) .map_err(|error| ValidationError::IdentifierError { error })?, ), - target_column: outbox.target_column, - arg_columns: outbox.arg_columns, - on_result_reducer: outbox - .on_result_reducer - .map(|name| { - NamespacedIdentifier::new(&RawNamespacedIdentifier::new(name.into_inner())) - .map(ReducerName::new) - .map_err(|error| ErrorStream::from(ValidationError::IdentifierError { error })) - }) - .transpose()?, - signature_hash: outbox.signature_hash, + target_column, + arg_columns, + on_result_reducer: on_result_reducer.map(ReducerName::new), + signature_hash, }); } Ok(()) } +fn attach_schedules_to_tables( + tables: &mut HashMap, + schedules: Vec<(ScheduleDef, Identifier)>, +) -> Result<()> { + for schedule in schedules { + let (schedule, table_name) = schedule; + let table = tables.values_mut().find(|t| *t.name == *table_name).ok_or_else(|| { + ValidationError::MissingScheduleTable { + table_name: table_name.as_raw().clone(), + schedule_name: schedule.name.clone(), + } + })?; + + // Enforce invariant: only one schedule per table + if table.schedule.is_some() { + return Err(ValidationError::DuplicateSchedule { + table: table.name.clone(), + } + .into()); + } + + if table.is_event { + return Err(ValidationError::ScheduledEventTable { + table: table.name.clone(), + } + .into()); + } + + table.schedule = Some(schedule); + } + + Ok(()) +} + /// Attach explicit view primary-key metadata from the raw V10 `ViewPrimaryKeys` /// section to validated [`ViewDef`]s. /// @@ -1422,6 +1455,7 @@ mod tests { use crate::error::*; use crate::identifier::Identifier; use crate::identifier::NamespacePath; + use crate::reducer_name::ReducerName; use crate::type_for_generate::ClientCodegenError; use itertools::Itertools; @@ -1433,6 +1467,7 @@ mod tests { use spacetimedb_lib::db::raw_def::v9::{btree, direct, hash}; use spacetimedb_lib::db::raw_def::*; use spacetimedb_lib::db::view::QUERY_VIEW_RETURN_TAG; + use spacetimedb_lib::hash_bytes; use spacetimedb_lib::http::Method as HttpMethod; use spacetimedb_lib::ScheduleAt; use spacetimedb_primitives::{ColId, ColList, ColSet}; @@ -1753,13 +1788,14 @@ mod tests { .with_index_no_accessor_name(direct(0), "outbound_pings_msg_id_idx_btree") .finish(); builder.add_reducer("receive_ping", ProductType::from([("payload", AlgebraicType::String)])); + let signature_hash = hash_bytes(b"test-signature"); builder.add_outbox( "outbound_pings", "receive_ping", ColId(1), [ColId(2)], Option::<&str>::None, - "test-signature", + signature_hash, ); let module: ModuleDef = builder.finish().try_into().expect("valid outbox module"); @@ -1768,7 +1804,7 @@ mod tests { assert_eq!(&outbox.remote_reducer[..], "receive_ping"); assert_eq!(outbox.target_column, ColId(1)); assert_eq!(outbox.arg_columns, vec![ColId(2)]); - assert_eq!(outbox.signature_hash, "test-signature"); + assert_eq!(outbox.signature_hash, signature_hash); let schema = TableSchema::from_module_def(&module, table, (), TableId::SENTINEL); let outbox = schema.outbox.expect("TableSchema carries outbox metadata"); @@ -1800,7 +1836,7 @@ mod tests { ColId(1), [ColId(2)], Option::<&str>::None, - "test-signature", + spacetimedb_lib::hash_bytes(b"test-signature"), ); let result: Result = builder.finish().try_into(); @@ -2558,6 +2594,84 @@ mod tests { }); } + fn outbox_with_on_result() -> RawModuleDefV10Builder { + let mut builder = RawModuleDefV10Builder::new(); + builder + .build_table_with_new_type( + "PingOutbox", + ProductType::from([ + ("msg_id", AlgebraicType::U64), + ("target", AlgebraicType::U256), + ("payload", AlgebraicType::String), + ]), + true, + ) + .with_auto_inc_primary_key(0) + .with_index_no_accessor_name(direct(0), "ping_outbox_msg_id_idx_btree") + .finish(); + builder.add_reducer("on_ping_result", ProductType::unit()); + builder.add_outbox( + "PingOutbox", + "receive_ping", + ColId(1), + [ColId(2)], + Some("on_ping_result"), + hash_bytes(b"receive_ping"), + ); + builder + } + + #[test] + fn outbox_on_result_reducer_is_attached() { + let def: ModuleDef = outbox_with_on_result().finish().try_into().unwrap(); + let table = &def.tables[&expect_identifier("ping_outbox")]; + let outbox = table.outbox.as_ref().unwrap(); + + assert_eq!(outbox.remote_reducer, ReducerName::for_test("receive_ping")); + assert_eq!(outbox.target_column, ColId(1)); + assert_eq!(outbox.on_result_reducer, Some(ReducerName::for_test("on_ping_result"))); + assert_eq!( + def.reducers[&expect_identifier("on_ping_result")].visibility, + FunctionVisibility::Private + ); + } + + #[test] + fn outbox_on_result_uses_canonical_submodule_namespace_and_round_trips() { + let mut child = outbox_with_on_result(); + let mut names = ExplicitNames::default(); + names.insert_table("PingOutbox", "WireOutbox"); + names.insert_function("on_ping_result", "ResultDone"); + child.add_explicit_names(names); + + let mut middle = RawModuleDefV10Builder::new(); + middle.add_submodule("innerMount", child.finish()); + let mut names = ExplicitNames::default(); + names.insert_namespace("innerMount", "InnerWire"); + middle.add_explicit_names(names); + + let mut root = RawModuleDefV10Builder::new(); + root.add_submodule("outerLib", middle.finish()); + let mut def: ModuleDef = root.finish().try_into().unwrap(); + + for _ in 0..3 { + let child = &def.submodules()["outer_lib"].submodules()["InnerWire"]; + let table = &child.tables[&expect_identifier("WireOutbox")]; + let outbox = table.outbox.as_ref().unwrap(); + let callback = outbox.on_result_reducer.as_ref().unwrap(); + assert_eq!(&**callback, "outer_lib.InnerWire.ResultDone"); + assert_eq!( + def.reducer_by_name(callback).unwrap().1.visibility, + FunctionVisibility::Private + ); + assert_eq!(outbox.remote_reducer, ReducerName::for_test("receive_ping")); + assert_eq!(&*table.accessor_name, "PingOutbox"); + + let raw: RawModuleDefV10 = def.into(); + def = raw.try_into().expect("mounted outbox callback should round-trip"); + } + } + #[test] fn missing_scheduled_reducer() { let mut builder = RawModuleDefV10Builder::new(); diff --git a/crates/schema/src/def/validate/v9.rs b/crates/schema/src/def/validate/v9.rs index 5fd18abc64c..c8e5dcd2b60 100644 --- a/crates/schema/src/def/validate/v9.rs +++ b/crates/schema/src/def/validate/v9.rs @@ -340,11 +340,11 @@ impl ModuleValidatorV9<'_> { constraints, sequences, schedule, + outbox: None, // V9 modules do not support IDC outbox metadata. table_type, table_access, is_event: false, // V9 does not support event tables accessor_name: name, - outbox: None, }) } diff --git a/crates/schema/src/error.rs b/crates/schema/src/error.rs index 391db8584cd..58977a51ec3 100644 --- a/crates/schema/src/error.rs +++ b/crates/schema/src/error.rs @@ -150,8 +150,6 @@ pub enum ValidationError { MultipleColumnDefaultValues { table: RawIdentifier, col_id: ColId }, #[error("Table {table} not found")] TableNotFound { table: RawIdentifier }, - #[error("table {table} is assigned in multiple outboxes")] - DuplicateOutbox { table: Identifier }, #[error("outbox table {table} must not be an event table")] OutboxEventTable { table: Identifier }, #[error("outbox table {table} must not be a scheduled table")] @@ -190,6 +188,15 @@ pub enum ValidationError { DuplicateSchedule { table: Identifier }, #[error("scheduled table {table} must not be an event table")] ScheduledEventTable { table: Identifier }, + #[error("table {table} is assigned in multiple outbox definitions")] + DuplicateOutbox { table: Identifier }, + #[error("outbox table {} not found", table_name)] + MissingOutboxTable { table_name: RawIdentifier }, + #[error("on_result reducer {reducer_name} for outbox {table} does not exist")] + MissingOutboxOnResult { + table: Identifier, + reducer_name: RawIdentifier, + }, #[error("table {} corresponding to schedule {} not found", table_name, schedule_name)] MissingScheduleTable { table_name: RawIdentifier, diff --git a/crates/schema/src/schema.rs b/crates/schema/src/schema.rs index 67ec9bb35ff..dd1de77fba2 100644 --- a/crates/schema/src/schema.rs +++ b/crates/schema/src/schema.rs @@ -14,6 +14,7 @@ use itertools::Itertools; use spacetimedb_lib::db::auth::{StAccess, StTableType}; use spacetimedb_lib::db::raw_def::v9::RawSql; use spacetimedb_lib::db::raw_def::{generate_cols_name, RawConstraintDefV8}; +use spacetimedb_lib::Hash as SpacetimeHash; use spacetimedb_primitives::*; use spacetimedb_sats::product_value::InvalidFieldError; use spacetimedb_sats::raw_identifier::{RawIdentifier, RawNamespacedIdentifier}; @@ -987,11 +988,11 @@ impl Schema for TableSchema { constraints, sequences, schedule, + outbox, table_type, table_access, is_event, accessor_name, - outbox, .. } = def; @@ -1023,7 +1024,7 @@ impl Schema for TableSchema { target_column: outbox.target_column, arg_columns: outbox.arg_columns.clone(), on_result_reducer: outbox.on_result_reducer.clone(), - signature_hash: outbox.signature_hash.clone(), + signature_hash: outbox.signature_hash, }); TableSchema::new( @@ -1471,7 +1472,7 @@ pub struct OutboxSchema { /// Local reducer to invoke with the remote result before acknowledging this stream. pub on_result_reducer: Option, /// Hash of the receiver reducer signature as seen by the sender bindings. - pub signature_hash: String, + pub signature_hash: SpacetimeHash, } impl OutboxSchema { diff --git a/crates/smoketests/modules/Cargo.lock b/crates/smoketests/modules/Cargo.lock index 511af9a1eea..44a26585b69 100644 --- a/crates/smoketests/modules/Cargo.lock +++ b/crates/smoketests/modules/Cargo.lock @@ -856,6 +856,20 @@ dependencies = [ "spacetimedb", ] +[[package]] +name = "smoketest-module-idc-receiver" +version = "0.1.0" +dependencies = [ + "spacetimedb", +] + +[[package]] +name = "smoketest-module-idc-sender" +version = "0.1.0" +dependencies = [ + "spacetimedb", +] + [[package]] name = "smoketest-module-logs-level-filter" version = "0.1.0" diff --git a/crates/smoketests/modules/Cargo.toml b/crates/smoketests/modules/Cargo.toml index 447c7cef977..8870181aedd 100644 --- a/crates/smoketests/modules/Cargo.toml +++ b/crates/smoketests/modules/Cargo.toml @@ -117,6 +117,8 @@ members = [ "logs-level-filter", # Misc tests + "idc-receiver", + "idc-sender", "namespaces", "new-user-flow", "module-nested-op", diff --git a/crates/smoketests/modules/idc-receiver/Cargo.toml b/crates/smoketests/modules/idc-receiver/Cargo.toml new file mode 100644 index 00000000000..a359cb3ad5f --- /dev/null +++ b/crates/smoketests/modules/idc-receiver/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "smoketest-module-idc-receiver" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +spacetimedb.workspace = true diff --git a/crates/smoketests/modules/idc-receiver/src/lib.rs b/crates/smoketests/modules/idc-receiver/src/lib.rs new file mode 100644 index 00000000000..ccbfc56d66c --- /dev/null +++ b/crates/smoketests/modules/idc-receiver/src/lib.rs @@ -0,0 +1,58 @@ +use spacetimedb::Table; + +const MODULE_VERSION: u32 = 1; + +#[derive(spacetimedb::SpacetimeType)] +pub struct PingDetails { + pub labels: Vec, + pub checkpoints: Vec, + pub note: Option, +} + +#[derive(spacetimedb::SpacetimeType)] +pub struct PingCheckpoint { + pub sequence: u32, + pub state: PingState, +} + +#[derive(spacetimedb::SpacetimeType)] +pub enum PingState { + Ready, + Deferred(Option), +} + +#[spacetimedb::table(accessor = ping_log)] +pub struct PingLog { + #[primary_key] + #[auto_inc] + id: u64, + sender: spacetimedb::Identity, + module_version: u32, + body: String, +} + +#[spacetimedb::reducer] +pub fn receive_ping(ctx: &spacetimedb::ReducerContext, body: String) { + ctx.db.ping_log().insert(PingLog { + id: 0, + sender: ctx.sender(), + module_version: MODULE_VERSION, + body, + }); +} + +#[spacetimedb::table(accessor = detailed_ping_log)] +pub struct DetailedPingLog { + #[primary_key] + #[auto_inc] + id: u64, + body: String, + details: PingDetails, +} + +#[spacetimedb::reducer] +pub fn receive_detailed_ping(ctx: &spacetimedb::ReducerContext, body: String, details: PingDetails) { + ctx.db + .detailed_ping_log() + .insert(DetailedPingLog { id: 0, body, details }); +} diff --git a/crates/smoketests/modules/idc-sender/Cargo.toml b/crates/smoketests/modules/idc-sender/Cargo.toml new file mode 100644 index 00000000000..9b4ac618508 --- /dev/null +++ b/crates/smoketests/modules/idc-sender/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "smoketest-module-idc-sender" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +spacetimedb.workspace = true diff --git a/crates/smoketests/modules/idc-sender/src/lib.rs b/crates/smoketests/modules/idc-sender/src/lib.rs new file mode 100644 index 00000000000..ca31cc45713 --- /dev/null +++ b/crates/smoketests/modules/idc-sender/src/lib.rs @@ -0,0 +1,134 @@ +mod remote_bindings; + +use remote_bindings::game_world; +use spacetimedb::Table; + +const MODULE_VERSION: u32 = 1; + +#[spacetimedb::table(accessor = ping_log)] +pub struct PingLog { + #[primary_key] + #[auto_inc] + id: u64, + sender: spacetimedb::Identity, + body: String, +} + +#[spacetimedb::reducer] +pub fn receive_ping(ctx: &spacetimedb::ReducerContext, body: String) { + ctx.db.ping_log().insert(PingLog { + id: 0, + sender: ctx.sender(), + body, + }); +} + +#[spacetimedb::table(accessor = outbound_ping, outbox(game_world::receive_ping))] +pub struct OutboundPing { + #[primary_key] + #[auto_inc] + message_number: u64, + #[target] + destination: game_world::Identity, + #[param(name = body)] + bodypo: String, +} + +#[spacetimedb::reducer] +pub fn enqueue_ping(ctx: &spacetimedb::ReducerContext, target: game_world::Identity, body: String) { + ctx.db.outbound_ping().insert(OutboundPing { + message_number: 0, + destination: target, + bodypo: body, + }); +} + +#[spacetimedb::reducer] +pub fn enqueue_pings(ctx: &spacetimedb::ReducerContext, target: game_world::Identity, bodies: Vec) { + for body in bodies { + enqueue_ping(ctx, target, body); + } +} + +#[spacetimedb::table(accessor = ping_result)] +pub struct PingResult { + #[primary_key] + id: u64, + #[auto_inc] + callback_order: u64, + module_version: u32, + body: String, + succeeded: bool, + error: Option, +} + +#[spacetimedb::reducer(on_result(self::outbound_ping))] +pub fn on_ping_result(ctx: &spacetimedb::ReducerContext, row: OutboundPing, result: Result<(), String>) { + ctx.db.ping_result().insert(PingResult { + id: row.message_number, + callback_order: 0, + module_version: MODULE_VERSION, + body: row.bodypo, + succeeded: result.is_ok(), + error: result.err(), + }); +} + +#[spacetimedb::table(accessor = outbound_detailed_ping, outbox(game_world::receive_detailed_ping))] +pub struct OutboundDetailedPing { + #[primary_key] + #[auto_inc] + id: u64, + #[target] + target: game_world::Identity, + body: String, + details: game_world::PingDetails, +} + +#[spacetimedb::reducer] +pub fn enqueue_detailed_ping(ctx: &spacetimedb::ReducerContext, target: game_world::Identity, body: String) { + ctx.db.outbound_detailed_ping().insert(OutboundDetailedPing { + id: 0, + target, + body, + details: game_world::PingDetails { + labels: vec!["nested".into(), "idc".into()], + checkpoints: vec![ + game_world::PingCheckpoint { + sequence: 1, + state: game_world::PingState::Ready, + }, + game_world::PingCheckpoint { + sequence: 2, + state: game_world::PingState::Deferred(Some("waiting".into())), + }, + game_world::PingCheckpoint { + sequence: 3, + state: game_world::PingState::Deferred(None), + }, + ], + note: Some("optional-note".into()), + }, + }); +} + +#[spacetimedb::table(accessor = detailed_ping_result)] +pub struct DetailedPingResult { + #[primary_key] + id: u64, + body: String, + details: game_world::PingDetails, +} + +#[spacetimedb::reducer(on_result(self::outbound_detailed_ping))] +pub fn on_detailed_ping_result( + ctx: &spacetimedb::ReducerContext, + row: OutboundDetailedPing, + _result: Result<(), String>, +) { + ctx.db.detailed_ping_result().insert(DetailedPingResult { + id: row.id, + body: row.body, + details: row.details, + }); +} diff --git a/crates/smoketests/modules/idc-sender/src/remote_bindings/mod.rs b/crates/smoketests/modules/idc-sender/src/remote_bindings/mod.rs new file mode 100644 index 00000000000..c904f0a6d0d --- /dev/null +++ b/crates/smoketests/modules/idc-sender/src/remote_bindings/mod.rs @@ -0,0 +1,2 @@ +#[path = "receiver/lib.rs"] +pub mod game_world; diff --git a/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/lib.rs b/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/lib.rs new file mode 100644 index 00000000000..f9917957e3f --- /dev/null +++ b/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/lib.rs @@ -0,0 +1,216 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] + +use spacetimedb::spacetimedb_lib as __lib; + +pub mod ping_checkpoint_type; +pub mod ping_details_type; +pub mod ping_state_type; + +pub use ping_checkpoint_type::PingCheckpoint; +pub use ping_details_type::PingDetails; +pub use ping_state_type::PingState; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct Identity(pub spacetimedb::Identity); + +impl spacetimedb::SpacetimeType for Identity { + fn make_type( + typespace: &mut S, + ) -> spacetimedb::spacetimedb_lib::AlgebraicType { + ::make_type(typespace) + } +} + +impl spacetimedb::Serialize for Identity { + fn serialize(&self, serializer: S) -> Result { + ::serialize(&self.0, serializer) + } +} + +impl<'de> spacetimedb::Deserialize<'de> for Identity { + fn deserialize>(deserializer: D) -> Result { + ::deserialize(deserializer).map(Self) + } +} + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct ReceiveDetailedPingArgs { + pub body: String, + pub details: PingDetails, +} + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_detailed_ping_body_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as body), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(body), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_receive_detailed_ping_body_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_detailed_ping_body_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_detailed_ping_body { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(body), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as body), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: String = x; }; + $module::__spacetimedb_typecheck_outbox_receive_detailed_ping_body_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_receive_detailed_ping_body!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_detailed_ping_body; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_detailed_ping_details_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as details), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(details), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_receive_detailed_ping_details_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_detailed_ping_details_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_detailed_ping_details { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(details), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as details), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: $module::PingDetails = x; }; + $module::__spacetimedb_typecheck_outbox_receive_detailed_ping_details_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_receive_detailed_ping_details!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_detailed_ping_details; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_detailed_ping { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_receive_detailed_ping_body!(__outbox_receiver; $($columns)*), + __outbox_receiver::__spacetimedb_typecheck_outbox_receive_detailed_ping_details!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_detailed_ping; + +#[allow(non_camel_case_types)] +pub struct receive_detailed_ping; + +impl spacetimedb::rt::RemoteReducer for receive_detailed_ping { + const NAME: &'static str = "receive_detailed_ping"; + const SIGNATURE_HASH: &'static str = "fa1b6b89ae6916bc96abf80e9b1c7e2ab847783b3944f05f46f89055f22b1cce"; + type Args = ReceiveDetailedPingArgs; +} + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct ReceivePingArgs { + pub body: String, +} + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate { + ($module:ident;) => {}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as body), $($rest:tt)*) => { + compile_error!(concat!( + "outbox has multiple columns matching remote reducer parameter `", + stringify!(body), + "`" + )); + }; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate!($module; $($rest)*); + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_ping_body { + ($module:ident;) => {{ + compile_error!(concat!( + "outbox has no column matching remote reducer parameter `", + stringify!(body), + "`" + )); + 0u16 + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as body), $($rest:tt)*) => {{ + let _ = |x: $ty| { let _: String = x; }; + $module::__spacetimedb_typecheck_outbox_receive_ping_body_reject_duplicate!($module; $($rest)*); + $index + }}; + ($module:ident; ($index:literal, $field:ident : $ty:ty as $other:ident), $($rest:tt)*) => { + $module::__spacetimedb_typecheck_outbox_receive_ping_body!($module; $($rest)*) + }; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_ping_body; + +#[doc(hidden)] +macro_rules! __spacetimedb_typecheck_outbox_receive_ping { + ($module:path, { $($columns:tt)* }) => {{ + #[allow(unused_imports)] + use $module as __outbox_receiver; + &[__outbox_receiver::__spacetimedb_typecheck_outbox_receive_ping_body!(__outbox_receiver; $($columns)*)] + }}; +} + +#[doc(hidden)] +pub(crate) use __spacetimedb_typecheck_outbox_receive_ping; + +#[allow(non_camel_case_types)] +pub struct receive_ping; + +impl spacetimedb::rt::RemoteReducer for receive_ping { + const NAME: &'static str = "receive_ping"; + const SIGNATURE_HASH: &'static str = "386957a94632958d5ae8343e258f3a6f9dce9d7dafc46831050894baa7a4e4e1"; + type Args = ReceivePingArgs; +} diff --git a/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_checkpoint_type.rs b/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_checkpoint_type.rs new file mode 100644 index 00000000000..1189bb1dc71 --- /dev/null +++ b/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_checkpoint_type.rs @@ -0,0 +1,12 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::ping_state_type::PingState; +use super::Identity; + +#[derive(spacetimedb::SpacetimeType, Clone, PartialEq, Debug)] +pub struct PingCheckpoint { + pub sequence: u32, + pub state: PingState, +} diff --git a/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_details_type.rs b/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_details_type.rs new file mode 100644 index 00000000000..7dd61824d92 --- /dev/null +++ b/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_details_type.rs @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::ping_checkpoint_type::PingCheckpoint; +use super::Identity; + +#[derive(spacetimedb::SpacetimeType, Clone, PartialEq, Debug)] +pub struct PingDetails { + pub labels: Vec, + pub checkpoints: Vec, + pub note: Option, +} diff --git a/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_state_type.rs b/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_state_type.rs new file mode 100644 index 00000000000..ef14875bdd6 --- /dev/null +++ b/crates/smoketests/modules/idc-sender/src/remote_bindings/receiver/ping_state_type.rs @@ -0,0 +1,11 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::Identity; + +#[derive(spacetimedb::SpacetimeType, Clone, PartialEq, Debug)] +pub enum PingState { + Ready, + Deferred(Option), +} diff --git a/crates/smoketests/src/lib.rs b/crates/smoketests/src/lib.rs index 423d4524e35..5d2f56cc61f 100644 --- a/crates/smoketests/src/lib.rs +++ b/crates/smoketests/src/lib.rs @@ -189,6 +189,17 @@ pub fn workspace_root() -> PathBuf { .to_path_buf() } +/// Copies a Rust module fixture's manifest and source into a temporary project. +pub fn copy_module_fixture(name: &str, dest: &Path) -> Result<()> { + let source = workspace_root().join("crates/smoketests/modules").join(name); + fs::create_dir_all(dest.join("src"))?; + for file in ["Cargo.toml", "src/lib.rs"] { + fs::copy(source.join(file), dest.join(file)) + .with_context(|| format!("Failed to copy {file} from fixture {name}"))?; + } + Ok(()) +} + /// Rewrites `spacetimedb` dependency in `/Cargo.toml` to use local workspace bindings. pub fn patch_module_cargo_to_local_bindings(module_dir: &Path) -> Result<()> { let cargo_toml_path = module_dir.join("Cargo.toml"); @@ -202,7 +213,9 @@ pub fn patch_module_cargo_to_local_bindings(module_dir: &Path) -> Result<()> { let patched = cargo_toml .lines() .map(|line| { - if line.trim_start().starts_with("spacetimedb = ") { + if line.trim_start().starts_with("spacetimedb = ") + || line.trim_start().starts_with("spacetimedb.workspace = ") + { replacement.as_str() } else { line @@ -453,7 +466,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Emscripten") endif() "#; -fn parse_identity_from_publish_output(publish_output: &str) -> Result { +/// Extracts the database identity from a single database publication. +pub fn parse_identity_from_publish_output(publish_output: &str) -> Result { let re = Regex::new(r"identity: ([0-9a-fA-F]+)").unwrap(); re.captures(publish_output) .and_then(|caps| caps.get(1)) @@ -1539,7 +1553,15 @@ log = "0.4" pub fn call(&self, name: &str, args: &[&str]) -> Result { let identity = self.database_identity.as_ref().context("No database published")?; - let mut cmd_args = vec!["call", "--server", &self.server_url, "--", identity.as_str(), name]; + let mut cmd_args = vec![ + "call", + "--no-config", + "--server", + &self.server_url, + "--", + identity.as_str(), + name, + ]; cmd_args.extend(args); self.spacetime(&cmd_args) @@ -1549,7 +1571,15 @@ log = "0.4" pub fn call_output(&self, name: &str, args: &[&str]) -> Output { let identity = self.database_identity.as_ref().expect("No database published"); - let mut cmd_args = vec!["call", "--server", &self.server_url, "--", identity.as_str(), name]; + let mut cmd_args = vec![ + "call", + "--no-config", + "--server", + &self.server_url, + "--", + identity.as_str(), + name, + ]; cmd_args.extend(args); self.spacetime_cmd(&cmd_args) @@ -1561,6 +1591,7 @@ log = "0.4" let mut cmd_args = vec![ "call", + "--no-config", "--anonymous", "--server", &self.server_url, diff --git a/crates/smoketests/tests/cluster.rs b/crates/smoketests/tests/cluster.rs index f0aa305b01a..62ca5ff4ca7 100644 --- a/crates/smoketests/tests/cluster.rs +++ b/crates/smoketests/tests/cluster.rs @@ -23,6 +23,7 @@ mod cluster { mod filtering; mod http_egress; mod http_routes; + mod idc; mod logs_level_filter; mod module_nested_op; mod modules; diff --git a/crates/smoketests/tests/cluster/idc.rs b/crates/smoketests/tests/cluster/idc.rs new file mode 100644 index 00000000000..636590c3be6 --- /dev/null +++ b/crates/smoketests/tests/cluster/idc.rs @@ -0,0 +1,424 @@ +use std::time::{Duration, Instant}; + +use spacetimedb_smoketests::{ + copy_module_fixture, parse_identity_from_publish_output, patch_module_cargo_to_local_bindings, random_string, + Smoketest, +}; + +struct IdcTest { + test: Smoketest, + receiver: String, + sender: String, +} + +impl IdcTest { + fn new() -> Self { + let mut test = Smoketest::builder().autopublish(false).build(); + let receiver_db = format!("idc-receiver-{}", random_string()); + let sender_db = format!("idc-sender-{}", random_string()); + + for name in ["receiver", "sender"] { + let dir = test.project_dir.path().join(name); + copy_module_fixture(&format!("idc-{name}"), &dir).expect("failed to copy module fixture"); + patch_module_cargo_to_local_bindings(&dir).expect("failed to patch module Cargo.toml"); + } + std::fs::write( + test.project_dir.path().join("spacetime.json"), + serde_json::to_vec_pretty(&serde_json::json!({ + "server": test.server_url, + "database": receiver_db, + "module-path": "./receiver", + "children": [ + { + "database": sender_db, + "module-path": "./sender", + "dependencies": [{ "name": "game_world", "database": receiver_db }] + } + ] + })) + .unwrap(), + ) + .expect("failed to write spacetime.json"); + test.spacetime(&["generate", &sender_db]) + .expect("failed to generate receiver bindings"); + test.spacetime(&["publish", "--server", &test.server_url, "--yes=all"]) + .expect("failed to publish IDC modules"); + + let resolve_identity = |database: &str| { + let response = test + .api_call("GET", &format!("/v1/database/{database}/identity")) + .expect("failed to resolve database identity"); + assert!( + response.is_success(), + "identity lookup failed for {database}: HTTP {}", + response.status_code + ); + response.text().expect("invalid database identity response") + }; + let receiver = resolve_identity(&receiver_db); + let sender = resolve_identity(&sender_db); + test.database_identity = Some(sender.clone()); + Self { test, receiver, sender } + } + + fn publish(&self, module: &str, database: &str) -> String { + let output = self + .test + .spacetime(&[ + "publish", + "--no-config", + "--server", + &self.test.server_url, + "--module-path", + self.test.project_dir.path().join(module).to_str().unwrap(), + "--yes=all", + database, + ]) + .expect("failed to publish module update"); + parse_identity_from_publish_output(&output).expect("publish output should contain database identity") + } + + fn rows(&self, database: &str, sql: &str) -> Vec { + let output = self + .test + .spacetime(&[ + "sql", + "--no-config", + "--server", + &self.test.server_url, + "--format", + "json", + database, + sql, + ]) + .expect("failed to query database"); + let results: serde_json::Value = serde_json::from_str(&output).expect("invalid SQL JSON output"); + results[0]["rows"] + .as_array() + .expect("SQL result should contain rows") + .clone() + } + + fn enqueue(&self, bodies: &[String]) { + self.test + .call( + "enqueue_pings", + &[ + &serde_json::to_string(&self.receiver).unwrap(), + &serde_json::to_string(bodies).unwrap(), + ], + ) + .expect("failed to enqueue pings"); + } + + fn wait_for_messages(&self, expected: &[(String, u32)]) { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + // The auto-increment columns record execution order, independently of message IDs. + let mut delivered = self.rows(&self.receiver, "SELECT id, body, module_version FROM ping_log"); + let mut callbacks = self.rows( + &self.sender, + "SELECT callback_order, body, module_version, succeeded, error FROM ping_result", + ); + delivered.sort_by_key(|row| row[0].as_u64().unwrap()); + callbacks.sort_by_key(|row| row[0].as_u64().unwrap()); + let pending = self.rows(&self.sender, "SELECT message_number FROM outbound_ping"); + assert!(delivered.len() <= expected.len(), "duplicate deliveries: {delivered:?}"); + assert!(callbacks.len() <= expected.len(), "duplicate callbacks: {callbacks:?}"); + if delivered.len() == expected.len() && callbacks.len() == expected.len() && pending.is_empty() { + for (index, (body, version)) in expected.iter().enumerate() { + assert_eq!(delivered[index][1], *body, "receiver delivery order"); + assert_eq!(delivered[index][2], *version, "receiver module version"); + assert_eq!(callbacks[index][1], *body, "sender callback order"); + assert_eq!(callbacks[index][2], *version, "sender module version"); + assert_eq!(callbacks[index][3], true, "callback failed: {:?}", callbacks[index]); + } + return; + } + assert!( + Instant::now() < deadline, + "IDC did not finish: delivered={delivered:?}, callbacks={callbacks:?}, pending={pending:?}" + ); + std::thread::sleep(Duration::from_millis(100)); + } + } + + fn send_ping_to(&self, receiver: &str, body: &str) { + self.test + .call( + "enqueue_ping", + &[ + &serde_json::to_string(receiver).unwrap(), + &serde_json::to_string(body).unwrap(), + ], + ) + .expect("failed to enqueue ping"); + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let callbacks = self.rows( + &self.sender, + &format!("SELECT succeeded FROM ping_result WHERE body = '{body}'"), + ); + let pending = self.rows(&self.sender, "SELECT message_number FROM outbound_ping"); + if !callbacks.is_empty() && pending.is_empty() { + assert_eq!(callbacks, vec![serde_json::json!([true])]); + assert_eq!( + self.rows(receiver, &format!("SELECT body FROM ping_log WHERE body = '{body}'")), + vec![serde_json::json!([body])], + ); + return; + } + assert!( + Instant::now() < deadline, + "ping {body} did not finish: {callbacks:?}, {pending:?}" + ); + std::thread::sleep(Duration::from_millis(100)); + } + } + + fn send_detailed_ping(&self, body: &str) { + self.test + .call( + "enqueue_detailed_ping", + &[ + &serde_json::to_string(&self.receiver).unwrap(), + &serde_json::to_string(body).unwrap(), + ], + ) + .expect("failed to enqueue detailed ping"); + let deadline = Instant::now() + Duration::from_secs(20); + let expected_details = serde_json::json!([ + ["nested", "idc"], + [[1, [0, []]], [2, [1, [0, "waiting"]]], [3, [1, [1, []]]]], + [0, "optional-note"] + ]); + loop { + let delivered = self.rows( + &self.receiver, + &format!("SELECT details FROM detailed_ping_log WHERE body = '{body}'"), + ); + let callbacks = self.rows( + &self.sender, + &format!("SELECT details FROM detailed_ping_result WHERE body = '{body}'"), + ); + let pending = self.rows(&self.sender, "SELECT id FROM outbound_detailed_ping"); + if !callbacks.is_empty() && pending.is_empty() { + assert_eq!(delivered, vec![serde_json::json!([expected_details])]); + assert_eq!(callbacks, vec![serde_json::json!([expected_details])]); + return; + } + assert!( + Instant::now() < deadline, + "detailed IDC ping did not finish: delivered={delivered:?}, callbacks={callbacks:?}, pending={pending:?}" + ); + std::thread::sleep(Duration::from_millis(100)); + } + } + + fn edit_module(&self, module: &str, from: &str, to: &str) { + let path = self.test.project_dir.path().join(module).join("src/lib.rs"); + let source = std::fs::read_to_string(&path).unwrap().replace("\r\n", "\n"); + assert!(source.contains(from), "missing source in {module}: {from}"); + std::fs::write(&path, source.replace(from, to)).unwrap(); + } + + fn update_modules(&self, version: u32) { + for (module, database) in [("receiver", &self.receiver), ("sender", &self.sender)] { + self.edit_module( + module, + &format!("const MODULE_VERSION: u32 = {};", version - 1), + &format!("const MODULE_VERSION: u32 = {version};"), + ); + assert_eq!(self.publish(module, database), *database); + } + } +} + +#[test] +fn idc_outbox_delivers_between_two_rust_modules() { + let suite = IdcTest::new(); + suite + .test + .call( + "enqueue_ping", + &[&serde_json::to_string(&suite.receiver).unwrap(), "\"hello-idc\""], + ) + .expect("failed to enqueue ping"); + suite.wait_for_messages(&[("hello-idc".into(), 1)]); +} + +#[test] +fn idc_outbox_delivers_twenty_messages_in_order() { + let suite = IdcTest::new(); + let bodies: Vec<_> = (0..20).map(|index| format!("message-{index}")).collect(); + suite.enqueue(&bodies); + suite.wait_for_messages(&bodies.into_iter().map(|body| (body, 1)).collect::>()); +} + +#[test] +fn idc_outbox_delivers_to_two_databases_with_the_same_receiver_module() { + let suite = IdcTest::new(); + let second_receiver = suite.publish("receiver", &format!("idc-receiver-{}", random_string())); + assert_ne!(suite.receiver, second_receiver); + + // The same bindings work for both databases before either receiver changes. + suite.send_ping_to(&suite.receiver, "first-receiver"); + suite.send_ping_to(&second_receiver, "second-receiver"); + + // Update only the first receiver. Existing rows get revision 0; new calls supply it. + suite.edit_module( + "receiver", + " module_version: u32,\n body: String,", + " module_version: u32,\n body: String,\n #[default(0)]\n revision: u32,", + ); + suite.edit_module( + "receiver", + "pub fn receive_ping(ctx: &spacetimedb::ReducerContext, body: String)", + "pub fn receive_ping(ctx: &spacetimedb::ReducerContext, body: String, revision: u32)", + ); + suite.edit_module("receiver", " body,\n", " body,\n revision,\n"); + assert_eq!(suite.publish("receiver", &suite.receiver), suite.receiver); + assert_eq!( + suite.rows(&suite.receiver, "SELECT body, revision FROM ping_log"), + vec![serde_json::json!(["first-receiver", 0])], + ); + + // Regenerate the first receiver's bindings and add the new argument to the sender's outbox. + suite + .test + .spacetime(&["generate"]) + .expect("failed to regenerate receiver bindings"); + suite.edit_module( + "sender", + " bodypo: String,", + " bodypo: String,\n #[default(0)]\n revision: u32,", + ); + suite.edit_module( + "sender", + " bodypo: body,", + " bodypo: body,\n revision: 7,", + ); + assert_eq!(suite.publish("sender", &suite.sender), suite.sender); + suite.send_ping_to(&suite.receiver, "after-update"); + assert_eq!( + suite.rows( + &suite.receiver, + "SELECT revision FROM ping_log WHERE body = 'after-update'" + ), + vec![serde_json::json!([7])], + ); + assert_eq!( + suite.rows(&second_receiver, "SELECT body FROM ping_log"), + vec![serde_json::json!(["second-receiver"])], + ); +} + +#[test] +fn idc_outboxes_deliver_in_both_directions_concurrently() { + let suite = IdcTest::new(); + let peer = suite.publish("sender", &format!("idc-peer-{}", random_string())); + let from_sender: Vec<_> = (0..20).map(|index| format!("sender-{index}")).collect(); + let from_peer: Vec<_> = (0..20).map(|index| format!("peer-{index}")).collect(); + + // Release both calls together, without waiting for either direction's deliveries. + let start = std::sync::Barrier::new(2); + std::thread::scope(|scope| { + for (source, target, bodies) in [(&suite.sender, &peer, &from_sender), (&peer, &suite.sender, &from_peer)] { + let (test, start) = (&suite.test, &start); + scope.spawn(move || { + start.wait(); + test.spacetime(&[ + "call", + "--no-config", + "--server", + &test.server_url, + "--", + source, + "enqueue_pings", + &serde_json::to_string(target).unwrap(), + &serde_json::to_string(bodies).unwrap(), + ]) + .expect("failed to enqueue concurrent pings"); + }); + } + }); + + for (database, incoming, outgoing) in [ + (&suite.sender, &from_peer, &from_sender), + (&peer, &from_sender, &from_peer), + ] { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let mut delivered = suite.rows(database, "SELECT id, body FROM ping_log"); + let mut callbacks = suite.rows(database, "SELECT callback_order, body, succeeded FROM ping_result"); + let pending = suite.rows(database, "SELECT message_number FROM outbound_ping"); + assert!(delivered.len() <= incoming.len(), "duplicate deliveries: {delivered:?}"); + assert!(callbacks.len() <= outgoing.len(), "duplicate callbacks: {callbacks:?}"); + if delivered.len() == incoming.len() && callbacks.len() == outgoing.len() && pending.is_empty() { + delivered.sort_by_key(|row| row[0].as_u64().unwrap()); + callbacks.sort_by_key(|row| row[0].as_u64().unwrap()); + for (row, body) in delivered.iter().zip(incoming) { + assert_eq!(row[1], *body, "delivery order for {database}"); + } + for (row, body) in callbacks.iter().zip(outgoing) { + assert_eq!(row[1], *body, "callback order for {database}"); + assert_eq!(row[2], true, "callback failed: {row:?}"); + } + break; + } + assert!( + Instant::now() < deadline, + "bidirectional IDC did not finish for {database}: delivered={delivered:?}, callbacks={callbacks:?}, pending={pending:?}" + ); + std::thread::sleep(Duration::from_millis(100)); + } + } +} + +#[test] +fn idc_outbox_preserves_order_across_module_updates() { + let suite = IdcTest::new(); + let mut expected = Vec::new(); + for version in 1..=4 { + if version == 2 { + // Rename the Rust accessor while preserving the canonical name used by the old bindings. + suite.edit_module( + "receiver", + "#[spacetimedb::reducer]\npub fn receive_ping", + "#[spacetimedb::reducer(name = \"receive_ping\")]\npub fn accept_ping", + ); + } + if version > 1 { + suite.update_modules(version); + } + let bodies: Vec<_> = (expected.len()..expected.len() + 5) + .map(|index| format!("message-{index}")) + .collect(); + suite.enqueue(&bodies); + expected.extend(bodies.into_iter().map(|body| (body, version))); + suite.wait_for_messages(&expected); + } +} + +#[test] +fn idc_outbox_uses_regenerated_bindings_after_argument_reordering() { + let suite = IdcTest::new(); + suite.send_detailed_ping("before-update"); + + // Changing parameter order changes the signature hash and the outbox's argument-column mapping. + // The stored row types stay the same, so both databases can be updated without clearing data. + suite.edit_module( + "receiver", + "body: String, details: PingDetails", + "details: PingDetails, body: String", + ); + suite + .test + .spacetime(&["generate"]) + .expect("failed to regenerate receiver bindings"); + assert_eq!(suite.publish("receiver", &suite.receiver), suite.receiver); + // The regenerated bindings map the unchanged sender columns into the new argument order. + assert_eq!(suite.publish("sender", &suite.sender), suite.sender); + + suite.send_detailed_ping("after-update"); +} diff --git a/crates/smoketests/tests/standalone/cli/generate.rs b/crates/smoketests/tests/standalone/cli/generate.rs index 39d3c5a95a8..911da839030 100644 --- a/crates/smoketests/tests/standalone/cli/generate.rs +++ b/crates/smoketests/tests/standalone/cli/generate.rs @@ -1,6 +1,6 @@ use predicates::prelude::*; use spacetimedb_guard::ensure_binaries_built; -use spacetimedb_smoketests::patch_module_cargo_to_local_bindings; +use spacetimedb_smoketests::{copy_module_fixture, patch_module_cargo_to_local_bindings}; use std::process::Command; fn cli_cmd() -> Command { @@ -90,3 +90,138 @@ fn cli_generate_with_config_but_no_match_uses_cli_args() { "Generated files should exist in CLI-specified output directory" ); } + +/// Standalone-only: receiver/module bindings are generated from a local Rust module without contacting a server. +#[test] +fn cli_generate_rust_module_bindings() { + let temp_dir = tempfile::tempdir().expect("failed to create temp dir"); + + let output = cli_cmd() + .args([ + "init", + "--non-interactive", + "--lang", + "rust", + "--project-path", + temp_dir.path().to_str().unwrap(), + "test-project", + ]) + .current_dir(temp_dir.path()) + .output() + .expect("failed to execute"); + assert!( + output.status.success(), + "init failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let module_dir = temp_dir.path().join("spacetimedb"); + patch_module_cargo_to_local_bindings(&module_dir).expect("failed to patch module Cargo.toml"); + + let output = cli_cmd() + .args(["build", "--module-path", module_dir.to_str().unwrap()]) + .output() + .expect("failed to execute"); + assert!( + output.status.success(), + "build failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let output_dir = module_dir.join("receiver-bindings"); + let output = cli_cmd() + .args([ + "generate", + "--lang", + "rust", + "--bindings", + "module", + "--out-dir", + output_dir.to_str().unwrap(), + "--module-path", + module_dir.to_str().unwrap(), + ]) + .current_dir(&module_dir) + .output() + .expect("failed to execute"); + assert!( + output.status.success(), + "generate failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let root = std::fs::read_to_string(output_dir.join("lib.rs")).expect("generated lib.rs should exist"); + assert!(root.contains("pub struct Identity(pub spacetimedb::Identity);")); + assert!(root.contains("impl spacetimedb::rt::RemoteReducer for add")); + assert!(root.contains("const NAME: &'static str = \"add\";")); + assert!(!root.contains("DbConnection")); + assert!(!output_dir.join("add_reducer.rs").exists()); +} + +/// Standalone-only: a sender module can use generated receiver bindings from a spacetime.json dependency. +#[test] +fn cli_generate_receiver_bindings_from_dependency_compile_in_sender() { + let temp_dir = tempfile::tempdir().expect("failed to create temp dir"); + let receiver_dir = temp_dir.path().join("receiver"); + let sender_dir = temp_dir.path().join("sender"); + + copy_module_fixture("idc-receiver", &receiver_dir).expect("failed to copy receiver fixture"); + copy_module_fixture("idc-sender", &sender_dir).expect("failed to copy sender fixture"); + patch_module_cargo_to_local_bindings(&receiver_dir).expect("failed to patch receiver Cargo.toml"); + patch_module_cargo_to_local_bindings(&sender_dir).expect("failed to patch sender Cargo.toml"); + + std::fs::write( + temp_dir.path().join("spacetime.json"), + r#"{ + "server": "local", + "children": [ + { + "database": "game-world", + "module-path": "./receiver" + }, + { + "database": "lobby", + "module-path": "./sender", + "dependencies": [ + { "name": "game_world", "database": "game-world" } + ] + } + ] +} +"#, + ) + .expect("failed to write spacetime.json"); + + let output = cli_cmd() + .args(["generate", "lobby"]) + .current_dir(temp_dir.path()) + .output() + .expect("failed to execute"); + assert!( + output.status.success(), + "generate failed:\nstdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + + let remote_bindings_mod = std::fs::read_to_string(sender_dir.join("src/remote_bindings/mod.rs")) + .expect("generated remote_bindings mod.rs should exist"); + assert!(remote_bindings_mod.contains("pub mod game_world;")); + + let generated = sender_dir.join("src/remote_bindings/game_world/mod.rs"); + let root = std::fs::read_to_string(&generated).expect("generated receiver binding should exist"); + assert!(root.contains("pub struct Identity(pub spacetimedb::Identity);")); + assert!(root.contains("impl spacetimedb::rt::RemoteReducer for receive_ping")); + assert!(root.contains("receive_ping")); + + let output = cli_cmd() + .args(["build", "--module-path", sender_dir.to_str().unwrap()]) + .output() + .expect("failed to execute"); + assert!( + output.status.success(), + "sender build failed:\nstdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} diff --git a/crates/testing/tests/idc_actor.rs b/crates/testing/tests/idc_actor.rs index f48860cb336..f96f2abbf34 100644 --- a/crates/testing/tests/idc_actor.rs +++ b/crates/testing/tests/idc_actor.rs @@ -255,9 +255,7 @@ fn outbox_schema(name: &str) -> TableSchema { &AlgebraicType::unit(), &AlgebraicType::String, &spacetimedb_sats::Typespace::default(), - ) - .to_hex() - .to_string(), + ), }), ) }