diff --git a/Cargo.lock b/Cargo.lock index 63438460d..be447be88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1445,6 +1445,7 @@ dependencies = [ "proc-macro2", "quote", "serde", + "serde_json", "sha2 0.10.9", "syn 2.0.119", "trybuild", diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index 28e9e89da..cdfc55745 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -703,10 +703,6 @@ fn human_and_json_diagnostics_preserve_same_facts_and_redact_values() { .to_json() .expect("diagnostic JSON") .contains("postgres://")); - assert_eq!( - result.canonical_bytes().expect("canonical result"), - result.canonical_bytes().expect("second canonical result") - ); let decoded: ContractDiagnostic = serde_json::from_value(serde_json::json!({ "code": "CTL-SCHEMA-DRIFT", @@ -1251,7 +1247,7 @@ fn write_json_value(path: &Path, value: &Value) { } #[test] -fn migration_inventory_is_deterministic_and_preserves_runtime_order() { +fn migration_inventory_preserves_runtime_order() { let inventory = MigrationInventory::from_repository_root(repository_root()) .expect("repository migration inventory"); let versions = inventory @@ -1263,12 +1259,6 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] ); - assert_eq!( - inventory.canonical_bytes().expect("canonical inventory"), - inventory - .canonical_bytes() - .expect("second canonical inventory") - ); } #[test] diff --git a/distributed_cli/src/contracts/transaction.rs b/distributed_cli/src/contracts/transaction.rs index 06eab121e..fa9e63d87 100644 --- a/distributed_cli/src/contracts/transaction.rs +++ b/distributed_cli/src/contracts/transaction.rs @@ -300,15 +300,4 @@ mod tests { assert!(contracts_accept(&root, ContractAcceptScope::Catalog, &bad).is_err()); let _ = fs::remove_dir_all(root); } - - #[test] - fn check_report_is_no_write() { - // Empty catalog check shape only — catalog construction is covered elsewhere. - let report = ContractsCheckReport { - ok: true, - result: ContractCheckResult::default(), - human: String::new(), - }; - assert!(report.ok); - } } diff --git a/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.stderr b/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.stderr deleted file mode 100644 index f6f73a505..000000000 --- a/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.stderr +++ /dev/null @@ -1,29 +0,0 @@ -error[E0277]: `Opaque` has no game payload encoding - --> tests/compile_fail/game_pure_unsupported_output.rs:7:14 - | -7 | fn make() -> Opaque { - | ^^^^^^ unsupported payload field type - | -help: the trait `Wire` is not implemented for `Opaque` - --> tests/compile_fail/game_pure_unsupported_output.rs:3:1 - | -3 | struct Opaque; - | ^^^^^^^^^^^^^ - = note: supported: bool, u8, i8, u16, i16, u32, i32, u64, f32, f64, String, Vec, Option and `#[derive(GameRecord)]` structs - = help: the following other types implement trait `Wire`: - bool - f32 - f64 - i16 - i32 - i8 - u16 - u32 - and $N others -note: required by a bound in `distributed_game::GamePure::Output` - --> $WORKSPACE/distributed_game/src/pure.rs - | - | pub trait GamePure { -... - | type Output: Wire; - | ^^^^ required by this bound in `GamePure::Output` diff --git a/distributed_game_macros/tests/compile_fail/input_buttons_on_float.stderr b/distributed_game_macros/tests/compile_fail/input_buttons_on_float.stderr deleted file mode 100644 index 5ecf53ade..000000000 --- a/distributed_game_macros/tests/compile_fail/input_buttons_on_float.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error[E0277]: `#[buttons]` needs a u8, u16 or u32 field, not `f32` - --> tests/compile_fail/input_buttons_on_float.rs:6:14 - | -6 | buttons: f32, - | ---------^^^ - | | | - | | button bits live in an unsigned integer - | `f32` doesn't satisfy the trait bound - | - = help: the trait `ButtonBits` is not implemented for `f32` -help: the following other types implement trait `ButtonBits` - --> $WORKSPACE/distributed_game/src/codec.rs - | - | impl ButtonBits for $ty { - | ^^^^^^^^^^^^^^^^^^^^^^^ - | | - | `u16` - | `u32` - | `u8` -... - | button_bits!(u8, u16, u32); - | -------------------------- in this macro invocation - = note: this error originates in the macro `button_bits` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/distributed_game_macros/tests/compile_fail/input_unsupported_field.stderr b/distributed_game_macros/tests/compile_fail/input_unsupported_field.stderr deleted file mode 100644 index 38d6993b4..000000000 --- a/distributed_game_macros/tests/compile_fail/input_unsupported_field.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error[E0277]: `String` cannot be a game input field - --> tests/compile_fail/input_unsupported_field.rs:5:11 - | -5 | text: String, - | ------^^^^^^ - | | | - | | unsupported input field type - | `String` doesn't satisfy the trait bound - | - = help: the trait `InputField` is not implemented for `String` - = note: inputs are small fixed scalars: bool, u8, i8, u16, i16, u32, i32 or f32 (optionally #[quant]/#[angle]) - = help: the following other types implement trait `InputField`: - bool - f32 - i16 - i32 - i8 - u16 - u32 - u8 diff --git a/distributed_game_macros/tests/compile_fail/predict_returns_state.stderr b/distributed_game_macros/tests/compile_fail/predict_returns_state.stderr deleted file mode 100644 index 5ffaac908..000000000 --- a/distributed_game_macros/tests/compile_fail/predict_returns_state.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0308]: mismatched types - --> tests/compile_fail/predict_returns_state.rs:14:4 - | -14 | fn step(state: &State, _input: &Push, _context: &(), _dt: f32) -> f32 { - | ^^^^^^^^^^^^^-----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | | - | | expected `State` because of return type - | expected `State`, found `f32` - | -help: try wrapping the expression in `State` - | -14 | fn State { x: step(state: &State, _input: &Push, _context: &(), _dt: f32) -> f32 } { - | ++++++++++ + diff --git a/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.stderr b/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.stderr deleted file mode 100644 index 025cf5611..000000000 --- a/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.stderr +++ /dev/null @@ -1,12 +0,0 @@ -error[E0277]: `#[quant]` / `#[angle]` need an `f32` field, not `u8` - --> tests/compile_fail/replicated_quant_on_integer.rs:7:8 - | -7 | x: u8, - | ^^ quantize an f32 - | - = help: the trait `QuantizedF32` is not implemented for `u8` -help: the trait `QuantizedF32` is implemented for `f32` - --> $WORKSPACE/distributed_game/src/codec.rs - | - | impl QuantizedF32 for f32 { - | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.stderr b/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.stderr deleted file mode 100644 index d44fa8440..000000000 --- a/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.stderr +++ /dev/null @@ -1,14 +0,0 @@ -error[E0277]: `i8` cannot be a replicated entity field - --> tests/compile_fail/replicated_unsupported_type.rs:8:13 - | -8 | charge: i8, - | ^^ unsupported entity field type - | - = help: the trait `EntityField` is not implemented for `i8` - = note: supported: bool, u8, u16, u32, i32, f32 (optionally #[quant]/#[angle]), String (short_str) and Vec (bytes) - = help: the following other types implement trait `EntityField`: - f32 - i32 - u16 - u32 - u8 diff --git a/distributed_game_macros/tests/rustc_fail.rs b/distributed_game_macros/tests/rustc_fail.rs new file mode 100644 index 000000000..9b2fd816d --- /dev/null +++ b/distributed_game_macros/tests/rustc_fail.rs @@ -0,0 +1,43 @@ +//! Compile failures reported through a trait bound (`#[diagnostic::on_unimplemented]` +//! text or a type mismatch) rather than the macro's own error. Each must fail +//! and name its cause; rustc's notes around it are not pinned. See +//! `tests/support/rustc_fail.rs` at the workspace root. + +#[path = "../../tests/support/rustc_fail.rs"] +mod rustc_fail; + +#[test] +fn rustc_rejects_generated_code_for_the_named_cause() { + rustc_fail::assert_fail_with( + env!("CARGO_MANIFEST_DIR"), + "tests/rustc_fail", + r#"distributed_game = { path = "{workspace}/distributed_game" } +serde = { version = "1", features = ["derive"] }"#, + &[ + ( + "game_pure_unsupported_output", + &["`Opaque` has no game payload encoding"], + ), + ( + "input_buttons_on_float", + &["`#[buttons]` needs a u8, u16 or u32 field, not `f32`"], + ), + ( + "input_unsupported_field", + &["`String` cannot be a game input field"], + ), + ( + "replicated_unsupported_type", + &["`i8` cannot be a replicated entity field"], + ), + ( + "replicated_quant_on_integer", + &["`#[quant]` / `#[angle]` need an `f32` field, not `u8`"], + ), + ( + "predict_returns_state", + &["E0308", "expected `State`, found `f32`"], + ), + ], + ); +} diff --git a/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.rs b/distributed_game_macros/tests/rustc_fail/game_pure_unsupported_output.rs similarity index 100% rename from distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.rs rename to distributed_game_macros/tests/rustc_fail/game_pure_unsupported_output.rs diff --git a/distributed_game_macros/tests/compile_fail/input_buttons_on_float.rs b/distributed_game_macros/tests/rustc_fail/input_buttons_on_float.rs similarity index 100% rename from distributed_game_macros/tests/compile_fail/input_buttons_on_float.rs rename to distributed_game_macros/tests/rustc_fail/input_buttons_on_float.rs diff --git a/distributed_game_macros/tests/compile_fail/input_unsupported_field.rs b/distributed_game_macros/tests/rustc_fail/input_unsupported_field.rs similarity index 100% rename from distributed_game_macros/tests/compile_fail/input_unsupported_field.rs rename to distributed_game_macros/tests/rustc_fail/input_unsupported_field.rs diff --git a/distributed_game_macros/tests/compile_fail/predict_returns_state.rs b/distributed_game_macros/tests/rustc_fail/predict_returns_state.rs similarity index 100% rename from distributed_game_macros/tests/compile_fail/predict_returns_state.rs rename to distributed_game_macros/tests/rustc_fail/predict_returns_state.rs diff --git a/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.rs b/distributed_game_macros/tests/rustc_fail/replicated_quant_on_integer.rs similarity index 100% rename from distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.rs rename to distributed_game_macros/tests/rustc_fail/replicated_quant_on_integer.rs diff --git a/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.rs b/distributed_game_macros/tests/rustc_fail/replicated_unsupported_type.rs similarity index 100% rename from distributed_game_macros/tests/compile_fail/replicated_unsupported_type.rs rename to distributed_game_macros/tests/rustc_fail/replicated_unsupported_type.rs diff --git a/distributed_macros/Cargo.toml b/distributed_macros/Cargo.toml index acdc671dc..165b21a75 100644 --- a/distributed_macros/Cargo.toml +++ b/distributed_macros/Cargo.toml @@ -24,3 +24,5 @@ trybuild = "=1.0.121" # Cargo permits dev-dependency cycles. distributed = { path = ".." } serde = { version = "1.0", features = ["derive"] } +# Reads `cargo check --message-format=json` in tests/rustc_fail.rs. +serde_json = "1" diff --git a/distributed_macros/src/entry_tests.rs b/distributed_macros/src/entry_tests.rs index 41606d834..442d3a55b 100644 --- a/distributed_macros/src/entry_tests.rs +++ b/distributed_macros/src/entry_tests.rs @@ -80,336 +80,25 @@ mod tests { } #[test] - fn expand_sourced_generates_enum_and_aggregate() { - let attr = quote! { entity }; - let item = quote! { - impl Todo { - #[event("initialized")] - pub fn initialize(&mut self, id: String) { - self.id = id; - } - } - }; - let out = sourced::expand_sourced(attr, item).unwrap().to_string(); - assert!(out.contains("enum TodoEvent"), "got: {out}"); - assert!( - out.contains("impl :: distributed :: Aggregate for Todo"), - "got: {out}" - ); - } - - #[test] - fn expand_sourced_places_state_capture_after_transition_body() { - let attr = quote! { - entity, - aggregate_type = "todo", - domain_state = TodoState, - }; - let item = quote! { - impl Todo { - #[event("todo.completed", version = 1, domain)] - pub fn complete(&mut self) { - self.completed = true; - } - } - }; - - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - let digest = output.find("digest_v").unwrap(); - let transition = output.find("self . completed = true").unwrap(); - let capture = output.find("capture_domain_state").unwrap(); - - assert!(digest < transition); - assert!(transition < capture); - assert!(output.contains("is_replaying")); - assert!(output.contains("pub enum TodoCompletedDomainEvent")); - assert!(output.contains( - "impl :: distributed :: domain_event :: DomainEventContract for TodoCompletedDomainEvent" - )); - assert!(output.contains("DomainEventBodyContract < TodoState >")); - } - - #[test] - fn known_values_are_declared_not_read_from_the_recorder_body() { - let attr = quote! { - entity, - aggregate_type = "todo", - domain_state = TodoState, - }; - let expand = |event: proc_macro2::TokenStream| { - sourced::expand_sourced( - attr.clone(), - quote! { - impl Todo { - pub fn complete(&mut self) { - self.record_completed().unwrap(); - } - - #event - fn record_completed(&mut self) { - self.status = TodoStatus::Completed; - self.assignee_id = None; - } - } - }, - ) - }; - - let undeclared = expand(quote!(#[event("todo.completed", version = 1, domain)])) - .unwrap() - .to_string(); - assert!( - !undeclared.contains("fn command_event_known_values"), - "assignments in the body predict nothing: {undeclared}" - ); - - let declared = expand(quote!( - #[event("todo.completed", version = 1, domain, known(status: "completed", assignee_id: null))] - )) - .unwrap() - .to_string(); - assert!( - declared.contains("fn command_event_known_values"), - "got: {declared}" - ); - assert!( - declared.contains("state_preview ! { TodoCompletedDomainEvent => TodoState { status : \"completed\" , assignee_id : null , } }"), - "got: {declared}" - ); - - let event_mode = expand(quote!( - #[event("todo.completed", version = 1, domain = event, known(status: "completed"))] - )) - .unwrap() - .to_string(); - assert!( - event_mode.contains("event_preview ! { TodoCompletedDomainEvent => TodoCompletedDomainEvent { status : \"completed\" , } }"), - "an event-mode recorder declares constants of its own body: {event_mode}" - ); - - let error = expand(quote!( - #[event("todo.completed", version = 1, known(status: "completed"))] - )) - .unwrap_err() - .to_string(); - assert!(error.contains("needs one of those"), "{error}"); - } - - #[test] - fn sourced_helpers_ignore_other_receivers_and_nested_item_self() { - let output = sourced::expand_sourced( - quote! { entity, aggregate_type = "todo" }, + fn known_values_need_a_domain_mode() { + let error = sourced::expand_sourced( + quote! { entity, aggregate_type = "todo", domain_state = TodoState }, quote! { impl Todo { - pub fn unrelated(&mut self, other: &mut Todo) { - other.record_completed().unwrap(); - struct Other; - impl Other { - fn action(&mut self) { self.record_completed(); } - } + pub fn complete(&mut self) { + self.record_completed().unwrap(); + } + + #[event("todo.completed", version = 1, known(status: "completed"))] + fn record_completed(&mut self) { + self.status = TodoStatus::Completed; } - #[event("todo.completed", domain = event)] - fn record_completed(&mut self) {} } }, ) - .unwrap() + .unwrap_err() .to_string(); - assert!(!output.contains("pub enum Unrelated"), "{output}"); - assert!(!output.contains("pub mod domain_commands"), "{output}"); - } - - #[test] - fn sourced_helper_custom_body_uses_declared_type_contract() { - for output_type in [ - quote!(crate::facts::BranchCreated), - quote!(super::facts::BranchCreated), - quote!(BranchCreated), - ] { - let output = sourced::expand_sourced( - quote! { entity, aggregate_type = "repository" }, - quote! { - impl Repository { - pub fn create(&mut self) { self.create_refs().unwrap(); } - fn create_refs(&mut self) { self.record_branch().unwrap(); } - #[event( - "repository.branch_created", - domain = with(#output_type, branch_created) - )] - fn record_branch(&mut self) {} - } - }, - ) - .unwrap() - .to_string(); - let descriptor = quote! { - distributed::command::__command_projection_event_descriptor::<#output_type,>() - } - .to_string(); - assert!(output.contains(&descriptor), "{output}"); - assert!(output.contains("for domain_commands :: Create"), "{output}"); - assert!( - !output.contains("RepositoryBranchCreatedDomainEvent"), - "{output}" - ); - } - } - - #[test] - fn expand_sourced_identity_mode_generates_independent_public_descriptor() { - let attr = quote! { - entity, - aggregate_type = "todo", - }; - let item = quote! { - impl Todo { - #[event("todo.renamed", version = 2, domain = event)] - pub fn rename(&mut self, title: String) { - self.title = title; - } - } - }; - - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - - assert!(output.contains("pub struct TodoRenamedDomainEvent")); - assert!(output.contains( - "impl :: distributed :: domain_event :: DomainEventContract for TodoRenamedDomainEvent" - )); - assert!(output.contains("DomainEventBodyDescriptor :: distributed_json")); - assert!(output.contains("capture_domain_event")); - assert!(!output.contains("payload_bytes")); - } - - #[test] - fn expand_sourced_deletion_uses_aggregate_sequence_as_incarnation() { - let attr = quote! { - entity, - aggregate_type = "todo", - }; - let item = quote! { - impl Todo { - #[event("todo.purged", domain = deleted)] - pub fn purge(&mut self) { - self.purged = true; - } - } - }; - - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - - assert!(output.contains("pub struct TodoDomainIdentity")); - assert!(output.contains("pub enum TodoPurgedDomainEvent")); - assert!(output.contains("DomainEventBodyContract < :: distributed :: DomainDeletion")); - assert!(output.contains("self . entity . version ()")); - assert!(output.contains("capture_domain_deletion")); - assert!(!output.contains("capture_domain_state")); - } - - #[test] - fn expand_sourced_custom_mode_type_checks_a_pure_function_pointer() { - let attr = quote! { - entity, - events = "TodoReplayEvent", - aggregate_type = "todo", - }; - let item = quote! { - impl Todo { - #[event( - "todo.completed", - domain = with(TodoCompleted, TodoCompleted::capture_after) - )] - pub fn complete(&mut self) { - self.completed = true; - } - } - }; - - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - - assert!(output.contains( - "fn (& Todo , & TodoReplayEvent) -> TodoCompleted = TodoCompleted :: capture_after" - )); - assert!(output.contains("if let Some")); - assert!(output.contains("capture_domain_event")); - assert!(output.contains("DomainEventContract > :: EVENT_NAME")); - assert!(output.contains("DomainEventContract > :: EVENT_VERSION")); - assert!(output.contains("DomainEventBodyContract < T >")); - assert!( - output.contains("!= < TodoCompleted as :: distributed :: DomainEvent > :: DESCRIPTOR") - ); - } - - #[test] - fn expand_sourced_rejects_duplicate_event_names() { - let attr = quote! { entity }; - let item = quote! { - impl Todo { - #[event("done")] - pub fn complete(&mut self) {} - #[event("done")] - pub fn finish(&mut self) {} - } - }; - let err = sourced::expand_sourced(attr, item).expect_err("duplicate should error"); - assert!( - err.to_string().contains("duplicate #[event] name `done`"), - "got: {err}" - ); - } - - #[test] - fn expand_sourced_rejects_variant_ident_collisions() { - let attr = quote! { entity }; - let item = quote! { - impl Workflow { - #[event("user.completed")] - pub fn user_completed(&mut self) {} - #[event("admin.completed")] - pub fn admin_completed(&mut self) {} - } - }; - let err = sourced::expand_sourced(attr, item).expect_err("variant collision should error"); - let msg = err.to_string(); - assert!(msg.contains("`user.completed`"), "got: {msg}"); - assert!(msg.contains("`admin.completed`"), "got: {msg}"); - assert!(msg.contains("`Completed`"), "got: {msg}"); - } - - #[test] - fn expand_sourced_rejects_tuple_parameter_pattern() { - let attr = quote! { entity }; - let item = quote! { - impl Point { - #[event("moved")] - pub fn moved(&mut self, (x, y): (u8, u8)) { - self.x = x; - self.y = y; - } - } - }; - let err = sourced::expand_sourced(attr, item).expect_err("tuple pattern should error"); - assert!( - err.to_string() - .contains("unsupported parameter pattern in #[event] method"), - "got: {err}" - ); - } - - #[test] - fn expand_sourced_rejects_event_without_receiver() { - let attr = quote! { entity }; - let item = quote! { - impl Todo { - #[event("initialized")] - pub fn initialize(id: String) {} - } - }; - let err = sourced::expand_sourced(attr, item).expect_err("missing receiver should error"); - assert!( - err.to_string().contains("must take a `&mut self` receiver"), - "got: {err}" - ); + assert!(error.contains("needs one of those"), "{error}"); } // ---- upcasters ------------------------------------------------------- @@ -443,83 +132,6 @@ mod tests { // ---- aggregate ------------------------------------------------------- - #[test] - fn expand_command_emits_thin_mount() { - let input = quote! { - name: "todo.complete", - transition: domain_commands::Complete, - aggregate: Todo, - input: TodoCompleteInput, - outcome: Eventual, - shard: |input| input.todo_id.clone(), - load: required, - roles: ["user", "admin"], - field: "todos_complete", - invoke: |todo, _input, principal| todo.complete(principal), - payload: |todo, _principal| TodoStatusPayload::from_todo(&**todo), - }; - let out = crate::command::expand(input).expect("expand").to_string(); - assert!(out.contains("struct Complete"), "{out}"); - assert!(out.contains("fn complete"), "{out}"); - assert!(out.contains("todo . complete"), "{out}"); - assert!(out.contains("load_by"), "{out}"); - assert!(out.contains("eventual"), "{out}"); - assert!(out.contains("PortableCommand"), "{out}"); - } - - #[test] - fn expand_command_preserves_contract_projection_options() { - let input = quote! { - name: "chat.post", - transition: domain_commands::Post, - aggregate: ChatMessage, - input: ChatPostInput, - outcome: Eventual, - shard: |input| input.message_id.clone(), - roles: ["user", "admin"], - field: "chat_messages_post", - constructor: post_message, - authenticated_user_field: ( - ChatMessagePostedDomainEvent, - ChatMessageState, - "author_id" - ), - preview_reduce_known_record: blob_preview(), - guard: authenticated_user, - handle: handle_post, - }; - let out = crate::command::expand(input).expect("expand").to_string(); - assert!(out.contains("authenticated_user_field"), "{out}"); - assert!(out.contains("fn post_message"), "{out}"); - assert!(out.contains("ChatMessagePostedDomainEvent"), "{out}"); - assert!(out.contains("ChatMessageState"), "{out}"); - assert!(out.contains("author_id"), "{out}"); - assert!(out.contains("preview_reduce_known_record"), "{out}"); - assert!(out.contains("blob_preview"), "{out}"); - assert!(out.contains("declared_in_rust_package"), "{out}"); - assert!(out.contains("CARGO_PKG_NAME"), "{out}"); - } - - #[test] - fn expand_command_allows_constructor_override_for_keyword_name() { - let input = quote! { - name: "blob.move", - transition: domain_commands::MoveDir, - aggregate: BlobGame, - input: BlobMoveInput, - outcome: Atomic, - shard: |input| input.game_id.clone(), - roles: ["user", "admin"], - field: "blob_games_move", - constructor: move_dir, - guard: authenticated_user, - handle: handle_move, - }; - let out = crate::command::expand(input).expect("expand").to_string(); - assert!(out.contains("struct Move"), "{out}"); - assert!(out.contains("fn move_dir"), "{out}"); - } - fn thin_command( name: &str, load: proc_macro2::TokenStream, @@ -542,19 +154,6 @@ mod tests { .map(|tokens| tokens.to_string()) } - #[test] - fn expand_command_thin_form_takes_every_load_and_a_guard() { - for (load, method) in [ - (quote!(required), "load_by"), - (quote!(or_create), "load_or_create_by"), - (quote!(create), "create_by"), - ] { - let out = thin_command("todo.create", load, quote!(["user"])).expect("expand"); - assert!(out.contains(&format!(". {method} (")), "{method}: {out}"); - assert!(out.contains(". guard (authenticated_user)"), "{out}"); - } - } - /// The method form and `command!` reject the same names and roles. #[test] fn expand_command_shares_name_and_role_rules_with_the_method_form() { diff --git a/distributed_macros/src/read_model/tests.rs b/distributed_macros/src/read_model/tests.rs index 27b20983b..41dc84cab 100644 --- a/distributed_macros/src/read_model/tests.rs +++ b/distributed_macros/src/read_model/tests.rs @@ -3,21 +3,7 @@ use super::*; use syn::DeriveInput; #[test] -fn direct_relationship_references_are_order_independent_and_emitted() { - for attributes in [ - "references = \"namespace,oid\", belongs_to = \"Object\", foreign_key = \"scope,oid\"", - "belongs_to = \"Object\", foreign_key = \"scope,oid\", references = \"namespace,oid\"", - ] { - let input = syn::parse_str(&format!( - "struct Ref {{ id: String, #[readmodel({attributes})] object: Option }}" - )) - .unwrap(); - let expanded = expand_read_model(input).unwrap().to_string(); - assert!( - expanded.contains("references : Some (\"namespace,oid\""), - "{expanded}" - ); - } +fn direct_relationship_references_need_one_belongs_to() { for attributes in [ "references = \"id\"", "belongs_to = \"Object\", foreign_key = \"id\", references = \"id\", references = \"id\"", @@ -32,19 +18,7 @@ fn direct_relationship_references_are_order_independent_and_emitted() { } #[test] -fn boxed_belongs_to_preserves_target_markers_and_checks_inner_type() { - let input: DeriveInput = syn::parse_quote! { - struct Parent { - id: String, - #[readmodel(belongs_to = "Child", foreign_key = "id")] - child: Option>, - } - }; - let expanded = expand_read_model(input).unwrap().to_string(); - assert!(expanded.contains("type Target = Child"), "{expanded}"); - assert!(!expanded.contains("type Target = std :: boxed :: Box")); - assert!(expanded.contains("Box :: new")); - assert!(expanded.contains("value . as_ref ()")); +fn boxed_belongs_to_rejects_anything_but_one_box_of_the_target() { for ty in [ "Option>", "Option>>", @@ -59,191 +33,6 @@ fn boxed_belongs_to_preserves_target_markers_and_checks_inner_type() { } } -#[test] -fn expand_read_model_accepts_named_id_field() { - let input: DeriveInput = syn::parse_quote! { - struct CounterView { - id: String, - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("impl :: distributed :: ReadModel for CounterView")); - assert!(expanded.contains("fn id")); -} - -#[test] -fn expand_read_model_accepts_explicit_id_attribute() { - let input: DeriveInput = syn::parse_quote! { - struct CounterView { - id: String, - #[readmodel(id)] - counter_id: String, - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("& self . counter_id")); - assert!(!expanded.contains("& self . id")); -} - -#[test] -fn expand_read_model_accepts_declared_name() { - let input: DeriveInput = syn::parse_quote! { - #[readmodel(name = "operational.todos", table = "operational_todos")] - struct OperationalTodos { - #[readmodel(id)] - todo_id: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - assert!( - expanded.contains("operational.todos") || expanded.contains("operational . todos"), - "{expanded}" - ); - assert!(!expanded.contains("model_name : \"OperationalTodos\"")); - assert!( - expanded.contains("operational_todos"), - "default table must come from the Rust type, not the declared name: {expanded}" - ); -} - -#[test] -fn expand_read_model_accepts_direct_collection_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[collection("counter_views")] - struct CounterView { - #[id] - counter_id: String, - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("const COLLECTION : & 'static str = \"counter_views\"")); - assert!(expanded.contains("& self . counter_id")); -} - -#[test] -fn expand_read_model_accepts_direct_table_and_id_column_attributes() { - let input: DeriveInput = syn::parse_quote! { - #[table = "counter_views"] - struct CounterView { - #[id("counter_id")] - id: String, - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("table_name : \"counter_views\"")); - assert!(expanded.contains("column_name : \"counter_id\"")); -} - -#[test] -fn expand_read_model_accepts_direct_column_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("counter_views")] - struct CounterView { - #[id] - id: String, - #[column("counter_value")] - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("column_name : \"counter_value\"")); -} - -#[test] -fn expand_read_model_accepts_direct_index_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("counter_views")] - struct CounterView { - #[id] - id: String, - #[index("idx_counter_views_value")] - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("name : Some (\"idx_counter_views_value\"")); - assert!(expanded.contains("columns : vec ! [\"value\"")); - assert!(expanded.contains("unique : false")); -} - -#[test] -fn expand_read_model_accepts_direct_unique_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("counter_views")] - struct CounterView { - #[id] - id: String, - #[unique("uq_counter_views_slug")] - slug: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("name : Some (\"uq_counter_views_slug\"")); - assert!(expanded.contains("columns : vec ! [\"slug\"")); - assert!(expanded.contains("unique : true")); -} - -#[test] -fn expand_read_model_accepts_struct_compound_index_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("account_summaries")] - #[index(name = "idx_account_summaries_owner_created", columns = ["owner", "created_at"])] - struct AccountSummary { - #[id("account_id")] - id: String, - owner: String, - #[column("created_at_utc")] - created_at: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("name : Some (\"idx_account_summaries_owner_created\"")); - assert!(expanded.contains("columns : vec ! [\"owner\" . to_string () , \"created_at_utc\"")); - assert!(expanded.contains("unique : false")); -} - -#[test] -fn expand_read_model_accepts_struct_compound_unique_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("accounts")] - #[unique(columns = ["tenant_id", "slug"])] - struct AccountSummary { - #[id("account_id")] - id: String, - tenant_id: String, - slug: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("name : Some (\"uq_accounts_tenant_id_slug\"")); - assert!(expanded.contains("columns : vec ! [\"tenant_id\"")); - assert!(expanded.contains("\"slug\"")); - assert!(expanded.contains("unique : true")); -} - #[test] fn expand_read_model_rejects_struct_index_without_columns() { let input: DeriveInput = syn::parse_quote! { @@ -299,23 +88,6 @@ fn expand_read_model_rejects_missing_id_field_for_document_models() { ); } -#[test] -fn expand_read_model_allows_composite_relational_models_without_string_id() { - let input: DeriveInput = syn::parse_quote! { - #[readmodel(table = "player_weapons", primary_key = ["player_id", "weapon_id"])] - struct PlayerWeapon { - #[readmodel(foreign_key = "players.player_id", delegated_from = "Player.player_id")] - player_id: String, - weapon_id: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("impl :: distributed :: RelationalReadModel for PlayerWeapon")); - assert!(!expanded.contains("impl :: distributed :: ReadModel for PlayerWeapon")); -} - #[test] fn expand_read_model_rejects_multiple_explicit_id_attributes() { let input: DeriveInput = syn::parse_quote! { @@ -375,43 +147,6 @@ fn expand_read_model_rejects_unknown_field_attributes() { ); } -#[test] -fn expand_read_model_accepts_relationship_metadata_before_relationship_kind() { - let input: DeriveInput = syn::parse_quote! { - #[readmodel(table = "players")] - struct Player { - #[readmodel(id, column = "player_id")] - id: String, - #[readmodel(foreign_key = "player_id", has_many = "PlayerWeapon")] - weapons: Vec, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("RelationshipKind :: HasMany")); - assert!(expanded.contains("foreign_key : Some (\"player_id\"")); -} - -#[test] -fn expand_read_model_accepts_through_before_many_to_many() { - let input: DeriveInput = syn::parse_quote! { - #[readmodel(table = "players")] - struct Player { - #[readmodel(id, column = "player_id")] - id: String, - #[readmodel(through = "player_weapon_links", foreign_key = "player_id", many_to_many = "Weapon")] - weapons: Vec, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("RelationshipKind :: ManyToMany")); - assert!(expanded.contains("through : Some (\"player_weapon_links\"")); - assert!(expanded.contains("foreign_key : Some (\"player_id\"")); -} - #[test] fn expand_read_model_rejects_tuple_structs() { let input: DeriveInput = syn::parse_quote! { @@ -524,22 +259,3 @@ fn default_storage_name_treats_ambiguous_terminal_s_as_plural() { assert_eq!(actual, expected); } - -#[test] -fn expand_read_model_shares_natural_default_between_document_and_relational_metadata() { - let input: DeriveInput = syn::parse_quote! { - struct BlobGames { - #[id] - game_id: String, - #[index] - owner_id: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!( - expanded.contains("const COLLECTION : & 'static str = \"blob_games\"") - && expanded.contains("table_name : \"blob_games\"") - ); -} diff --git a/distributed_macros/src/snapshot.rs b/distributed_macros/src/snapshot.rs index 0fd866b23..a8fed1c6b 100644 --- a/distributed_macros/src/snapshot.rs +++ b/distributed_macros/src/snapshot.rs @@ -286,35 +286,6 @@ fn has_serde_skip(attrs: &[syn::Attribute]) -> bool { mod tests { use super::*; - #[test] - fn expand_snapshot_accepts_named_struct() { - let input: DeriveInput = syn::parse_quote! { - struct Todo { - entity: distributed::Entity, - task: String, - } - }; - - let expanded = expand_snapshot(input).unwrap().to_string(); - - assert!(expanded.contains("pub struct TodoSnapshot")); - assert!(expanded.contains("impl :: distributed :: Snapshottable for Todo")); - } - - #[test] - fn expand_snapshot_rejects_tuple_structs() { - let input: DeriveInput = syn::parse_quote! { - struct Todo(String); - }; - - let err = expand_snapshot(input).expect_err("tuple struct should return an error"); - - assert!( - err.to_string().contains("requires named fields"), - "unexpected error: {err}" - ); - } - #[test] fn expand_snapshot_rejects_enums() { let input: DeriveInput = syn::parse_quote! { @@ -432,42 +403,6 @@ mod tests { ); } - #[test] - fn expand_snapshot_without_version_attr_inherits_default() { - let input: DeriveInput = syn::parse_quote! { - struct Todo { - entity: distributed::Entity, - task: String, - } - }; - - let expanded = expand_snapshot(input).unwrap().to_string(); - - // No explicit const is emitted; the trait default (1) is inherited. - assert!( - !expanded.contains("const SNAPSHOT_VERSION"), - "default case must not emit a SNAPSHOT_VERSION const: {expanded}" - ); - } - - #[test] - fn expand_snapshot_emits_version_const() { - let input: DeriveInput = syn::parse_quote! { - #[snapshot(version = 3)] - struct Todo { - entity: distributed::Entity, - task: String, - } - }; - - let expanded = expand_snapshot(input).unwrap().to_string(); - - assert!( - expanded.contains("const SNAPSHOT_VERSION : u64 = 3"), - "expected emitted version const: {expanded}" - ); - } - #[test] fn expand_snapshot_rejects_zero_version() { let input: DeriveInput = syn::parse_quote! { diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr deleted file mode 100644 index 977aae8f5..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error[E0271]: type mismatch resolving `<__DistributedInputEffectInputField_ids as EffectInputFieldMarker>::Value == String` - --> tests/command_input_defaults_compile_fail/input_default_list.rs:11:23 - | -11 | default input.ids = ulid(); - | ^^^ type mismatch resolving `<__DistributedInputEffectInputField_ids as EffectInputFieldMarker>::Value == String` - | -note: expected this to be `std::string::String` - --> tests/command_input_defaults_compile_fail/input_default_list.rs:5:10 - | - 5 | ids: Vec, - | ^^^^^^^^^^^ - = note: expected struct `String` - found struct `Vec` -note: required by a bound in `distributed::command::__input_default_ulid` - --> $WORKSPACE/src/command/effect_wire.rs - | - | pub fn __input_default_ulid() -> CompiledInputDefault -... - | F: EffectInputFieldMarker, - | ^^^^^^^^^^^^^^ required by this bound in `__input_default_ulid` diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr deleted file mode 100644 index ef540e950..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error[E0271]: type mismatch resolving `<__DistributedInputEffectInputField_id as EffectInputFieldMarker>::Value == String` - --> tests/command_input_defaults_compile_fail/input_default_nullable.rs:12:23 - | -12 | default input.id = uuid_v7(); - | ^^ type mismatch resolving `<__DistributedInputEffectInputField_id as EffectInputFieldMarker>::Value == String` - | -note: expected this to be `std::string::String` - --> tests/command_input_defaults_compile_fail/input_default_nullable.rs:6:9 - | - 6 | id: Option, - | ^^^^^^^^^^^^^^ - = note: expected struct `String` - found enum `std::option::Option` -note: required by a bound in `distributed::command::__input_default_uuid_v7` - --> $WORKSPACE/src/command/effect_wire.rs - | - | pub fn __input_default_uuid_v7() -> CompiledInputDefault -... - | F: EffectInputFieldMarker, - | ^^^^^^^^^^^^^^ required by this bound in `__input_default_uuid_v7` diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr deleted file mode 100644 index 1b3229fab..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr +++ /dev/null @@ -1,18 +0,0 @@ -error[E0271]: type mismatch resolving `<__DistributedInputEffectInputField_count as EffectInputFieldMarker>::Value == String` - --> tests/command_input_defaults_compile_fail/input_default_wrong_type.rs:11:23 - | -11 | default input.count = uuid_v7(); - | ^^^^^ type mismatch resolving `<__DistributedInputEffectInputField_count as EffectInputFieldMarker>::Value == String` - | -note: expected this to be `std::string::String` - --> tests/command_input_defaults_compile_fail/input_default_wrong_type.rs:5:12 - | - 5 | count: i64, - | ^^^ -note: required by a bound in `distributed::command::__input_default_uuid_v7` - --> $WORKSPACE/src/command/effect_wire.rs - | - | pub fn __input_default_uuid_v7() -> CompiledInputDefault -... - | F: EffectInputFieldMarker, - | ^^^^^^^^^^^^^^ required by this bound in `__input_default_uuid_v7` diff --git a/distributed_macros/tests/rustc_fail.rs b/distributed_macros/tests/rustc_fail.rs new file mode 100644 index 000000000..f68ba46ec --- /dev/null +++ b/distributed_macros/tests/rustc_fail.rs @@ -0,0 +1,48 @@ +//! Compile failures whose message is rustc's, not the macro's (a trait bound +//! or a type mismatch in generated code). Each must fail and name its cause; +//! the full rendering is not pinned. See `tests/support/rustc_fail.rs`. + +#[path = "../../tests/support/rustc_fail.rs"] +mod rustc_fail; + +#[test] +fn rustc_rejects_generated_code_for_the_named_cause() { + rustc_fail::assert_fail_with( + env!("CARGO_MANIFEST_DIR"), + "tests/rustc_fail", + r#"distributed = { path = "{workspace}" } +serde = { version = "1", features = ["derive"] }"#, + &[ + // A generated input default only fits a `String` field. + ( + "input_default_list", + &[ + "E0271", + "Value == String", + "InputField_ids as EffectInputFieldMarker", + ], + ), + ( + "input_default_nullable", + &[ + "E0271", + "Value == String", + "InputField_id as EffectInputFieldMarker", + ], + ), + ( + "input_default_wrong_type", + &[ + "E0271", + "Value == String", + "InputField_count as EffectInputFieldMarker", + ], + ), + // Only methods that record on `self` become domain commands. + ( + "sourced_helper_other_receiver", + &["cannot find type `Unrelated` in module `domain_commands`"], + ), + ], + ); +} diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs b/distributed_macros/tests/rustc_fail/input_default_list.rs similarity index 100% rename from distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs rename to distributed_macros/tests/rustc_fail/input_default_list.rs diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs b/distributed_macros/tests/rustc_fail/input_default_nullable.rs similarity index 100% rename from distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs rename to distributed_macros/tests/rustc_fail/input_default_nullable.rs diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs b/distributed_macros/tests/rustc_fail/input_default_wrong_type.rs similarity index 100% rename from distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs rename to distributed_macros/tests/rustc_fail/input_default_wrong_type.rs diff --git a/distributed_macros/tests/rustc_fail/sourced_helper_other_receiver.rs b/distributed_macros/tests/rustc_fail/sourced_helper_other_receiver.rs new file mode 100644 index 000000000..ccf769d36 --- /dev/null +++ b/distributed_macros/tests/rustc_fail/sourced_helper_other_receiver.rs @@ -0,0 +1,40 @@ +use distributed::{sourced, Entity}; + +#[derive(Default)] +pub struct Todo { + entity: Entity, + completed: bool, +} + +#[sourced(entity, aggregate_type = "todo")] +impl Todo { + pub fn complete(&mut self) -> distributed::SourcedResult { + self.record_completed()?; + Ok(()) + } + + // Records on another receiver and through a nested item's `self`: neither + // is this aggregate's transition, so no `domain_commands::Unrelated`. + pub fn unrelated(&mut self, other: &mut Todo) { + other.record_completed().unwrap(); + struct Other; + impl Other { + #[allow(dead_code)] + fn record_completed(&mut self) {} + #[allow(dead_code)] + fn action(&mut self) { + self.record_completed(); + } + } + } + + #[event("todo.completed", domain = event)] + fn record_completed(&mut self) { + self.completed = true; + } +} + +fn main() { + let _: Option = None; + let _: Option = None; +} diff --git a/src/command_ledger/tests.rs b/src/command_ledger/tests.rs index 660220bca..10c56125c 100644 --- a/src/command_ledger/tests.rs +++ b/src/command_ledger/tests.rs @@ -1490,7 +1490,7 @@ fn modeled_projection_metadata_bounds_fail_before_completion() { } #[test] -fn cell_ledger_external_binding_round_trips_and_legacy_rows_stay_unbound() { +fn cell_ledger_external_binding_round_trips() { let id = Uuid::now_v7().to_string(); let request = external_reservation(&id, 141, 142, "orders-cell").unwrap(); let started = SystemTime::UNIX_EPOCH + Duration::from_secs(100); @@ -1500,15 +1500,6 @@ fn cell_ledger_external_binding_round_trips_and_legacy_rows_stay_unbound() { assert_eq!(restored.external_binding, row.external_binding); assert_eq!(restored.durable_cell_key(), row.durable_cell_key()); - // Cell rows written before external dispatch existed omit the optional - // field. They remain readable, but cannot be treated as externally bound - // evidence after a process restart. - let mut legacy: serde_json::Value = serde_json::from_str(&encoded).unwrap(); - legacy.as_object_mut().unwrap().remove("external_binding"); - let legacy = serde_json::to_string(&legacy).unwrap(); - let restored_legacy = CommandLedgerRecord::from_durable_cell_json(&legacy).unwrap(); - assert!(restored_legacy.external_binding.is_none()); - let completed_id = Uuid::now_v7().to_string(); let completed_request = external_reservation(&completed_id, 143, 144, "orders-cell-completed").unwrap(); @@ -2029,7 +2020,7 @@ fn expiry_is_a_permanent_compact_tombstone() { } #[test] -fn durable_success_states_use_only_the_succeeded_vocabulary() { +fn durable_success_states_round_trip_their_storage_names() { let cases = [ (CommandLedgerState::Succeeded, "succeeded"), ( @@ -2043,6 +2034,4 @@ fn durable_success_states_use_only_the_succeeded_vocabulary() { assert_eq!(state.as_str(), encoded); assert_eq!(CommandLedgerState::parse(encoded).unwrap(), state); } - assert!(CommandLedgerState::parse("accepted").is_err()); - assert!(CommandLedgerState::parse("accepted_pending_projection").is_err()); } diff --git a/src/entity/entity.rs b/src/entity/entity.rs index 5bb931214..bbf63eaf3 100644 --- a/src/entity/entity.rs +++ b/src/entity/entity.rs @@ -660,17 +660,6 @@ mod tests { } } - #[test] - fn new() { - let entity = Entity::new(); - assert_eq!(entity.id(), ""); - assert_eq!(entity.version(), 0); - assert!(entity.events().is_empty()); - assert!(!entity.is_replaying()); - assert_eq!(entity.snapshot_version(), 0); - assert_eq!(entity.committed_version(), 0); - } - #[test] fn digest() { let mut entity = Entity::new(); @@ -725,31 +714,6 @@ mod tests { assert!(!entity.is_replaying()); } - #[test] - fn clone() { - let entity = Entity::new(); - let cloned_entity = entity.clone(); - - assert_eq!(entity.id(), cloned_entity.id()); - assert_eq!(entity.version(), cloned_entity.version()); - assert_eq!(entity.events(), cloned_entity.events()); - assert_eq!(entity.snapshot_version(), cloned_entity.snapshot_version()); - assert_eq!( - entity.committed_version(), - cloned_entity.committed_version() - ); - } - - #[test] - fn debug() { - let entity = Entity::new(); - let debug_str = format!("{:?}", entity); - - assert!(debug_str.contains("Entity")); - assert!(debug_str.contains("id: \"\"")); - assert!(debug_str.contains("version: 0")); - } - #[test] fn serialize_deserialize() { let mut entity = Entity::new(); diff --git a/src/entity/event_record.rs b/src/entity/event_record.rs index 8b90fae9a..9a6175a39 100644 --- a/src/entity/event_record.rs +++ b/src/entity/event_record.rs @@ -274,35 +274,6 @@ impl EventRecord { mod tests { use super::*; - #[test] - fn new() { - let payload = bitcode::serialize(&("arg1", "arg2")).unwrap(); - let event_record = EventRecord::new("test_event", payload.clone(), 1); - assert_eq!(event_record.event_name, "test_event"); - assert_eq!(event_record.payload, payload); - assert_eq!(event_record.sequence, 1); - } - - #[test] - fn clone() { - let payload = bitcode::serialize(&("arg1", "arg2")).unwrap(); - let original = EventRecord::new("test_event", payload, 1); - let cloned = original.clone(); - assert_eq!(cloned.event_name, "test_event"); - assert_eq!(cloned.payload, original.payload); - assert_eq!(cloned.sequence, 1); - } - - #[test] - fn debug() { - let payload = bitcode::serialize(&("arg1", "arg2")).unwrap(); - let event_record = EventRecord::new("test_event", payload, 1); - let debug_str = format!("{:?}", event_record); - assert!(debug_str.contains("EventRecord")); - assert!(debug_str.contains("event_name: \"test_event\"")); - assert!(debug_str.contains("sequence: 1")); - } - #[test] fn serialize_deserialize() { let payload = bitcode::serialize(&("arg1", "arg2")).unwrap(); @@ -332,13 +303,6 @@ mod tests { assert!(err.message.contains("unsupported payload codec `json`")); } - #[test] - fn payload_bytes() { - let payload = vec![0xff, 0x00, 0xab]; - let event_record = EventRecord::new("test_event", payload.clone(), 1); - assert_eq!(event_record.payload_bytes(), &payload[..]); - } - #[test] fn with_metadata_constructor() { let mut meta = HashMap::new(); @@ -402,20 +366,4 @@ mod tests { assert!(json.contains("metadata")); assert!(json.contains("key")); } - - #[test] - fn deserialize_without_metadata_field_defaults_to_empty() { - let json = r#"{"event_name":"old_event","payload_codec":"bitcode","payload_codec_version":1,"payload":"","sequence":1,"timestamp":{"secs_since_epoch":0,"nanos_since_epoch":0}}"#; - let record: EventRecord = serde_json::from_str(json).unwrap(); - assert!(record.metadata.is_empty()); - } - - #[test] - fn deserialize_without_payload_codec_fields_defaults_to_bitcode() { - let json = r#"{"event_name":"old_event","payload":"","sequence":1,"timestamp":{"secs_since_epoch":0,"nanos_since_epoch":0},"metadata":{}}"#; - let record: EventRecord = serde_json::from_str(json).unwrap(); - - assert_eq!(record.payload_codec, BITCODE_PAYLOAD_CODEC); - assert_eq!(record.payload_codec_version, BITCODE_PAYLOAD_CODEC_VERSION); - } } diff --git a/src/in_memory_repo/repository.rs b/src/in_memory_repo/repository.rs index cca904ea2..edcbc223f 100644 --- a/src/in_memory_repo/repository.rs +++ b/src/in_memory_repo/repository.rs @@ -918,12 +918,6 @@ mod tests { .await } - #[test] - fn new() { - let repo = InMemoryRepository::new(); - assert!(repo.event_store.read().unwrap().is_empty()); - } - #[tokio::test] async fn single_entity_commit() { let repo = InMemoryRepository::new(); diff --git a/src/microsvc/cell_host/tests.rs b/src/microsvc/cell_host/tests.rs index a200207ad..aaa161541 100644 --- a/src/microsvc/cell_host/tests.rs +++ b/src/microsvc/cell_host/tests.rs @@ -739,34 +739,6 @@ async fn parent_cells_are_isolated_and_have_no_cross_cell_commit() { assert!(GetStream::get_stream(&game_2, &player_id).await.is_err()); } -#[test] -fn cargo_features_keep_sqlite_and_do_not_add_celld() { - let manifest = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml")); - assert!( - manifest - .lines() - .any(|line| line.trim_start().starts_with("sqlite =")), - "sqlite feature must remain next to postgres" - ); - assert!( - manifest - .lines() - .any(|line| line.trim_start().starts_with("postgres =")), - "postgres feature must remain next to sqlite" - ); - let features = manifest - .split("[features]") - .nth(1) - .and_then(|rest| rest.split("\n[").next()) - .expect("features table"); - assert!( - !features - .lines() - .any(|line| line.trim_start().starts_with("celld")), - "PCH-DEC-005: do not add a celld Cargo feature beside sqlite/postgres" - ); -} - #[tokio::test] async fn reference_host_applies_the_sealed_row_reducer_on_commit() { let store = CellStreamStore::new("CellItem", "item-s") diff --git a/src/outbox_worker/store/tests.rs b/src/outbox_worker/store/tests.rs index fbace6840..59aa3d8d9 100644 --- a/src/outbox_worker/store/tests.rs +++ b/src/outbox_worker/store/tests.rs @@ -527,7 +527,7 @@ async fn complete_many_rejects_stale_and_missing_claims() { } #[tokio::test] -async fn already_published_message_is_not_completed_again() { +async fn completing_an_already_completed_claim_reports_not_found() { let repo = InMemoryRepository::new(); let message = OutboxMessage::create("msg-1", "Event", b"{}".to_vec()).unwrap(); let _id = store_message(&repo, message).await; diff --git a/src/projection/catalog.rs b/src/projection/catalog.rs index 064fcfbaf..31cfd2814 100644 --- a/src/projection/catalog.rs +++ b/src/projection/catalog.rs @@ -1175,6 +1175,32 @@ mod tests { error, ProjectionTopologyError::DirectIneligible { .. } )); + + // A multi-row program (two output models) is never direct evidence. + let error = ProjectionBinding::materialize_direct( + DirectProjectionPlacement::new(&descriptor), + ProjectionSourceBinding::try_new("todo-domain", "ordered-domain-events", 1).unwrap(), + ProjectionOwner::try_new("todo-direct").unwrap(), + "distributed-projection-partition", + 1, + vec![ + ProjectionOutput::try_new("Todos", "todos", todo_schema("todos")).unwrap(), + ProjectionOutput::try_new( + "TodoAudits", + "todo_audits", + model_schema("TodoAudits", "todo_audits"), + ) + .unwrap(), + ], + vec![], + None, + ) + .unwrap_err(); + + assert!(matches!( + error, + ProjectionTopologyError::DirectIneligible { .. } + )); } fn activation( diff --git a/tests/aggregate_command/main.rs b/tests/aggregate_command/main.rs index 23b7be9de..cc257a52d 100644 --- a/tests/aggregate_command/main.rs +++ b/tests/aggregate_command/main.rs @@ -13,6 +13,8 @@ use distributed::{sourced, DomainState, Entity}; use serde::{Deserialize, Serialize}; use serde_json::json; +mod thin; + #[derive(Clone, Default, Serialize, Deserialize)] pub struct Hero { entity: Entity, diff --git a/tests/aggregate_command/thin.rs b/tests/aggregate_command/thin.rs new file mode 100644 index 000000000..9184bb2e5 --- /dev/null +++ b/tests/aggregate_command/thin.rs @@ -0,0 +1,219 @@ +//! `command!` (the thin, aggregate-external form) against the same `Hero`: +//! each `load:` kind, `guard:`, `constructor:` and +//! `preview_reduce_known_record:` behave as declared at dispatch time. + +use super::*; +use distributed::command; +use distributed::command::CommandProjectionPureReduce; + +fn not_mallory(ctx: &CausalCommandContext<'_, Hero>) -> bool { + ctx.session().user_id() != Some("mallory") +} + +fn hero_preview() -> CommandProjectionPureReduce { + CommandProjectionPureReduce::wasm( + "hero.preview", + "hero/pkg/hero_wasm", + "heroPreview", + "Heroes", + ) + .key_input("hero_id", ["hero_id"]) + .arg_input("item", ["item"]) + .assign(["items"]) +} + +command! { + name: "hero.enlist", + transition: domain_commands::Create, + aggregate: Hero, + input: CreateHero, + outcome: Eventual, + shard: |input| input.hero_id.clone(), + load: create, + roles: ["player"], + field: "heroes_enlist", + invoke: |hero, input, principal| hero + .create(principal, CreateHero { hero_id: input.hero_id.clone(), name: input.name.clone() }) + .map(|_| ()), + payload: |hero, _principal| hero_payload(hero), +} + +command! { + name: "hero.outfit", + transition: domain_commands::Equip, + aggregate: Hero, + input: EquipInput, + outcome: Eventual, + shard: |input| input.hero_id.clone(), + load: required, + roles: ["player"], + field: "heroes_outfit", + constructor: outfit_command, + preview_reduce_known_record: hero_preview(), + guard: not_mallory, + invoke: |hero, input, principal| hero.equip(input.slot.clone(), principal, &input.item), + payload: |hero, _principal| hero_payload(hero), +} + +command! { + name: "hero.doze", + transition: domain_commands::Nap, + aggregate: Hero, + input: NapInput, + outcome: Eventual, + shard: |_input| "cy".to_string(), + load: or_create, + roles: ["player"], + field: "heroes_doze", + invoke: |hero, input, principal| hero + .nap(principal.to_string(), NapInput { minutes: input.minutes }) + .map(|_| ()), + payload: |hero, _principal| hero_payload(hero), +} + +fn thin_cell(id: &str) -> AggregateCell { + AggregateCell::::new(id) + .unwrap() + .mount(enlist()) + .mount(outfit_command()) + .mount(doze()) +} + +#[tokio::test] +async fn create_load_starts_a_new_aggregate_and_rejects_an_existing_one() { + let cell = thin_cell("t1"); + let created = dispatch( + &cell, + "hero.enlist", + json!({ "hero_id": "t1", "name": "Ana" }), + session(Some("ana")), + ) + .await + .unwrap(); + assert_eq!( + created, + json!({ "hero_id": "t1", "name": "Ana", "items": 0 }) + ); + + let again = dispatch( + &cell, + "hero.enlist", + json!({ "hero_id": "t1", "name": "Ana" }), + session(Some("ana")), + ) + .await; + assert!( + matches!(again, Err(CausalDispatchError::Rejected { .. })), + "{again:?}" + ); + assert_eq!(cell.history().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn required_load_and_guard_gate_the_transition() { + let missing = dispatch( + &thin_cell("t2"), + "hero.outfit", + json!({ "hero_id": "t2", "slot": "hand", "item": "axe" }), + session(Some("ana")), + ) + .await; + assert!( + matches!( + missing, + Err(CausalDispatchError::Rejected { status: 404, .. }) + ), + "{missing:?}" + ); + + let cell = thin_cell("t3"); + dispatch( + &cell, + "hero.enlist", + json!({ "hero_id": "t3", "name": "Ana" }), + session(Some("ana")), + ) + .await + .unwrap(); + let outfitted = dispatch( + &cell, + "hero.outfit", + json!({ "hero_id": "t3", "slot": "hand", "item": "sword" }), + session(Some("ana")), + ) + .await + .unwrap(); + assert_eq!(outfitted["items"], 1); + + // Mallory owns this hero, so only the guard can refuse her. + let guarded = thin_cell("t4"); + dispatch( + &guarded, + "hero.enlist", + json!({ "hero_id": "t4", "name": "Mal" }), + session(Some("mallory")), + ) + .await + .unwrap(); + let refused = dispatch( + &guarded, + "hero.outfit", + json!({ "hero_id": "t4", "slot": "head", "item": "hat" }), + session(Some("mallory")), + ) + .await; + assert!(refused.is_err(), "the guard must refuse: {refused:?}"); + assert!(guarded.load().await.unwrap().unwrap().slots.is_empty()); +} + +#[tokio::test] +async fn or_create_load_reuses_the_shard_aggregate() { + let cell = thin_cell("cy"); + for naps in 1..=2 { + dispatch( + &cell, + "hero.doze", + json!({ "minutes": 5 }), + session(Some("cy")), + ) + .await + .unwrap(); + assert_eq!(cell.load().await.unwrap().unwrap().naps, naps); + } + // created + two naps on one aggregate + assert_eq!(cell.history().await.unwrap().len(), 3); +} + +#[test] +fn declarations_register_their_fields_and_the_declaring_package() { + let specs = distributed::microsvc::Routes::new() + .with_repo(distributed::AggregateRepository::<_, Hero>::new( + distributed::InMemoryRepository::new(), + )) + .mount(enlist()) + .mount(outfit_command()) + .mount(doze()) + .command_specs() + .unwrap(); + let field = |id: &str| { + specs + .iter() + .find(|spec| spec.id == id) + .unwrap_or_else(|| panic!("missing {id}")) + .field_name + .clone() + }; + assert_eq!(field("hero.enlist"), "heroes_enlist"); + assert_eq!(field("hero.outfit"), "heroes_outfit"); + assert_eq!(field("hero.doze"), "heroes_doze"); + + let outfit = specs.iter().find(|spec| spec.id == "hero.outfit").unwrap(); + let contract = &outfit.projection_contract; + let pure = &contract["pure_reduces"][0]; + assert_eq!(pure["fn_name"], "hero.preview", "{contract}"); + assert_eq!( + pure["wasm_rust_package"], + env!("CARGO_PKG_NAME"), + "{contract}" + ); +} diff --git a/tests/application_composition.rs b/tests/application_composition.rs index 4e4cbeba0..c4984ab0a 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -792,12 +792,6 @@ fn explicit_definition_mount_identity_and_missing_pairing_fail_closed() { assert!(duplicate.to_string().contains("duplicate command identity")); } -#[test] -fn no_linker_inventory_is_needed_for_explicit_application_selection() { - let application = application_with_commands(&["todo.create"]); - assert_eq!(application.manifest().module_ids(), ["todo"]); -} - #[test] fn nested_fingerprints_and_projection_references_are_fail_closed() { let application = application_with_commands(&["todo.create"]); diff --git a/tests/celld/main.rs b/tests/celld/main.rs index f70094bf2..ee9444146 100644 --- a/tests/celld/main.rs +++ b/tests/celld/main.rs @@ -1,10 +1,9 @@ //! Live celld host: one Todo Durable Object per todo id, one Chat cell per //! message id. //! -//! Fixture checks always run. The HTTP round-trip runs only when `CELLD_URL` +//! Every test runs only when `CELLD_URL` //! is set (operator started compose + `celld deploy`). See `tests/celld/README.md`. -use std::path::Path; use std::time::Duration; use distributed::cell_host::{ @@ -19,169 +18,6 @@ const TEST_PRINCIPAL_PARTITION: &str = "test-principal-alice"; #[path = "../support/env.rs"] mod env_support; -fn worker_dir() -> &'static Path { - Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/celld/worker")) -} - -fn relay_worker_dir() -> &'static Path { - Path::new(concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/celld/relay-worker" - )) -} - -#[test] -fn worker_declares_sqlite_todo_and_chat_cells() { - let wrangler = - std::fs::read_to_string(worker_dir().join("wrangler.jsonc")).expect("wrangler.jsonc"); - let spec: Value = serde_json::from_str(&wrangler).expect("wrangler json"); - assert_eq!(spec["main"], "build/worker/shim.mjs"); - let bindings = spec["durable_objects"]["bindings"].as_array().unwrap(); - assert_eq!(bindings[0]["name"], "TODO"); - assert_eq!(bindings[0]["class_name"], "TodoCell"); - assert_eq!(bindings[1]["name"], "CHAT"); - assert_eq!(bindings[1]["class_name"], "ChatCell"); - let v1 = spec["migrations"][0]["new_sqlite_classes"] - .as_array() - .unwrap(); - assert_eq!(v1[0], "TodoCell"); - let v2 = spec["migrations"][1]["new_sqlite_classes"] - .as_array() - .unwrap(); - assert_eq!(v2[0], "ChatCell"); - assert_eq!(spec["queues"]["producers"][0]["binding"], "OUTBOX"); - assert_eq!( - spec["queues"]["producers"][0]["queue"], - "distributed-outbox" - ); - assert!(spec["vars"].get("OUTBOX_DRAIN_URL").is_none()); - - let source = std::fs::read_to_string(worker_dir().join("src/lib.rs")).expect("lib.rs"); - assert!(source.contains("pub struct TodoCell")); - assert!(source.contains("pub struct ChatCell")); - assert!(source.contains("AggregateCell::")); - assert!(source.contains("AggregateCell::")); - assert!(source.contains("id_from_name")); - assert!(source.contains("mount(create())")); - assert!(source.contains("mount(complete())")); - assert!(source.contains("mount(post())")); - assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_events")); - assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_snapshots")); - assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_sealed")); - assert!(source.contains("todo.create")); - assert!(source.contains("todo.complete")); - assert!(source.contains("chat.post")); - assert!(!source.contains("outbox.complete")); - assert!(!source.contains("outbox.claim")); - assert!(!source.contains("outbox.release")); - assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_outbox")); - assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_commands")); - assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_state")); - assert!(!source.contains("durable_state")); - assert!(!source.contains("restore_durable_state")); - assert!(!source.contains("ON CONFLICT(id) DO UPDATE SET body = excluded.body")); - assert!(source.contains("dispatch_idempotent")); - assert!(source.contains("CelldOutbox::from_env(&env, \"OUTBOX\")")); - assert!(source.contains("with_celld_outbox(outbox)")); - assert!(source.contains(".drain_outbox(env)")); - assert!( - source.contains("cell\n .alarm(env)"), - "the Durable Object alarm handler fires cell alarms and drains through AggregateCell::alarm" - ); - assert!(!source.contains("persist_and_drain_outbox")); - assert!(!source.contains("CelldQueuePublisher::from_env")); - assert!(!source.contains("drain_outbox_to_queue")); - assert!(!source.contains("arm_drain_alarm")); - assert!( - !source.contains("outcome.released") && !source.contains("outcome.failed"), - "retryable Queue outcomes must stay alarm-owned, not fail a committed command" - ); - assert!(source.contains("dispatch.projection_events()")); - assert!(source.contains("\"events\": events")); - assert!(!source.contains("CellOutboxWireItem")); - assert!(!source.contains("restore_durable_commands")); - assert!(!source.contains("sealed_row")); - assert!(source.contains("from_state_with_snapshots")); - assert!(!source.contains("restore_durable_events")); - assert!(!source.contains("restore_durable_snapshots")); - assert!(!source.contains("restore_cell_state")); -} - -#[test] -fn alarm_worker_arms_cell_alarms_and_shares_the_durable_object_alarm() { - let dir = Path::new(concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/celld/alarm-worker" - )); - let wrangler = std::fs::read_to_string(dir.join("wrangler.jsonc")).expect("wrangler.jsonc"); - let spec: Value = serde_json::from_str(&wrangler).expect("wrangler json"); - assert_eq!( - spec["durable_objects"]["bindings"][0]["class_name"], - "TickerCell" - ); - assert_eq!(spec["migrations"][0]["new_sqlite_classes"][0], "TickerCell"); - assert_eq!(spec["queues"]["producers"][0]["binding"], "OUTBOX"); - let source = std::fs::read_to_string(dir.join("src/lib.rs")).expect("lib.rs"); - assert!(source.contains("ctx.schedule(")); - assert!(source.contains("schedule_guard::")); - assert!(source.contains(".requires(Capability::Scheduling)")); - assert!(source.contains(".alarm(&self.env)")); - assert!(source.contains("with_celld_outbox(outbox)")); - let harness = std::fs::read_to_string(concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/celld/alarms.mjs" - )) - .expect("alarms.mjs"); - assert!(harness.contains("fires once across restart")); - assert!(harness.contains("watchdog not starved by a far domain alarm")); -} - -#[test] -fn relay_worker_consumes_events_queue_through_native_bus_boundary() { - let wrangler = std::fs::read_to_string(relay_worker_dir().join("wrangler.jsonc")) - .expect("relay wrangler.jsonc"); - let spec: Value = serde_json::from_str(&wrangler).expect("relay wrangler json"); - assert_eq!( - spec["queues"]["consumers"][0]["queue"], - "distributed-outbox" - ); - assert_eq!( - spec["vars"]["CELLD_QUEUE_RELAY_URL"], - "http://127.0.0.1:8791/internal/celld-queue/relay" - ); - assert_eq!(spec["vars"]["CELLD_QUEUE_RELAY_LOCAL_TEST"], "1"); - - let source = - std::fs::read_to_string(relay_worker_dir().join("src/lib.rs")).expect("relay lib.rs"); - assert!(source.contains("#[event(queue)]")); - assert!(source.contains("CelldQueueRelay")); - assert!(source.contains("CelldQueueHttpPublisher")); - assert!(source.contains("new_local_test")); - assert!(!source.contains("event(fetch)")); -} - -#[test] -fn local_entrypoint_delegates_to_the_single_persistent_profile() { - let makefile = - std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/celld/Makefile")) - .expect("Makefile"); - assert!(makefile.contains("PROFILE_DIR := ../e2e-ui")); - assert!(makefile.contains("up-celld-nats")); - assert!(makefile.contains("test-celld")); - assert!(makefile.contains("down-celld")); - assert!(makefile.contains("worker/.celld/dev")); - assert!(!makefile.contains("docker-compose.yml")); - assert!(!makefile.contains("dev-relay")); - - let profile_makefile = std::fs::read_to_string(concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/e2e-ui/Makefile" - )) - .expect("profile Makefile"); - assert!(profile_makefile.contains("refusing to start celld")); - assert!(profile_makefile.contains("refusing to stop untracked listener")); -} - #[tokio::test] async fn live_cell_private_routes_reject_missing_forged_and_malformed_authority() { let Some(base) = env_support::require_service("CELLD_URL", "celld live security boundary") diff --git a/tests/distributed_read_model/main.rs b/tests/distributed_read_model/main.rs index 043b85bf5..dfea6c235 100644 --- a/tests/distributed_read_model/main.rs +++ b/tests/distributed_read_model/main.rs @@ -1200,21 +1200,21 @@ async fn postgres_matrix_repo() -> Option<( } #[cfg(feature = "postgres")] -async fn postgres_matrix_bus() -> Option { +async fn postgres_matrix_bus( +) -> Option<(postgres::PostgresTestSchema, distributed::bus::PostgresBus)> { use distributed::bus::PostgresBus; let schema = postgres::PostgresTestSchema::create_from_env("matrix_pgbus", "Postgres-bus matrix cell") .await?; let bus = PostgresBus::new(schema.repository().await.pool().clone()).group("matrix"); bus.ensure_tables().await.expect("postgres bus tables"); - // The schema has no Drop, so the bus's tables outlive this fixture. - Some(bus) + Some((schema, bus)) } #[cfg(all(feature = "postgres", feature = "sqlite"))] #[tokio::test] async fn matrix_sqlite_persistence_over_postgres_bus() { - let Some(bus) = postgres_matrix_bus().await else { + let Some((_bus_schema, bus)) = postgres_matrix_bus().await else { return; }; run_matrix_cell(bus, sqlite_matrix_repo().await, "sqlite-pgbus").await; @@ -1223,7 +1223,7 @@ async fn matrix_sqlite_persistence_over_postgres_bus() { #[cfg(feature = "postgres")] #[tokio::test] async fn matrix_postgres_persistence_over_postgres_bus() { - let (Some((_schema, repo)), Some(bus)) = + let (Some((_schema, repo)), Some((_bus_schema, bus))) = (postgres_matrix_repo().await, postgres_matrix_bus().await) else { return; diff --git a/tests/e2e-ui/crates/blob-domain/src/commands/mod.rs b/tests/e2e-ui/crates/blob-domain/src/commands/mod.rs index e8c3ed85b..e892cf1af 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/mod.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/mod.rs @@ -50,11 +50,4 @@ mod tests { assert!(projection.contains("blob.simulate_move"), "{projection}"); assert!(projection.contains("blobSimulateMove"), "{projection}"); } - - #[test] - fn client_preview_wasm_stays_in_blob_domain_wasm_module() { - let src = include_str!("../wasm.rs"); - assert!(src.contains("blobSimulateMove")); - assert!(src.contains("blob_simulate_move")); - } } diff --git a/tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs b/tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs index 7ac9419b1..4d744a450 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs @@ -1,6 +1,6 @@ +use distributed::command; use distributed::command::{Atomic, CommandProjectionPureReduce, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; -use distributed::command; use e2e_readmodels::BlobGames; use serde::Deserialize; @@ -73,15 +73,6 @@ mod tests { use distributed::cell_host::instance_name; use distributed::Aggregate; - #[test] - fn shard_is_game_id() { - let input = BlobMoveInput { - game_id: "g1".into(), - direction: "up".into(), - }; - assert_eq!(Move::shard(&input), "g1"); - } - #[test] fn cell_is_parent_game_shard() { let input = BlobMoveInput { diff --git a/tests/e2e-ui/crates/blob-domain/src/commands/start.rs b/tests/e2e-ui/crates/blob-domain/src/commands/start.rs index debc66cc7..daf1900d0 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/start.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/start.rs @@ -1,6 +1,6 @@ +use distributed::command; use distributed::command::{Atomic, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; -use distributed::command; use e2e_readmodels::BlobGames; use serde::Deserialize; @@ -43,16 +43,3 @@ command! { guard: authenticated_user, handle: handle_start, } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_game_id() { - let input = BlobStartInput { - game_id: "g1".into(), - }; - assert_eq!(Start::shard(&input), "g1"); - } -} diff --git a/tests/e2e-ui/crates/blob-domain/src/commands/start_level.rs b/tests/e2e-ui/crates/blob-domain/src/commands/start_level.rs index b0dfc9aef..d157a426c 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/start_level.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/start_level.rs @@ -1,6 +1,6 @@ +use distributed::command; use distributed::command::{Atomic, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; -use distributed::command; use e2e_readmodels::BlobGames; use serde::Deserialize; @@ -39,16 +39,3 @@ command! { guard: authenticated_user, handle: handle_start_level, } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_game_id() { - let input = BlobStartLevelInput { - game_id: "g1".into(), - }; - assert_eq!(StartLevel::shard(&input), "g1"); - } -} diff --git a/tests/e2e-ui/crates/chat-domain/src/commands/post.rs b/tests/e2e-ui/crates/chat-domain/src/commands/post.rs index 2b5fed84c..c2841786d 100644 --- a/tests/e2e-ui/crates/chat-domain/src/commands/post.rs +++ b/tests/e2e-ui/crates/chat-domain/src/commands/post.rs @@ -1,6 +1,6 @@ +use distributed::command; use distributed::command::{Eventual, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; -use distributed::command; use serde::{Deserialize, Serialize}; use crate::{domain_commands, ChatMessage, ChatMessagePostedDomainEvent, ChatMessageState}; @@ -129,24 +129,6 @@ mod tests { use distributed::microsvc::Routes; use distributed::{AggregateBuilder, InMemoryRepository}; - #[test] - fn shard_is_message_id() { - let input = ChatPostInput { - message_id: "m1".into(), - body: "hi".into(), - room_id: "lobby".into(), - created_at: "1".into(), - }; - assert_eq!(Post::shard(&input), "m1"); - } - - #[test] - fn post_uses_handle_escape_hatch() { - assert_eq!(Post::COMMAND, "chat.post"); - let _ = handle_post; - let _ = canonical_near_unix_millis; - } - #[test] fn created_at_rejects_non_canonical() { assert!(canonical_near_unix_millis("not-a-time").is_err()); diff --git a/tests/e2e-ui/crates/projections/src/blob.rs b/tests/e2e-ui/crates/projections/src/blob.rs index 824628688..8b16e2598 100644 --- a/tests/e2e-ui/crates/projections/src/blob.rs +++ b/tests/e2e-ui/crates/projections/src/blob.rs @@ -41,222 +41,12 @@ distributed::projection! { }; } -/// Compile-time guards for removed authoring surfaces. -/// -/// ```compile_fail -/// const _GONE: () = projection! {}; -/// ``` -/// -/// ```compile_fail,E0599 -/// use blob_domain::BlobGame; -/// use e2e_readmodels::BlobGames; -/// use e2e_projections::BLOB_GAMES; -/// use distributed::microsvc::{AggregateCheckout, CausalCommandContext}; -/// fn gone(ctx: &CausalCommandContext<'_, BlobGame>, game: AggregateCheckout) { -/// let _ = ctx.project(BLOB_GAMES).commit(game).unwrap().projected_many::(); -/// } -/// ``` -#[doc(hidden)] -pub struct BlobDirectEligibilityGuards; - #[cfg(test)] mod tests { - use distributed::mutation::{delete_by_pk_program_for_model, state_upsert_program_for_model}; - use distributed::projection::lower::{ - finish_lowering, lower_model_mutation, EventualOnly, ProjectionDescriptor, - ProjectionLoweringError, ProjectionOutputInventory, ProjectionOutputModel, - ProjectionProgramCell, - }; - use distributed::projection::ProjectionEventSelector; - use distributed::{ - body_field_binding, compile_projection, MutationColumn, MutationKind, MutationOperation, - MutationProgram, ProjectionHandler, ProjectionInputSource, ProjectionPartition, - ProjectionProgram, ProjectionProgramError, ProjectionTarget, ProjectionValueType, - RelationalReadModel, ResolvedProjectionPlan, RowValue, TableMutation, - }; - use serde::{Deserialize, Serialize}; + use distributed::{MutationKind, RowValue, TableMutation}; use super::*; - use blob_domain::{test_map_no_holes, BlobGame, BlobGameState, Direction}; - - #[derive(Clone, Serialize, Deserialize, distributed::ReadModel)] - #[readmodel(primary_key = ["game_id"])] - struct BlobGameAudits { - #[readmodel(id)] - game_id: String, - owner_id: String, - score: i64, - player_dead: bool, - current_level: i64, - current_level_completed: bool, - map_json: String, - status: String, - } - - fn blob_moved_selector() -> Result { - ProjectionEventSelector::try_from_descriptor(&distributed::DomainEventDescriptor::state::< - BlobGameState, - >("blob.moved", 1)) - } - - fn moved( - name: &str, - inputs: Vec, - mutation: MutationProgram, - ) -> Result { - compile_projection( - name, - 1, - ProjectionPartition::Unit, - [ProjectionHandler::try_new( - "moved", - blob_moved_selector()?, - inputs, - mutation, - )?], - ) - } - - fn game_id() -> Result { - body_field_binding(["game_id"], ["game_id"], ProjectionValueType::String) - } - - fn patch_blob_program() -> Result { - let schema = BlobGames::schema(); - let column = - |name: &str| MutationColumn::try_new(name, ProjectionValueType::String, [name]); - let patch = MutationOperation::try_new( - "patch-status", - MutationKind::Patch, - ProjectionTarget::try_new(schema.model_name.clone(), schema.table_name.clone())?, - vec![column("game_id")?], - vec![column("status")?], - )?; - moved( - "blob_patch_fixture", - vec![ - game_id()?, - body_field_binding(["status"], ["status"], ProjectionValueType::String)?, - ], - MutationProgram::try_new("patch_blob_games", 1, vec![patch])?, - ) - } - - distributed::projection! { - const PATCH_BLOB_GAMES: ProjectionDescriptor = { - name: "blob_patch_fixture", - version: 1, - epoch: "fixture", - model: BlobGames, - program: patch_blob_program, - }; - } - - fn delete_blob_program() -> Result { - moved( - "blob_delete_fixture", - vec![game_id()?], - delete_by_pk_program_for_model::("delete_blob_games", 1, "delete-blob")?, - ) - } - - distributed::projection! { - const DELETE_BLOB_GAMES: ProjectionDescriptor = { - name: "blob_delete_fixture", - version: 1, - epoch: "fixture", - model: BlobGames, - program: delete_blob_program, - }; - } - - fn multi_row_blob_program() -> Result { - let games = state_upsert_program_for_model::( - "save_blob_games_multi", - 1, - "upsert-games", - "first", - )?; - let audits = state_upsert_program_for_model::( - "save_blob_audits_multi", - 1, - "upsert-audits", - "second", - )?; - moved( - "blob_multi_row_fixture", - vec![ - ProjectionInputSource::Body.binding("first")?, - ProjectionInputSource::Body.binding("second")?, - ], - MutationProgram::try_new( - "blob_multi_row_mutation", - 1, - [games.operations(), audits.operations()].concat(), - )?, - ) - } - - fn multi_row_blob_lower( - plan: &ResolvedProjectionPlan, - ) -> Result - { - let mut builder = distributed::read_model::ReadModelWritePlanBuilder::new(); - for mutation in plan.mutations() { - match mutation.target().model() { - "BlobGames" => lower_model_mutation::(&mut builder, mutation)?, - "BlobGameAudits" => lower_model_mutation::(&mut builder, mutation)?, - other => { - return Err(ProjectionLoweringError::Table( - distributed::TableStoreError::Metadata(format!("unknown model `{other}`")), - )); - } - } - } - finish_lowering(builder, plan) - } - - fn multi_row_blob_inventory() -> Result { - Ok(ProjectionOutputInventory::new( - vec![ - ProjectionOutputModel::of::()?, - ProjectionOutputModel::of::()?, - ], - Vec::new(), - )) - } - - const MULTI_ROW_BLOB_GAMES: ProjectionDescriptor = ProjectionDescriptor::new( - "blob_multi_row_fixture", - 1, - "fixture", - || { - static PROGRAM: ProjectionProgramCell = ProjectionProgramCell::new(); - PROGRAM.get_or_build(multi_row_blob_program) - }, - multi_row_blob_lower, - multi_row_blob_inventory, - ); - - fn assert_eventual_only(_: ProjectionDescriptor) {} - - #[test] - fn blob_program_is_built_from_save_blob_game_mutation() { - let program = BLOB_GAMES.program().unwrap(); - let from_mutations = BLOB_GAMES.program().unwrap(); - assert_eq!( - program.canonical_bytes().unwrap(), - from_mutations.canonical_bytes().unwrap() - ); - assert_eq!(program.arms().len(), 4); - assert!(program.arms().iter().all(|arm| { - arm.operations().len() == 1 && arm.operations()[0].kind() == MutationKind::Upsert - })); - assert_eq!( - SaveBlobGame().program().unwrap().operations()[0].kind(), - MutationKind::Upsert - ); - } + use blob_domain::{BlobGame, BlobGameState, Direction}; #[test] fn from_state_materializes_blob_games_row_for_handler_owned_projected() { @@ -363,8 +153,6 @@ mod tests { fn moved_state_is_one_complete_direct_upsert() { let mut game = BlobGame::default(); game.start_with_demo("g1", "alice").unwrap(); - let map = test_map_no_holes(); - let _ = map; if game.move_dir("alice", Direction::Up).is_ok() { assert_direct_state_upsert(&game, "blob.moved"); } @@ -377,11 +165,4 @@ mod tests { assert_eq!(inventory.models[0].model, "BlobGames"); assert_eq!(BLOB_GAMES.program().unwrap().arms().len(), 4); } - - #[test] - fn patch_delete_and_multi_row_descriptors_are_not_direct_candidates() { - assert_eventual_only(PATCH_BLOB_GAMES); - assert_eventual_only(DELETE_BLOB_GAMES); - assert_eventual_only(MULTI_ROW_BLOB_GAMES); - } } diff --git a/tests/e2e-ui/crates/projections/src/lib.rs b/tests/e2e-ui/crates/projections/src/lib.rs index 98be2da7d..33228112a 100644 --- a/tests/e2e-ui/crates/projections/src/lib.rs +++ b/tests/e2e-ui/crates/projections/src/lib.rs @@ -8,6 +8,6 @@ mod todos; pub use auth_users::{ map_zitadel_user_status, map_zitadel_user_upsert, ZitadelEmail, ZitadelUserPayload, }; -pub use blob::{SaveBlobGame, BlobDirectEligibilityGuards, BLOB_GAMES}; +pub use blob::{SaveBlobGame, BLOB_GAMES}; pub use chat::{SaveChatMessage, CHAT_MESSAGES}; pub use todos::{DeleteTodo, SaveTodo, TODOS}; diff --git a/tests/e2e-ui/crates/projections/src/todos.rs b/tests/e2e-ui/crates/projections/src/todos.rs index a1cbb70b8..cf812a9ec 100644 --- a/tests/e2e-ui/crates/projections/src/todos.rs +++ b/tests/e2e-ui/crates/projections/src/todos.rs @@ -60,27 +60,11 @@ distributed::projection! { mod tests { use distributed::domain_event::DomainEventContract; use distributed::projection::placement::ProjectionExecutionClass; - use distributed::{ - DomainEventBodyKind, MutationKind, RelationalReadModel, RowValue, TableMutation, - }; + use distributed::{DomainEventBodyKind, RelationalReadModel, RowValue, TableMutation}; use super::*; use todo_domain::{Todo, TodoPurgedDomainEvent}; - #[test] - fn todo_handlers_apply_save_and_delete_mutations() { - let program = TODOS.program().unwrap(); - assert_eq!(program.arms().len(), 8); - assert_eq!( - SaveTodo().program().unwrap().operations()[0].kind(), - MutationKind::Upsert - ); - assert_eq!( - DeleteTodo().program().unwrap().operations()[0].kind(), - MutationKind::Delete - ); - } - #[test] fn complete_lowers_to_full_row_upsert() { let mut todo = Todo::default(); @@ -134,22 +118,4 @@ mod tests { .to_string(); assert!(!json.contains("event_name")); } - - #[test] - fn graphql_file_matches_inline_graphql_looking_form() { - use distributed::mutation; - assert_eq!(SaveTodo().program().unwrap().name(), "SaveTodo"); - assert_eq!(DeleteTodo().program().unwrap().name(), "DeleteTodo"); - let from_file = SaveTodo().program().unwrap(); - let inline = mutation! { - mutation SaveTodo { - upsert_todos(object: $input.todo) - } - }; - assert_eq!( - from_file, - inline.program().unwrap(), - "mutation_file! and inline GraphQL-looking mutation! must share IR" - ); - } } diff --git a/tests/e2e-ui/crates/service/src/application.rs b/tests/e2e-ui/crates/service/src/application.rs index 2fadaf399..77c620138 100644 --- a/tests/e2e-ui/crates/service/src/application.rs +++ b/tests/e2e-ui/crates/service/src/application.rs @@ -4,7 +4,7 @@ //! inventory, and re-exports of the composed host APIs. Infrastructure //! (dialect, outbox, OIDC serve) stays in `host`; handlers stay in modules. -use crate::modules::{blob, chat, compose, identity, todo}; +use crate::modules::compose; /// Stable normal-application surface shared by user and admin sessions. pub const DISTRIBUTED_CLIENT_SURFACE: &str = "e2e-ui"; @@ -18,14 +18,3 @@ pub const E2E_UI_APPLICATION: &str = "e2e-ui"; /// Explicit module identities owned by the e2e application. pub const E2E_UI_MODULE_IDS: &[&str] = compose::MODULE_IDS; - -/// Compile-time proof that module inventory matches bounded-context crates. -pub const MODULE_DECLARATIONS: &[(&str, &str)] = &[ - (todo::MODULE_ID, "todo commands + projector"), - (chat::MODULE_ID, "chat commands + projector"), - (blob::MODULE_ID, "blob Atomic commands"), - ( - identity::MODULE_ID, - "Zitadel ingress/scrape commands + AuthUsers projector", - ), -]; diff --git a/tests/e2e-ui/crates/service/src/handlers/util.rs b/tests/e2e-ui/crates/service/src/handlers/util.rs index 9aa0154b2..adb88a598 100644 --- a/tests/e2e-ui/crates/service/src/handlers/util.rs +++ b/tests/e2e-ui/crates/service/src/handlers/util.rs @@ -1,15 +1,8 @@ -//! Shared handler helpers. -//! -//! **Admission vs domain** -//! - [`session_has_user`] / [`session_is_admin`] / [`causal_has_user`] / -//! [`causal_is_admin`] — command **guards** (session admission only). -//! - Handler bodies bind the principal and call the domain; they do not re-check -//! “am I logged in?” when a guard already did. -//! - Domain owns entity invariants (empty title, ownership, board rules). +//! Shared event-handler helpers. use distributed::bus::Message; -use distributed::microsvc::{CausalCommandContext, HandlerError, Session}; -use distributed::{Aggregate, BitcodePayloadCodec, PayloadCodec}; +use distributed::microsvc::HandlerError; +use distributed::{BitcodePayloadCodec, PayloadCodec}; use serde::de::DeserializeOwned; /// Decode event payload as JSON (tests) or bitcode (outbox → bus). @@ -30,122 +23,6 @@ fn looks_like_json(bytes: &[u8]) -> bool { ) } -pub fn rejected(err: impl std::fmt::Display) -> HandlerError { - HandlerError::Rejected(err.to_string()) -} - pub fn read_model_error(e: impl std::fmt::Display) -> HandlerError { HandlerError::Other(Box::new(std::io::Error::other(e.to_string()))) } - -/// Authenticated user from session (`x-user-id` via DevHeaders or OIDC claim map). -pub fn require_user(session: &Session) -> Result { - session - .user_id() - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .ok_or_else(|| HandlerError::Unauthorized("missing x-user-id".into())) -} - -/// Session has a non-empty user id (for `guard` — bool, not Result). -pub fn session_has_user(session: &Session) -> bool { - session.user_id().is_some_and(|s| !s.is_empty()) -} - -/// Engine role set contains `admin` (`x-roles` / OIDC claim map). For `guard`. -pub fn session_is_admin(session: &Session) -> bool { - session.has_role("admin") -} - -/// Typed causal guard: non-empty session user id. -pub fn causal_has_user(ctx: &CausalCommandContext<'_, A>) -> bool -where - A: Aggregate + Send + Sync + 'static, -{ - session_has_user(ctx.session()) -} - -/// Typed causal guard: session user present and carries `admin`. -pub fn causal_is_admin(ctx: &CausalCommandContext<'_, A>) -> bool -where - A: Aggregate + Send + Sync + 'static, -{ - session_has_user(ctx.session()) && session_is_admin(ctx.session()) -} - -/// Principal after a user-session guard (for domain `owner_id` / author args). -pub fn principal(ctx: &CausalCommandContext<'_, A>) -> Result -where - A: Aggregate + Send + Sync + 'static, -{ - ctx.user_id().map(str::to_string) -} - -/// Require engine role `admin` (handler-path Result form). -pub fn require_admin(session: &Session) -> Result<(), HandlerError> { - if session.has_role("admin") { - return Ok(()); - } - let roles = session.roles(); - if roles.is_empty() { - Err(HandlerError::Unauthorized("missing x-roles".into())) - } else { - Err(HandlerError::Rejected(format!( - "admin role required, got `{}`", - roles.join(",") - ))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; - - #[test] - fn session_has_user_requires_nonempty_id() { - let mut s = Session::new(); - assert!(!session_has_user(&s)); - s.set(USER_ID_KEY, ""); - assert!(!session_has_user(&s)); - s.set(USER_ID_KEY, "alice"); - assert!(session_has_user(&s)); - } - - #[test] - fn session_is_admin_exact_role() { - let mut s = Session::new(); - assert!(!session_is_admin(&s)); - s.set(ROLE_KEY, "user"); - assert!(!session_is_admin(&s)); - s.set(ROLE_KEY, "admin"); - assert!(session_is_admin(&s)); - } - - #[test] - fn require_admin_errors() { - let mut s = Session::new(); - assert!(require_admin(&s).is_err()); - s.set(ROLE_KEY, "user"); - assert!(require_admin(&s).is_err()); - s.set(ROLE_KEY, "admin"); - assert!(require_admin(&s).is_ok()); - } - - #[test] - fn require_user_errors_and_returns_id() { - let mut s = Session::new(); - assert!(require_user(&s).is_err()); - s.set(USER_ID_KEY, "bob"); - assert_eq!(require_user(&s).unwrap(), "bob"); - } - - #[test] - fn session_is_admin_requires_user_for_causal_admin_guard_semantics() { - // Admin role without a user id is not a usable principal for force_archive. - let mut s = Session::new(); - s.set(ROLE_KEY, "admin"); - assert!(session_is_admin(&s)); - assert!(!session_has_user(&s)); - } -} diff --git a/tests/e2e-ui/crates/service/src/modules/graphql.rs b/tests/e2e-ui/crates/service/src/modules/graphql.rs index ab646888f..0643becd6 100644 --- a/tests/e2e-ui/crates/service/src/modules/graphql.rs +++ b/tests/e2e-ui/crates/service/src/modules/graphql.rs @@ -822,13 +822,4 @@ mod client_surface_tests { let envelope = serde_json::to_value(envelope).expect("serialized protocol envelope"); assert_eq!(envelope["schemaHash"], generated.schema_fingerprint); } - - #[test] - fn module_inventory_lists_todo_chat_blob_identity() { - assert_eq!( - crate::E2E_UI_MODULE_IDS, - &["todo", "chat", "blob", "identity"] - ); - assert_eq!(crate::application::MODULE_DECLARATIONS.len(), 4); - } } diff --git a/tests/e2e-ui/crates/suite/tests/behavioral.rs b/tests/e2e-ui/crates/suite/tests/behavioral.rs index 205e5e508..3ccdf9916 100644 --- a/tests/e2e-ui/crates/suite/tests/behavioral.rs +++ b/tests/e2e-ui/crates/suite/tests/behavioral.rs @@ -515,7 +515,7 @@ async fn t5_unauthenticated_rejected() { }} }}"# ); - // DevHeaders with no identity → command guard rejects (causal_has_user). + // DevHeaders with no identity → command guard rejects. let (status, body) = graphql_raw(&base, &doc).await.expect(cases::UNAUTH); // GuardRejected is client-facing (often GraphQL errors / 400); Unauthorized // remains 401 when identity is checked elsewhere. diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/archive.rs b/tests/e2e-ui/crates/todo-domain/src/commands/archive.rs index c60f501e8..4814ce793 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/archive.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/archive.rs @@ -25,16 +25,3 @@ command! { invoke: |todo, _input, principal| todo.archive(principal), payload: |todo, _principal| TodoStatusPayload::from_todo(&**todo), } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_todo_id() { - let input = TodoArchiveInput { - todo_id: "todo-1".into(), - }; - assert_eq!(Archive::shard(&input), "todo-1"); - } -} diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/complete.rs b/tests/e2e-ui/crates/todo-domain/src/commands/complete.rs index 0c252d057..0bce21b9d 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/complete.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/complete.rs @@ -39,16 +39,3 @@ command! { invoke: |todo, _input, principal| todo.complete(principal), payload: |todo, _principal| TodoStatusPayload::from_todo(&**todo), } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_todo_id() { - let input = TodoCompleteInput { - todo_id: "todo-1".into(), - }; - assert_eq!(Complete::shard(&input), "todo-1"); - } -} diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/create.rs b/tests/e2e-ui/crates/todo-domain/src/commands/create.rs index cec7d4ac7..f3dcdc951 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/create.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/create.rs @@ -46,17 +46,3 @@ command! { default input.todo_id = uuid_v7(); }, } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_todo_id() { - let input = TodoCreateInput { - todo_id: "todo-1".into(), - title: "one".into(), - }; - assert_eq!(Create::shard(&input), "todo-1"); - } -} diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/force_archive.rs b/tests/e2e-ui/crates/todo-domain/src/commands/force_archive.rs index 5f8714edb..905d5375a 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/force_archive.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/force_archive.rs @@ -40,16 +40,3 @@ command! { } }, } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_todo_id() { - let input = TodoForceArchiveInput { - todo_id: "todo-1".into(), - }; - assert_eq!(ForceArchive::shard(&input), "todo-1"); - } -} diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/purge.rs b/tests/e2e-ui/crates/todo-domain/src/commands/purge.rs index 6e3b93ee4..7372e3d19 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/purge.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/purge.rs @@ -31,16 +31,3 @@ command! { purged: true, }, } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_todo_id() { - let input = TodoPurgeInput { - todo_id: "todo-1".into(), - }; - assert_eq!(Purge::shard(&input), "todo-1"); - } -} diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/rename.rs b/tests/e2e-ui/crates/todo-domain/src/commands/rename.rs index 7884e31e0..49dd7cafa 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/rename.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/rename.rs @@ -37,17 +37,3 @@ command! { } }, } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_todo_id() { - let input = TodoRenameInput { - todo_id: "todo-1".into(), - title: "renamed".into(), - }; - assert_eq!(Rename::shard(&input), "todo-1"); - } -} diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/reopen.rs b/tests/e2e-ui/crates/todo-domain/src/commands/reopen.rs index a5c28a2ea..0fb3da578 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/reopen.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/reopen.rs @@ -25,16 +25,3 @@ command! { invoke: |todo, _input, principal| todo.reopen(principal), payload: |todo, _principal| TodoStatusPayload::from_todo(&**todo), } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shard_is_todo_id() { - let input = TodoReopenInput { - todo_id: "todo-1".into(), - }; - assert_eq!(Reopen::shard(&input), "todo-1"); - } -} diff --git a/tests/e2e_ui_celld_nats_profile/main.rs b/tests/e2e_ui_celld_nats_profile/main.rs index 49f484fad..719f84577 100644 --- a/tests/e2e_ui_celld_nats_profile/main.rs +++ b/tests/e2e_ui_celld_nats_profile/main.rs @@ -1,77 +1,17 @@ -//! Optional celld+NATS e2e-ui profile. -//! -//! Fixture checks always run (default host stays one-process). Live smoke -//! runs only when `CELLD_URL` and `NATS_URL` are set. - -use std::path::Path; -use std::sync::Arc; -use std::time::Duration; +//! Optional celld+NATS e2e-ui profile: a live smoke that runs only when +//! `CELLD_URL` and `NATS_URL` are set. +#[cfg(all(feature = "graphql", feature = "http", feature = "sqlite"))] #[path = "../support/env.rs"] mod env_support; -fn repo_root() -> &'static Path { - Path::new(env!("CARGO_MANIFEST_DIR")) -} - -#[test] -fn default_e2e_ui_host_stays_one_process() { - let host = std::fs::read_to_string(repo_root().join("tests/e2e-ui/crates/service/src/host.rs")) - .expect("host.rs"); - assert!( - host.contains("single backend process"), - "default host.rs must remain the one-process playground" - ); - assert!( - host.contains("celld-nats-profile"), - "host.rs should point at the optional profile, not implement it" - ); - assert!( - !host.contains("NatsBus"), - "optional NATS profile must not replace SqliteBus/PostgresBus in host.rs" - ); -} - -#[test] -fn optional_profile_is_named_and_not_the_playground() { - let readme = - std::fs::read_to_string(repo_root().join("tests/e2e-ui/celld-nats-profile/README.md")) - .expect("profile README"); - assert!(readme.contains("optional"), "{readme}"); - assert!(readme.contains("make run"), "{readme}"); - assert!(readme.contains("make up-celld-nats"), "{readme}"); - assert!(readme.contains("make test-celld-nats"), "{readme}"); - assert!(readme.contains("CELLD_URL"), "{readme}"); - assert!(readme.contains("NATS_URL"), "{readme}"); - assert!( - readme.contains("not") && readme.contains("cell class"), - "projectors must stay off cells" - ); - - let compose = std::fs::read_to_string( - repo_root().join("tests/e2e-ui/celld-nats-profile/docker-compose.yml"), - ) - .expect("profile compose"); - assert!(compose.contains("e2e-ui-celld-nats-optional"), "{compose}"); - assert!(compose.contains("nats:2-alpine"), "{compose}"); - assert!( - !compose - .lines() - .any(|line| line.trim_start().starts_with("image:") && line.contains("minio")), - "do not run MinIO" - ); - - let worker = std::fs::read_to_string(repo_root().join("tests/celld/worker/src/lib.rs")) - .expect("todo cell worker"); - assert!( - worker.contains("projectors are not methods on this class"), - "cells stay command-only" - ); -} - #[cfg(all(feature = "graphql", feature = "http", feature = "sqlite"))] mod live { - use super::*; + use std::sync::Arc; + use std::time::Duration; + + use super::env_support; + use async_graphql::Request; use distributed::cell_host::{ CelldCommandHost, CelldRoute, InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, diff --git a/tests/gateway-postgres/run.py b/tests/gateway-postgres/run.py index 0a1be4941..a088c35c2 100644 --- a/tests/gateway-postgres/run.py +++ b/tests/gateway-postgres/run.py @@ -68,7 +68,6 @@ class Server(socketserver.ThreadingTCPServer): subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway,graphql,postgres", "--test", "edge_query_delivery_postgres", "--", "--ignored", "--nocapture"], cwd=ROOT, env=env, check=True) ready(primary) # The standby proof deliberately stops and restarts the primary. subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway,graphql,postgres", "--lib", "graphql::delivery::versions::tests::postgres_transactional_coverage_and_snapshot_race", "--", "--ignored", "--nocapture"], cwd=ROOT, env=env, check=True) - subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway,graphql,postgres", "--test", "postgres_repository", "projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks", "--", "--nocapture"], cwd=ROOT, env={**env, "DATABASE_URL": env["GATEWAY_TEST_PRIMARY_URL"]}, check=True) finally: for bridge in bridges: bridge.shutdown(); bridge.server_close() diff --git a/tests/graphql_engine/main.rs b/tests/graphql_engine/main.rs index 9416170e9..e26439b8c 100644 --- a/tests/graphql_engine/main.rs +++ b/tests/graphql_engine/main.rs @@ -160,19 +160,6 @@ async fn duplicate_table_name_errors() { ); } -#[tokio::test] -async fn unknown_column_in_permission_via_grant_ok() { - // grant_all uses all_columns — valid - let schema = simple_schema("Item", "items"); - let manifest = distributed::ReadModelCatalog::new("t").table_schema(schema); - GraphqlEngine::from_schema_catalog(&manifest, pool().await) - .unwrap() - .identity(IdentityConfig::dev_headers()) - .grant_all("user") - .build() - .unwrap(); -} - #[tokio::test] async fn build_handles_bidirectional_relationship_schemas() { let manifest = distributed::ReadModelCatalog::new("t") @@ -188,12 +175,3 @@ async fn build_handles_bidirectional_relationship_schemas() { assert!(sdl.contains("children")); assert!(sdl.contains("parent")); } - -#[tokio::test] -async fn pure_sql_compile_helper() { - use distributed::graphql::naming::root_list_field; - let schema = simple_schema("Item", "items"); - assert_eq!(root_list_field(&schema), "items"); - let sql = distributed::graphql::sdl::graphql_sdl_for_tables(&[schema]).unwrap(); - assert!(sql.contains("type Item")); -} diff --git a/tests/graphql_harden/main.rs b/tests/graphql_harden/main.rs index b019ec9b9..a1957d56e 100644 --- a/tests/graphql_harden/main.rs +++ b/tests/graphql_harden/main.rs @@ -92,7 +92,6 @@ on_each_dialect! { e4_missing_claim_header_is_stable_without_sql_leak, } softskip::{ - default_engine_has_strict_where_on, strict_unknown_where_key_errors, strict_denied_where_column_errors, strict_junk_order_by_column_errors, diff --git a/tests/graphql_harden/softskip.rs b/tests/graphql_harden/softskip.rs index c3b53fb59..e66043d47 100644 --- a/tests/graphql_harden/softskip.rs +++ b/tests/graphql_harden/softskip.rs @@ -17,16 +17,6 @@ use super::common::{ Db, OrderView, }; -/// Default builder is fail-closed. -pub async fn default_engine_has_strict_where_on(db: Db) { - let pool = seed_orders(&db).await; - let engine = engine_all_columns(pool); - assert!( - engine.strict_where(), - "strict_where must default to true for ship API" - ); -} - /// Unknown where key → error under default settings (not silent success). pub async fn strict_unknown_where_key_errors(db: Db) { let pool = seed_orders(&db).await; diff --git a/tests/graphql_oidc_authentik/main.rs b/tests/graphql_oidc_authentik/main.rs index 6a9964de7..39d9fa483 100644 --- a/tests/graphql_oidc_authentik/main.rs +++ b/tests/graphql_oidc_authentik/main.rs @@ -13,14 +13,6 @@ fn e2e_enabled() -> bool { common::gate_enabled("AUTHENTIK_E2E") } -#[tokio::test] -async fn e0_skips_when_not_gated() { - if e2e_enabled() { - return; - } - eprintln!("AUTHENTIK_E2E not set — skip live E1–E8"); -} - #[tokio::test] async fn e1_through_e8_live() { if !e2e_enabled() { diff --git a/tests/graphql_oidc_keycloak/main.rs b/tests/graphql_oidc_keycloak/main.rs index 357edf909..3f924ce62 100644 --- a/tests/graphql_oidc_keycloak/main.rs +++ b/tests/graphql_oidc_keycloak/main.rs @@ -13,14 +13,6 @@ fn e2e_enabled() -> bool { common::gate_enabled("KEYCLOAK_E2E") } -#[tokio::test] -async fn e0_skips_when_not_gated() { - if e2e_enabled() { - return; - } - eprintln!("KEYCLOAK_E2E not set — skip live E1–E8"); -} - #[tokio::test] async fn e1_through_e8_live() { if !e2e_enabled() { diff --git a/tests/graphql_oidc_zitadel/main.rs b/tests/graphql_oidc_zitadel/main.rs index 62e60ecc8..36a37dfe9 100644 --- a/tests/graphql_oidc_zitadel/main.rs +++ b/tests/graphql_oidc_zitadel/main.rs @@ -16,15 +16,6 @@ fn e2e_enabled() -> bool { common::gate_enabled("ZITADEL_E2E") } -/// E0 offline: binary runs without gate. -#[tokio::test] -async fn e0_skips_when_not_gated() { - if e2e_enabled() { - return; - } - eprintln!("ZITADEL_E2E not set — skip live E1–E8 (D12)"); -} - /// Live E1–E8 against real Zitadel issuer + shipped OidcBearer HTTP path. #[tokio::test] async fn e1_through_e8_live() { diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index b15570028..3d1fa777b 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -306,10 +306,6 @@ async fn protocol_fixture_with_retention(db: Db, retention: u64) -> ProtocolFixt } } -async fn protocol_engine_with_rows(db: Db) -> GraphqlEngine { - protocol_fixture_with_rows(db).await.engine -} - fn wire_response(response: async_graphql::Response) -> Value { assert!( !response.is_err(), @@ -424,7 +420,12 @@ fn tamper_first_cursor_token(mut cursors: Value) -> Value { } pub async fn projected_query_emits_exact_record_and_index_revisions_without_key_leaks(db: Db) { - let engine = protocol_engine_with_rows(db).await; + // `_db` holds the Postgres test schema the engine reads from. + let ProtocolFixture { + engine, + repository: _db, + .. + } = protocol_fixture_with_rows(db).await; let response = wire_response( engine .execute( @@ -496,7 +497,12 @@ pub async fn projected_query_emits_exact_record_and_index_revisions_without_key_ } pub async fn count_only_aggregate_emits_no_unselected_node_record_evidence(db: Db) { - let engine = protocol_engine_with_rows(db).await; + // `_db` holds the Postgres test schema the engine reads from. + let ProtocolFixture { + engine, + repository: _db, + .. + } = protocol_fixture_with_rows(db).await; let response = wire_response( engine .execute( @@ -538,7 +544,12 @@ pub async fn count_only_aggregate_emits_no_unselected_node_record_evidence(db: D } pub async fn aggregate_node_aliases_drive_data_and_exact_record_paths(db: Db) { - let engine = protocol_engine_with_rows(db).await; + // `_db` holds the Postgres test schema the engine reads from. + let ProtocolFixture { + engine, + repository: _db, + .. + } = protocol_fixture_with_rows(db).await; let response = wire_response( engine .execute( @@ -1149,7 +1160,12 @@ pub async fn resumed_suffix_coalesces_delete_recreate_and_repeated_upserts(db: D } pub async fn multi_root_causal_query_fails_before_merging_independent_snapshots(db: Db) { - let engine = protocol_engine_with_rows(db).await; + // `_db` holds the Postgres test schema the engine reads from. + let ProtocolFixture { + engine, + repository: _db, + .. + } = protocol_fixture_with_rows(db).await; let response = engine .execute( &user_session(), @@ -1595,7 +1611,12 @@ async fn exercise_query_transport(db: Db, mode: QueryGatewayMode) { } pub async fn unowned_legacy_query_is_explicitly_incomplete_and_still_strips_keys(db: Db) { - let engine = protocol_engine_with_rows(db).await; + // `_db` holds the Postgres test schema the engine reads from. + let ProtocolFixture { + engine, + repository: _db, + .. + } = protocol_fixture_with_rows(db).await; let response = wire_response( engine .execute( diff --git a/tests/graphql_sdl/main.rs b/tests/graphql_sdl/main.rs index 9e3fbc2a0..56fe38b91 100644 --- a/tests/graphql_sdl/main.rs +++ b/tests/graphql_sdl/main.rs @@ -223,19 +223,6 @@ fn manifest_graphql_sdl_method() { assert!(!sdl.contains("OutboxMessage")); } -#[test] -fn capture_sdl_to_scratch() { - let path = std::env::var("GROK_SCRATCH_SDL").unwrap_or_else(|_| "/dev/null".into()); - if path == "/dev/null" { - return; - } - let players = players(); - let weapons = weapons(); - let sdl = graphql_sdl_for_tables(&[players, weapons]).unwrap(); - std::fs::write(&path, &sdl).unwrap(); - assert!(sdl.contains("type PlayerView")); -} - /// Default / SQLite SDL omits PG jsonb comparison operators (weapons has JSON meta). #[test] fn sqlite_sdl_omits_postgres_json_comparison_ops() { diff --git a/tests/in_memory_repository_conformance/main.rs b/tests/in_memory_repository_conformance/main.rs index 0fb627b21..f9fc840c0 100644 --- a/tests/in_memory_repository_conformance/main.rs +++ b/tests/in_memory_repository_conformance/main.rs @@ -3,8 +3,8 @@ mod conformance; use distributed::InMemoryRepository; -async fn repository() -> Option { - Some(InMemoryRepository::new()) +async fn repository() -> Option<((), InMemoryRepository)> { + Some(((), InMemoryRepository::new())) } conformance::repository_conformance_tests!(); diff --git a/tests/legacy_authoring_absence.rs b/tests/legacy_authoring_absence.rs deleted file mode 100644 index 47f573879..000000000 --- a/tests/legacy_authoring_absence.rs +++ /dev/null @@ -1,157 +0,0 @@ -//! Structural gate: competing projector authoring surfaces must stay gone. -//! -//! Checks that the old event-owning projection **proc-macro**, separately -//! authored `command_effects!` / `command_confirmations!`, command-side -//! `.project(...)` selectors, and the public `ProjectionReadModelWorkspace` -//! ORM authoring path stay removed. -//! -//! The declarative `projection!` macro (event→mutation mount) is the current -//! public authoring surface and is expected in `src/lib.rs`. - -#![cfg(feature = "graphql")] - -#[test] -fn declarative_projection_macro_is_public_authoring() { - let lib = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/lib.rs")); - assert!( - lib.contains("macro_rules! projection"), - "declarative projection! must be defined at crate root" - ); - // Old gate rejected any `projection,` substring (false-positive on - // compile_projection). Ensure the proc-macro path stays gone instead. - assert!( - !lib.lines().any(|line| { - let trimmed = line.trim_start(); - !trimmed.starts_with("//") - && (trimmed.contains("pub use distributed_macros::projection") - || trimmed.contains("projection,") - && trimmed.contains("distributed_macros") - && !trimmed.contains("compile_projection")) - }), - "event-owning projection proc-macro must not be re-exported" - ); -} - -#[test] -fn mutation_macro_is_the_public_authoring_export() { - let lib = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/lib.rs")); - assert!( - lib.contains("mutation,"), - "mutation! must remain publicly re-exported" - ); - // Reject live re-exports (comments may still mention the removed macros). - assert!( - !lib.contains("command_effects,") - && !lib.contains("command_effects }") - && !lib.lines().any(|line| { - let trimmed = line.trim_start(); - !trimmed.starts_with("//") && trimmed.contains("command_effects") - }), - "command_effects! must not be re-exported at crate root" - ); - assert!( - !lib.contains("command_confirmations,") - && !lib.contains("command_confirmations }") - && !lib.lines().any(|line| { - let trimmed = line.trim_start(); - !trimmed.starts_with("//") && trimmed.contains("command_confirmations") - }), - "command_confirmations! must not be re-exported at crate root" - ); -} - -#[test] -fn handlers_source_has_no_command_side_project_selector() { - let handlers = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/microsvc/service/handlers.rs" - )); - assert!( - !handlers.contains("pub fn project<"), - "command-side .project(...) selector must be removed from handlers.rs" - ); -} - -#[test] -fn projection_read_model_workspace_is_gone() { - let microsvc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/microsvc/mod.rs")); - assert!( - !microsvc.contains("ProjectionReadModelWorkspace"), - "ProjectionReadModelWorkspace must not be re-exported from microsvc" - ); - let projector_mod = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/microsvc/projector/mod.rs" - )); - assert!( - !projector_mod.contains("graph_workspace"), - "graph_workspace module must be deleted from projector" - ); - assert!( - !std::path::Path::new(concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/microsvc/projector/graph_workspace.rs" - )) - .exists(), - "graph_workspace.rs must not exist" - ); -} - -#[test] -fn dead_effects_authoring_types_are_not_publicly_reexported() { - let graphql_mod = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/graphql/mod.rs")); - let command_mod = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/command/mod.rs")); - for forbidden in [ - "CompiledCommandEffects", - "CompiledConfirmationPlan", - "__command_effects", - "__command_confirmations", - "__effect_upsert", - "__effect_patch", - ] { - assert!( - !graphql_mod.contains(forbidden) && !command_mod.contains(forbidden), - "{forbidden} must not be re-exported from command:: or graphql::" - ); - } -} - -#[test] -fn typed_command_has_no_public_effects_or_confirmations_builder() { - let typed = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/command/typed_command.rs" - )); - assert!( - !typed.contains("pub fn effects("), - "TypedCommand::effects must be removed" - ); - assert!( - !typed.contains("pub fn confirmations("), - "TypedCommand::confirmations must be removed" - ); -} - -#[test] -fn macros_crate_does_not_export_effects_or_projection_macros() { - let macros_lib = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/distributed_macros/src/lib.rs" - )); - assert!( - !macros_lib.contains("pub fn command_effects("), - "command_effects! proc-macro must be removed" - ); - assert!( - !macros_lib.contains("pub fn command_confirmations("), - "command_confirmations! proc-macro must be removed" - ); - assert!( - !macros_lib.contains("pub fn projection("), - "projection! proc-macro must stay removed" - ); - assert!( - macros_lib.contains("mod command_input_defaults"), - "input defaults module must use the honest name" - ); -} diff --git a/tests/nats_transport/main.rs b/tests/nats_transport/main.rs index a2681b6d1..aafe9c2d5 100644 --- a/tests/nats_transport/main.rs +++ b/tests/nats_transport/main.rs @@ -4,13 +4,12 @@ //! JetStream-enabled NATS server. Skips when `NATS_URL` is unset. #![cfg(feature = "nats")] -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use distributed::bus::{ run_source, Handlers, MessagePublisher, NatsBus, NatsJetStreamSource, NatsPublisher, - RunOptions, TransportError, + RetryBackoff, RunOptions, TransportError, }; use distributed::microsvc::{Context, Message, MessageKind, Routes, Service}; use serde_json::json; @@ -577,9 +576,14 @@ async fn undecodable_payload_dead_letters_without_blocking() { /// A long-lived consumer that has gone through several empty fetches must /// still hand a newly published message to its handler immediately; it must /// not sleep out an idle interval or a fetch expiry first. +/// +/// The bound is the fetch expiry itself, not a latency budget: a consumer that +/// waited for its open fetch to expire, or idled between fetches, would take up +/// to one expiry, while a prompt one is a broker round trip. #[tokio::test] async fn message_published_after_empty_fetches_is_delivered_promptly() { let Some(url) = nats_url() else { return }; + const FETCH_EXPIRY: Duration = Duration::from_secs(2); let subject = unique("latency.idle"); let source = NatsJetStreamSource::connect( &url, @@ -589,7 +593,7 @@ async fn message_published_after_empty_fetches_is_delivered_promptly() { ) .await .expect("connect source") - .with_fetch_timeout(Duration::from_millis(500)); + .with_fetch_timeout(FETCH_EXPIRY); let handled = Arc::new(Mutex::new(None::)); let record = handled.clone(); let router = Arc::new(Handlers::new().on_event(&subject, move |_: &Message| { @@ -600,15 +604,15 @@ async fn message_published_after_empty_fetches_is_delivered_promptly() { async { Ok(()) } })); let consumer = tokio::spawn(run_source(router, source, RunOptions::default())); - // Several empty 500 ms fetches expire first. - tokio::time::sleep(Duration::from_millis(1_300)).await; + // Two empty fetches expire first; the message lands mid-way through a third. + tokio::time::sleep(FETCH_EXPIRY * 2 + FETCH_EXPIRY / 4).await; let publisher = NatsPublisher::connect(&url).await.expect("publisher"); let published = std::time::Instant::now(); publisher .publish(Message::new(&subject, MessageKind::Event, b"{}".to_vec()).with_id("late")) .await .expect("publish"); - let latency = tokio::time::timeout(Duration::from_secs(3), async { + let latency = tokio::time::timeout(FETCH_EXPIRY * 5, async { loop { if let Some(at) = *handled.lock().unwrap() { return at.duration_since(published); @@ -620,13 +624,18 @@ async fn message_published_after_empty_fetches_is_delivered_promptly() { .expect("idle consumer delivered the message"); consumer.abort(); assert!( - latency < Duration::from_millis(250), - "idle delivery took {latency:?}" + latency < FETCH_EXPIRY, + "idle delivery took {latency:?}, as long as a fetch expiry of {FETCH_EXPIRY:?}" ); } -/// A message that keeps failing retryably is redelivered with growing -/// delays instead of a hot loop, and a newer message is not delayed by it. +/// A message that keeps failing retryably is redelivered after a delay +/// instead of in a hot loop, and a newer message is not held behind it. +/// +/// Asserted by order, not by latency: with a 2 s first redelivery delay, the +/// fresh message published 300 ms after the poison must be handled before the +/// poison's second attempt. A hot NAK loop puts many poison attempts first; a +/// consumer that serialises behind the poison puts the fresh one after them. #[tokio::test] async fn retryable_nack_backs_off_without_starving_newer_messages() { let Some(url) = nats_url() else { return }; @@ -640,20 +649,13 @@ async fn retryable_nack_backs_off_without_starving_newer_messages() { .await .expect("connect source") .with_fetch_timeout(Duration::from_millis(500)); - let poison_attempts = Arc::new(AtomicUsize::new(0)); - let fresh_at = Arc::new(Mutex::new(None::)); - let (attempts, fresh) = (poison_attempts.clone(), fresh_at.clone()); + let handled = Arc::new(Mutex::new(Vec::::new())); + let log = handled.clone(); let router = Arc::new( Handlers::new().on_event(&subject, move |message: &Message| { - let poison = message.id() == Some("poison"); - if poison { - attempts.fetch_add(1, Ordering::SeqCst); - } else { - fresh - .lock() - .unwrap() - .get_or_insert_with(std::time::Instant::now); - } + let id = message.id().unwrap_or_default().to_owned(); + let poison = id == "poison"; + log.lock().unwrap().push(id); async move { if poison { Err(TransportError::retryable("rejected until repaired")) @@ -663,50 +665,55 @@ async fn retryable_nack_backs_off_without_starving_newer_messages() { } }), ); - let consumer = tokio::spawn(run_source(router, source, RunOptions::default())); + let mut options = RunOptions::default(); + options.backoff = RetryBackoff::new(Duration::from_secs(2), Duration::from_secs(2)); + let consumer = tokio::spawn(run_source(router, source, options)); let publisher = NatsPublisher::connect(&url).await.expect("publisher"); publisher .publish(Message::new(&subject, MessageKind::Event, b"{}".to_vec()).with_id("poison")) .await .expect("publish poison"); tokio::time::sleep(Duration::from_millis(300)).await; - let published = std::time::Instant::now(); publisher .publish(Message::new(&subject, MessageKind::Event, b"{}".to_vec()).with_id("fresh")) .await .expect("publish fresh"); - tokio::time::sleep(Duration::from_millis(1_200)).await; + let order = tokio::time::timeout(Duration::from_secs(15), async { + loop { + let order = handled.lock().unwrap().clone(); + if order.iter().filter(|id| *id == "poison").count() >= 2 { + return order; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the poison message is retried"); consumer.abort(); - let fresh_latency = fresh_at - .lock() - .unwrap() - .expect("fresh message handled") - .duration_since(published); - let attempts = poison_attempts.load(Ordering::SeqCst); - assert!( - fresh_latency < Duration::from_millis(250), - "fresh message waited {fresh_latency:?}" - ); - // 50 ms doubling over ~1.5 s allows at most ~6 attempts; an immediate - // NAK loop redelivers hundreds of times in the same window. - assert!( - (2..=8).contains(&attempts), - "poison retried {attempts} times: retries must continue but back off" + assert_eq!( + order[..3], + ["poison", "fresh", "poison"], + "the fresh message runs between the poison's first attempt and its delayed retry" ); } /// With the process policy in its own lane, a slow projection route for an /// earlier message does not delay the policy for a later message, and every /// delivery is still acknowledged exactly once after all of its lanes ran. +/// +/// The slow projection for `m1` waits until the policy for `m2` has run. If +/// the process lane waited for the default lane, neither would finish and the +/// deliveries would stay pending; no timing margin is involved. #[tokio::test] async fn slow_default_lane_does_not_delay_process_lane_over_jetstream() { let Some(url) = nats_url() else { return }; let namespace = unique("lanes").to_lowercase(); let bus = nats_bus(&url, &namespace, "lanes").await; - let started = std::time::Instant::now(); - let projection_done = Arc::new(Mutex::new(Vec::<(String, Duration)>::new())); - let policy_done = Arc::new(Mutex::new(Vec::<(String, Duration)>::new())); + let m2_policy_ran = Arc::new(tokio::sync::Notify::new()); + let projection_done = Arc::new(Mutex::new(Vec::::new())); + let policy_done = Arc::new(Mutex::new(Vec::::new())); let (projected, policed) = (projection_done.clone(), policy_done.clone()); + let (wait_for_m2, signal_m2) = (m2_policy_ran.clone(), m2_policy_ran.clone()); let service = Service::new() .named("lanes") .routes( @@ -716,12 +723,13 @@ async fn slow_default_lane_does_not_delay_process_lane_over_jetstream() { .handle(move |ctx: &Context<()>| { let id = ctx.message().id().unwrap_or_default().to_owned(); let projected = projected.clone(); + let wait_for_m2 = wait_for_m2.clone(); async move { if id == "m1" { // A slow projection / external effect. - tokio::time::sleep(Duration::from_millis(1_500)).await; + wait_for_m2.notified().await; } - projected.lock().unwrap().push((id, started.elapsed())); + projected.lock().unwrap().push(id); Ok(json!({})) } }), @@ -734,8 +742,13 @@ async fn slow_default_lane_does_not_delay_process_lane_over_jetstream() { .handle(move |ctx: &Context<()>| { let id = ctx.message().id().unwrap_or_default().to_owned(); let policed = policed.clone(); + let signal_m2 = signal_m2.clone(); async move { - policed.lock().unwrap().push((id, started.elapsed())); + if id == "m2" { + // `notify_one` stores a permit if m1 is not yet waiting. + signal_m2.notify_one(); + } + policed.lock().unwrap().push(id); Ok(json!({})) } }), @@ -751,32 +764,18 @@ async fn slow_default_lane_does_not_delay_process_lane_over_jetstream() { .await .expect("publish"); } - tokio::time::sleep(Duration::from_millis(2_500)).await; + tokio::time::timeout(Duration::from_secs(20), async { + while projection_done.lock().unwrap().len() < 2 || policy_done.lock().unwrap().len() < 2 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the process lane ran m2 while m1's projection waited for it"); consumer.abort(); let policed = policy_done.lock().unwrap().clone(); let projected = projection_done.lock().unwrap().clone(); - assert_eq!( - policed - .iter() - .map(|(id, _)| id.as_str()) - .collect::>(), - ["m1", "m2"], - "process lane keeps delivery order" - ); - assert_eq!( - projected - .iter() - .map(|(id, _)| id.as_str()) - .collect::>(), - ["m1", "m2"], - "default lane keeps delivery order" - ); - let m2_policy = policed[1].1; - let m1_projection = projected[0].1; - assert!( - m2_policy + Duration::from_millis(1_000) < m1_projection, - "process lane waited for the slow lane: m2 policy at {m2_policy:?}, m1 projection at {m1_projection:?}" - ); + assert_eq!(policed, ["m1", "m2"], "process lane keeps delivery order"); + assert_eq!(projected, ["m1", "m2"], "default lane keeps delivery order"); // Both deliveries were acknowledged: nothing pending or awaiting ack. let stream = bus.ensure_stream().await.expect("stream"); let mut durable = stream diff --git a/tests/persistent_repository_conformance/mod.rs b/tests/persistent_repository_conformance/mod.rs index 6a0961b18..0e3259d83 100644 --- a/tests/persistent_repository_conformance/mod.rs +++ b/tests/persistent_repository_conformance/mod.rs @@ -16,8 +16,10 @@ pub mod outbox_support; /// /// The including test target must: /// - declare this module as `mod conformance;` -/// - define `async fn repository() -> Option`, returning `None` to -/// skip (e.g. when the backing service's env var is unset). `Backend` must be +/// - define `async fn repository() -> Option<(Fixture, Backend)>`, returning +/// `None` to skip (e.g. when the backing service's env var is unset). +/// `Fixture` is held until the test ends (a Postgres test schema, dropped +/// with it; `()` when there is nothing to clean up). `Backend` must be /// `Clone`, expose an `outbox_store()` accessor, and — for SQL backends — /// already have the read-model conformance table bootstrapped (see /// [`read_models::conformance_table_registry`]). @@ -28,7 +30,7 @@ macro_rules! repository_conformance_tests { () => { #[tokio::test] async fn aggregate_checkout_flow_persists_reloaded_state() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::scenario::aggregate_checkout_flow_persists_reloaded_state(repo).await; @@ -36,7 +38,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn get_all_and_commit_all_round_trip() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::scenario::get_all_and_commit_all_round_trip(repo).await; @@ -44,7 +46,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn multi_stream_conflict_rolls_back_other_stream_and_snapshot() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::scenario::multi_stream_conflict_rolls_back_other_stream_and_snapshot(repo) @@ -53,7 +55,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn duplicate_stream_identity_is_rejected_before_write() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::scenario::duplicate_stream_identity_is_rejected_before_write(repo).await; @@ -61,7 +63,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn metadata_round_trips() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::scenario::metadata_round_trips(repo).await; @@ -69,7 +71,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn unsupported_codec_is_rejected_on_write() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::scenario::unsupported_codec_is_rejected_on_write(repo).await; @@ -77,7 +79,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn snapshots_use_full_stream_identity() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::scenario::snapshots_use_full_stream_identity(repo).await; @@ -85,7 +87,7 @@ macro_rules! repository_conformance_tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn racing_commits_one_wins_one_conflicts() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::scenario::racing_commits_one_wins_one_conflicts(repo, 8).await; @@ -93,7 +95,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn standalone_relational_write_plan_persists_row() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::read_models::standalone_relational_write_plan_persists_row(repo).await; @@ -101,7 +103,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn aggregate_commit_persists_read_model_plan() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::read_models::aggregate_commit_persists_read_model_plan(repo).await; @@ -109,7 +111,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn aggregate_conflict_rolls_back_read_model_plan() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::read_models::aggregate_conflict_rolls_back_read_model_plan(repo).await; @@ -117,7 +119,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn high_level_outbox_commit_persists_row_without_stream() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::high_level_outbox_commit_persists_row_without_stream( @@ -129,7 +131,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn duplicate_outbox_insert_rolls_back_aggregate() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::duplicate_outbox_insert_rolls_back_aggregate(repo).await; @@ -137,7 +139,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn aggregate_conflict_rolls_back_outbox() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::aggregate_conflict_rolls_back_outbox( @@ -149,7 +151,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn worker_claim_complete_and_retry_lifecycle() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::worker_claim_complete_and_retry_lifecycle( @@ -161,7 +163,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn worker_claim_by_ids_claims_only_requested() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::worker_claim_by_ids_claims_only_requested( @@ -173,7 +175,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn expired_outbox_lease_is_reclaimed_by_second_worker() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::expired_outbox_lease_is_reclaimed_by_second_worker( @@ -185,7 +187,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn publish_failure_after_commit_retains_outbox_row_until_delivered() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::publish_failure_after_commit_retains_outbox_row_until_delivered( @@ -197,7 +199,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn broker_outage_keeps_the_backlog_pending_with_growing_delay() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::broker_outage_keeps_the_backlog_pending_with_growing_delay( @@ -209,7 +211,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn failed_row_is_requeued_and_delivered() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::failed_row_is_requeued_and_delivered( @@ -221,7 +223,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn worker_completes_claims_in_one_batch() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::outbox::worker_completes_claims_in_one_batch( @@ -233,7 +235,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn consumer_inbox_records_dedupes_and_fences_with_real_effects() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::inbox::inbox_records_dedupes_and_fences_with_real_effects( @@ -245,7 +247,7 @@ macro_rules! repository_conformance_tests { #[tokio::test] async fn consumer_inbox_rejects_empty_receipt() { - let Some(repo) = repository().await else { + let Some((_fixture, repo)) = repository().await else { return; }; conformance::inbox::inbox_rejects_empty_receipt(repo).await; diff --git a/tests/postgres_repository/main.rs b/tests/postgres_repository/main.rs index 1ed9f1271..378089baf 100644 --- a/tests/postgres_repository/main.rs +++ b/tests/postgres_repository/main.rs @@ -20,39 +20,6 @@ use distributed::{ TransactionalCommit, }; use serde::{Deserialize, Serialize}; -use sqlx::migrate::{Migration, MigrationType, Migrator}; - -fn legacy_postgres_migrator() -> Migrator { - Migrator::with_migrations(vec![ - Migration::new( - 1, - "initial".into(), - MigrationType::Simple, - sqlx::SqlSafeStr::into_sql_str(include_str!( - "../../migrations/postgres/0001_initial.sql" - )), - false, - ), - Migration::new( - 2, - "command ledger".into(), - MigrationType::Simple, - sqlx::SqlSafeStr::into_sql_str(include_str!( - "../../migrations/postgres/0002_command_ledger.sql" - )), - false, - ), - Migration::new( - 3, - "projection protocol".into(), - MigrationType::Simple, - sqlx::SqlSafeStr::into_sql_str(include_str!( - "../../migrations/postgres/0003_projection_protocol.sql" - )), - false, - ), - ]) -} #[derive(Default)] struct Counter { @@ -185,74 +152,6 @@ async fn migration_is_idempotent_and_uses_postgres_column_types() { assert!(processed_messages_table.is_none()); } -#[tokio::test] -async fn projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks() { - let Some(schema) = postgres::PostgresTestSchema::create_from_env( - "postgres_ledger_upgrade", - "Postgres command-ledger upgrade test", - ) - .await - else { - return; - }; - let repo = schema.repository_unmigrated().await; - legacy_postgres_migrator().run(repo.pool()).await.unwrap(); - - sqlx::query( - r#" - INSERT INTO command_ledger ( - service_id, principal_partition, command_id, command_name, - command_contract_hash, input_hash, state, causation_id, - attempt_number, outcome, completed_at, retention_expires_at - ) VALUES ($1, $2, $3, $4, - decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), - 'projected', $5, 1, '{}'::jsonb, now(), now() + interval '1 day') - "#, - ) - .bind("service") - .bind("principal") - .bind("command") - .bind("todo.complete") - .bind("cause") - .execute(repo.pool()) - .await - .unwrap(); - - repo.migrate().await.unwrap(); - - let state: String = sqlx::query_scalar( - "SELECT state FROM command_ledger WHERE service_id = 'service' AND command_id = 'command'", - ) - .fetch_one(repo.pool()) - .await - .unwrap(); - assert_eq!(state, "atomic"); - - let latest_version: i64 = sqlx::query_scalar("SELECT MAX(version) FROM _sqlx_migrations") - .fetch_one(repo.pool()) - .await - .unwrap(); - assert_eq!(latest_version, 14); - - let invalid_service = sqlx::query( - r#" - INSERT INTO command_ledger ( - service_id, principal_partition, command_id, command_name, - command_contract_hash, input_hash, state, causation_id, - attempt_number, outcome, completed_at, retention_expires_at - ) VALUES ('', 'principal', 'invalid-service', 'todo.complete', - decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), - 'atomic', 'invalid-service-cause', 1, '{}'::jsonb, now(), now() + interval '1 day') - "#, - ) - .execute(repo.pool()) - .await; - assert!( - invalid_service.is_err(), - "non-empty service CHECK must survive migration" - ); -} - #[tokio::test] async fn aggregate_stream_round_trips_with_metadata() { let Some((_schema, repo)) = repository().await else { diff --git a/tests/postgres_repository_conformance/main.rs b/tests/postgres_repository_conformance/main.rs index 52f666013..62897b1aa 100644 --- a/tests/postgres_repository_conformance/main.rs +++ b/tests/postgres_repository_conformance/main.rs @@ -7,7 +7,7 @@ mod postgres; use distributed::PostgresRepository; -async fn repository() -> Option { +async fn repository() -> Option<(postgres::PostgresTestSchema, PostgresRepository)> { let schema = postgres::PostgresTestSchema::create_from_env( "pg_conformance", "Postgres conformance test", @@ -17,7 +17,7 @@ async fn repository() -> Option { repo.bootstrap_table_schema_for_dev(&conformance::read_models::conformance_table_registry()) .await .expect("read-model conformance table should bootstrap"); - Some(repo) + Some((schema, repo)) } conformance::repository_conformance_tests!(); diff --git a/tests/queued_repo/main.rs b/tests/queued_repo/main.rs index 9624b3955..6db0b44db 100644 --- a/tests/queued_repo/main.rs +++ b/tests/queued_repo/main.rs @@ -50,7 +50,10 @@ async fn seed(repo: &QueuedCounterRepo, id: &str) { repo.commit(&mut counter).await.unwrap(); } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +// Paused time: the runtime advances the clock only once every task is idle, +// so after the sleep task 2 has provably run as far as it can — it is parked +// on the lock, not merely not yet scheduled. +#[tokio::test(start_paused = true)] async fn second_load_waits_until_first_commits() { let repo = queued_repo(); seed(&repo, "c1").await; @@ -71,7 +74,7 @@ async fn second_load_waits_until_first_commits() { tokio::time::sleep(Duration::from_millis(50)).await; assert!( - !acquired.load(Ordering::SeqCst), + !acquired.load(Ordering::SeqCst) && !task2.is_finished(), "the second load must block while the first holds the lock" ); diff --git a/tests/read_model_metadata/main.rs b/tests/read_model_metadata/main.rs index be1ab12ac..d93ace93e 100644 --- a/tests/read_model_metadata/main.rs +++ b/tests/read_model_metadata/main.rs @@ -393,3 +393,77 @@ fn explicit_overrides_disambiguate_singular_names_ending_in_s() { ("statuses", "statuses", "buses", "buses") ); } + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] +#[table("counter_views")] +struct ExplicitIdView { + id: String, + #[readmodel(id)] + counter_id: String, + #[unique("uq_counter_views_slug")] + slug: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] +#[table("reordered_relationships")] +struct ReorderedRelationships { + #[id] + id: String, + target_tenant: String, + target_slug: Option, + #[readmodel( + references = "tenant_id,slug", + foreign_key = "target_tenant,target_slug", + belongs_to = "DirectTableView" + )] + target: Option, + #[readmodel(foreign_key = "player_id", has_many = "PlayerWeapon")] + weapons: Vec, + #[readmodel(through = "links", foreign_key = "id", many_to_many = "Player")] + players: Vec, +} + +#[test] +fn an_explicit_id_field_wins_over_a_field_named_id() { + let view = ExplicitIdView { + id: "row".into(), + counter_id: "counter-1".into(), + slug: "first".into(), + }; + assert_eq!(view.id(), "counter-1"); + assert_eq!(ExplicitIdView::schema().primary_key.columns, ["counter_id"]); + assert!(ExplicitIdView::schema().indexes.iter().any(|index| { + index.name.as_deref() == Some("uq_counter_views_slug") + && index.columns == ["slug"] + && index.unique + })); +} + +#[test] +fn relationship_attributes_mean_the_same_in_any_order() { + let schema = ReorderedRelationships::schema(); + let relation = |field: &str| { + schema + .relationships + .iter() + .find(|relation| relation.field_name == field) + .unwrap_or_else(|| panic!("missing relationship {field}")) + }; + + let target = relation("target"); + assert_eq!(target.kind, RelationshipKind::BelongsTo); + assert_eq!(target.references.as_deref(), Some("tenant_id,slug")); + assert_eq!( + target.foreign_key.as_deref(), + Some("target_tenant,target_slug") + ); + + let weapons = relation("weapons"); + assert_eq!(weapons.kind, RelationshipKind::HasMany); + assert_eq!(weapons.foreign_key.as_deref(), Some("player_id")); + + let players = relation("players"); + assert_eq!(players.kind, RelationshipKind::ManyToMany); + assert_eq!(players.through.as_deref(), Some("links")); + assert_eq!(players.foreign_key.as_deref(), Some("id")); +} diff --git a/tests/sagas/main.rs b/tests/sagas/main.rs index 0669be0d0..53c8c3dbe 100644 --- a/tests/sagas/main.rs +++ b/tests/sagas/main.rs @@ -9,5 +9,4 @@ mod commands; mod handlers; mod microsvc_saga; -mod orchestration; mod order; diff --git a/tests/sagas/orchestration.rs b/tests/sagas/orchestration.rs deleted file mode 100644 index 0efb34b55..000000000 --- a/tests/sagas/orchestration.rs +++ /dev/null @@ -1,455 +0,0 @@ -//! Saga Orchestration Tests -//! -//! ## The Order Fulfillment Saga -//! -//! This example implements an order fulfillment process: -//! -//! 1. **Start**: Saga receives order details -//! 2. **Reserve Inventory**: Reserve items from inventory -//! 3. **Process Payment**: Charge the customer -//! 4. **Complete**: Mark order as fulfilled -//! -//! If any step fails, the saga compensates by: -//! - Releasing inventory reservations -//! - Refunding payments -//! - Cancelling the order - -use super::order::{ - Inventory, Order, OrderFulfillmentSaga, OrderItem, OrderStatus, Payment, PaymentStatus, - SagaStatus, -}; -use distributed::{AggregateBuilder, InMemoryRepository}; - -#[tokio::test] -async fn saga_happy_path_completes_order() { - // Set up repositories for each aggregate type - let order_repo = InMemoryRepository::new().aggregate::(); - let inventory_repo = InMemoryRepository::new().aggregate::(); - let payment_repo = InMemoryRepository::new().aggregate::(); - let saga_repo = InMemoryRepository::new().aggregate::(); - - // === Setup: Initialize inventory === - let mut widget_inventory = Inventory::new(); - widget_inventory - .initialize("WIDGET-001".to_string(), 100) - .unwrap(); - inventory_repo.commit(&mut widget_inventory).await.unwrap(); - - // === Step 1: Create Order === - let order_id = "order-123".to_string(); - let items = vec![OrderItem { - sku: "WIDGET-001".to_string(), - quantity: 5, - price_cents: 1000, - }]; - - let mut order = Order::new(); - order - .create(order_id.clone(), "customer-456".to_string(), items.clone()) - .unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // === Step 2: Start Saga === - let mut order_fulfillment_saga = OrderFulfillmentSaga::new(); - order_fulfillment_saga - .start( - "saga-123".to_string(), - order_id.clone(), - "customer-456".to_string(), - items, - 5000, // 5 widgets * 1000 cents - ) - .unwrap(); - assert_eq!(order_fulfillment_saga.status(), SagaStatus::Started); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // === Step 3: Reserve Inventory === - let mut inventory = inventory_repo.get("WIDGET-001").await.unwrap().unwrap(); - assert!(inventory.can_reserve(5)); - inventory.reserve(order_id.clone(), 5).unwrap(); - inventory_repo.commit(&mut inventory).await.unwrap(); - - // Update saga state - let mut order_fulfillment_saga = saga_repo.get("saga-123").await.unwrap().unwrap(); - order_fulfillment_saga.inventory_reserved().unwrap(); - assert_eq!( - order_fulfillment_saga.status(), - SagaStatus::InventoryReserved - ); - assert!(order_fulfillment_saga.compensation().inventory_reserved); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // Update order state - let mut order = order_repo.get(&order_id).await.unwrap().unwrap(); - order.mark_inventory_reserved().unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // === Step 4: Process Payment === - let mut payment = Payment::new(); - payment - .initiate("payment-789".to_string(), order_id.clone(), 5000) - .unwrap(); - payment.authorize("txn-abc123".to_string()).unwrap(); - payment.capture().unwrap(); - assert!(payment.is_successful()); - payment_repo.commit(&mut payment).await.unwrap(); - - // Update saga state - let mut order_fulfillment_saga = saga_repo.get("saga-123").await.unwrap().unwrap(); - order_fulfillment_saga.payment_succeeded().unwrap(); - assert_eq!( - order_fulfillment_saga.status(), - SagaStatus::PaymentProcessed - ); - assert!(order_fulfillment_saga.compensation().payment_processed); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // Update order state - let mut order = order_repo.get(&order_id).await.unwrap().unwrap(); - order.mark_payment_processed().unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // === Step 5: Complete Saga === - let mut order_fulfillment_saga = saga_repo.get("saga-123").await.unwrap().unwrap(); - order_fulfillment_saga.complete().unwrap(); - assert_eq!(order_fulfillment_saga.status(), SagaStatus::Completed); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // Commit the inventory reservation (no longer reversible) - let mut inventory = inventory_repo.get("WIDGET-001").await.unwrap().unwrap(); - inventory.commit_reservation(order_id.clone()).unwrap(); - inventory_repo.commit(&mut inventory).await.unwrap(); - - // Complete the order - let mut order = order_repo.get(&order_id).await.unwrap().unwrap(); - order.complete().unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // === Verify Final State === - let final_order_fulfillment_saga = saga_repo.get("saga-123").await.unwrap().unwrap(); - assert_eq!(final_order_fulfillment_saga.status(), SagaStatus::Completed); - assert!(final_order_fulfillment_saga.is_complete()); - - let final_order = order_repo.get(&order_id).await.unwrap().unwrap(); - assert_eq!(final_order.status(), OrderStatus::Completed); - - let final_inventory = inventory_repo.get("WIDGET-001").await.unwrap().unwrap(); - assert_eq!(final_inventory.available(), 95); // 100 - 5 - assert_eq!(final_inventory.reserved(), 0); - assert!(final_inventory.reservation_for_order(&order_id).is_none()); -} - -#[tokio::test] -async fn saga_compensates_on_payment_failure() { - // Set up repositories - let order_repo = InMemoryRepository::new().aggregate::(); - let inventory_repo = InMemoryRepository::new().aggregate::(); - let payment_repo = InMemoryRepository::new().aggregate::(); - let saga_repo = InMemoryRepository::new().aggregate::(); - - // === Setup === - let mut widget_inventory = Inventory::new(); - widget_inventory - .initialize("WIDGET-002".to_string(), 50) - .unwrap(); - inventory_repo.commit(&mut widget_inventory).await.unwrap(); - - let order_id = "order-fail-456".to_string(); - let items = vec![OrderItem { - sku: "WIDGET-002".to_string(), - quantity: 10, - price_cents: 500, - }]; - - let mut order = Order::new(); - order - .create(order_id.clone(), "customer-789".to_string(), items.clone()) - .unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // === Start Saga === - let mut order_fulfillment_saga = OrderFulfillmentSaga::new(); - order_fulfillment_saga - .start( - "saga-fail-456".to_string(), - order_id.clone(), - "customer-789".to_string(), - items, - 5000, - ) - .unwrap(); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // === Reserve Inventory (succeeds) === - let mut inventory = inventory_repo.get("WIDGET-002").await.unwrap().unwrap(); - inventory.reserve(order_id.clone(), 10).unwrap(); - inventory_repo.commit(&mut inventory).await.unwrap(); - - let mut order_fulfillment_saga = saga_repo.get("saga-fail-456").await.unwrap().unwrap(); - order_fulfillment_saga.inventory_reserved().unwrap(); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - let mut order = order_repo.get(&order_id).await.unwrap().unwrap(); - order.mark_inventory_reserved().unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // Verify inventory is reserved - let inventory = inventory_repo.get("WIDGET-002").await.unwrap().unwrap(); - assert_eq!(inventory.available(), 40); // 50 - 10 - assert_eq!(inventory.reserved(), 10); - - // === Payment Fails === - let mut payment = Payment::new(); - payment - .initiate("payment-fail-xyz".to_string(), order_id.clone(), 5000) - .unwrap(); - payment.fail("Insufficient funds".to_string()).unwrap(); - assert!(!payment.is_successful()); - assert_eq!(payment.status(), PaymentStatus::Failed); - payment_repo.commit(&mut payment).await.unwrap(); - - // === Saga enters compensation mode === - let mut order_fulfillment_saga = saga_repo.get("saga-fail-456").await.unwrap().unwrap(); - order_fulfillment_saga - .step_failed("Payment".to_string(), "Insufficient funds".to_string()) - .unwrap(); - assert_eq!(order_fulfillment_saga.status(), SagaStatus::Compensating); - assert!(order_fulfillment_saga.needs_inventory_compensation()); - assert!(!order_fulfillment_saga.needs_payment_compensation()); // Payment wasn't successful - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // === Compensate: Release Inventory === - let mut inventory = inventory_repo.get("WIDGET-002").await.unwrap().unwrap(); - inventory.release_reservation(order_id.clone()).unwrap(); - inventory_repo.commit(&mut inventory).await.unwrap(); - - let mut order_fulfillment_saga = saga_repo.get("saga-fail-456").await.unwrap().unwrap(); - order_fulfillment_saga.inventory_compensated().unwrap(); - assert!(!order_fulfillment_saga.needs_inventory_compensation()); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // === Cancel Order === - let mut order = order_repo.get(&order_id).await.unwrap().unwrap(); - order - .cancel("Payment failed: Insufficient funds".to_string()) - .unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // === Mark Saga as Failed === - let mut order_fulfillment_saga = saga_repo.get("saga-fail-456").await.unwrap().unwrap(); - order_fulfillment_saga.mark_failed().unwrap(); - assert_eq!(order_fulfillment_saga.status(), SagaStatus::Failed); - assert!(order_fulfillment_saga.is_complete()); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // === Verify Final State === - let final_order_fulfillment_saga = saga_repo.get("saga-fail-456").await.unwrap().unwrap(); - assert_eq!(final_order_fulfillment_saga.status(), SagaStatus::Failed); - assert_eq!( - final_order_fulfillment_saga.failure_reason(), - Some("Payment: Insufficient funds") - ); - - let final_order = order_repo.get(&order_id).await.unwrap().unwrap(); - assert_eq!(final_order.status(), OrderStatus::Cancelled); - - // Inventory should be restored - let final_inventory = inventory_repo.get("WIDGET-002").await.unwrap().unwrap(); - assert_eq!(final_inventory.available(), 50); // Back to original - assert_eq!(final_inventory.reserved(), 0); -} - -#[tokio::test] -async fn saga_compensates_on_inventory_failure() { - // Set up repositories - let order_repo = InMemoryRepository::new().aggregate::(); - let inventory_repo = InMemoryRepository::new().aggregate::(); - let saga_repo = InMemoryRepository::new().aggregate::(); - - // === Setup: Low inventory === - let mut widget_inventory = Inventory::new(); - widget_inventory - .initialize("WIDGET-003".to_string(), 5) - .unwrap(); // Only 5 available - inventory_repo.commit(&mut widget_inventory).await.unwrap(); - - let order_id = "order-inv-fail-789".to_string(); - let items = vec![OrderItem { - sku: "WIDGET-003".to_string(), - quantity: 10, // Trying to order 10 - price_cents: 500, - }]; - - let mut order = Order::new(); - order - .create(order_id.clone(), "customer-xyz".to_string(), items.clone()) - .unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // === Start Saga === - let mut order_fulfillment_saga = OrderFulfillmentSaga::new(); - order_fulfillment_saga - .start( - "saga-inv-fail".to_string(), - order_id.clone(), - "customer-xyz".to_string(), - items, - 5000, - ) - .unwrap(); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // === Try to Reserve Inventory (fails - not enough stock) === - let inventory = inventory_repo.get("WIDGET-003").await.unwrap().unwrap(); - assert!(!inventory.can_reserve(10)); // Can't reserve 10 when only 5 available - - // Saga fails at first step - let mut order_fulfillment_saga = saga_repo.get("saga-inv-fail").await.unwrap().unwrap(); - order_fulfillment_saga - .step_failed( - "Inventory".to_string(), - "Insufficient stock for WIDGET-003".to_string(), - ) - .unwrap(); - assert_eq!(order_fulfillment_saga.status(), SagaStatus::Compensating); - // No compensation needed - nothing was reserved yet - assert!(!order_fulfillment_saga.needs_inventory_compensation()); - assert!(!order_fulfillment_saga.needs_payment_compensation()); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // Cancel order - let mut order = order_repo.get(&order_id).await.unwrap().unwrap(); - order.cancel("Insufficient stock".to_string()).unwrap(); - order_repo.commit(&mut order).await.unwrap(); - - // Mark saga as failed (no compensation needed) - let mut order_fulfillment_saga = saga_repo.get("saga-inv-fail").await.unwrap().unwrap(); - order_fulfillment_saga.mark_failed().unwrap(); - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // === Verify Final State === - let final_order_fulfillment_saga = saga_repo.get("saga-inv-fail").await.unwrap().unwrap(); - assert_eq!(final_order_fulfillment_saga.status(), SagaStatus::Failed); - assert!(final_order_fulfillment_saga.is_complete()); - - let final_order = order_repo.get(&order_id).await.unwrap().unwrap(); - assert_eq!(final_order.status(), OrderStatus::Cancelled); - - // Inventory unchanged - let final_inventory = inventory_repo.get("WIDGET-003").await.unwrap().unwrap(); - assert_eq!(final_inventory.available(), 5); - assert_eq!(final_inventory.reserved(), 0); -} - -#[tokio::test] -async fn saga_is_replayable_from_events() { - let saga_repo = InMemoryRepository::new().aggregate::(); - - let items = vec![OrderItem { - sku: "WIDGET-REPLAY".to_string(), - quantity: 3, - price_cents: 1500, - }]; - - // Create and progress a saga - let mut order_fulfillment_saga = OrderFulfillmentSaga::new(); - order_fulfillment_saga - .start( - "saga-replay".to_string(), - "order-replay".to_string(), - "customer-replay".to_string(), - items, - 4500, - ) - .unwrap(); - order_fulfillment_saga.inventory_reserved().unwrap(); - order_fulfillment_saga.payment_succeeded().unwrap(); - - // Commit to repository - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - - // Retrieve and verify state is reconstructed from events - let restored = saga_repo.get("saga-replay").await.unwrap().unwrap(); - - assert_eq!(restored.order_id(), "order-replay"); - assert_eq!(restored.customer_id(), "customer-replay"); - assert_eq!(restored.total_cents(), 4500); - assert_eq!(restored.status(), SagaStatus::PaymentProcessed); - assert!(restored.compensation().inventory_reserved); - assert!(restored.compensation().payment_processed); - - // Can continue from restored state - let mut restored = restored; - restored.complete().unwrap(); - saga_repo.commit(&mut restored).await.unwrap(); - - let final_order_fulfillment_saga = saga_repo.get("saga-replay").await.unwrap().unwrap(); - assert_eq!(final_order_fulfillment_saga.status(), SagaStatus::Completed); -} - -#[tokio::test] -async fn saga_tracks_compensation_state_correctly() { - let saga_repo = InMemoryRepository::new().aggregate::(); - - let items = vec![OrderItem { - sku: "WIDGET-COMP".to_string(), - quantity: 1, - price_cents: 100, - }]; - - // Progress saga through multiple steps - let mut order_fulfillment_saga = OrderFulfillmentSaga::new(); - order_fulfillment_saga - .start( - "saga-comp".to_string(), - "order-comp".to_string(), - "customer-comp".to_string(), - items, - 100, - ) - .unwrap(); - - // Initially no compensation needed - assert!(!order_fulfillment_saga.compensation().inventory_reserved); - assert!(!order_fulfillment_saga.compensation().payment_processed); - - // After inventory reserved - order_fulfillment_saga.inventory_reserved().unwrap(); - assert!(order_fulfillment_saga.compensation().inventory_reserved); - assert!(!order_fulfillment_saga.compensation().payment_processed); - - // After payment processed - order_fulfillment_saga.payment_succeeded().unwrap(); - assert!(order_fulfillment_saga.compensation().inventory_reserved); - assert!(order_fulfillment_saga.compensation().payment_processed); - - // Fail after both steps completed - order_fulfillment_saga - .step_failed("FinalStep".to_string(), "Something went wrong".to_string()) - .unwrap(); - assert_eq!(order_fulfillment_saga.status(), SagaStatus::Compensating); - assert!(order_fulfillment_saga.needs_inventory_compensation()); - assert!(order_fulfillment_saga.needs_payment_compensation()); - - // Compensate payment first - order_fulfillment_saga.payment_compensated().unwrap(); - assert!(order_fulfillment_saga.needs_inventory_compensation()); - assert!(!order_fulfillment_saga.needs_payment_compensation()); - - // Compensate inventory - order_fulfillment_saga.inventory_compensated().unwrap(); - assert!(!order_fulfillment_saga.needs_inventory_compensation()); - assert!(!order_fulfillment_saga.needs_payment_compensation()); - - // Now can mark as failed - order_fulfillment_saga.mark_failed().unwrap(); - assert_eq!(order_fulfillment_saga.status(), SagaStatus::Failed); - assert!(order_fulfillment_saga.is_complete()); - - // Verify it persists correctly - saga_repo.commit(&mut order_fulfillment_saga).await.unwrap(); - let restored = saga_repo.get("saga-comp").await.unwrap().unwrap(); - assert_eq!(restored.status(), SagaStatus::Failed); - assert!(!restored.compensation().inventory_reserved); - assert!(!restored.compensation().payment_processed); -} diff --git a/tests/sagas/order/mod.rs b/tests/sagas/order/mod.rs index 11210b5e8..1330151d7 100644 --- a/tests/sagas/order/mod.rs +++ b/tests/sagas/order/mod.rs @@ -5,5 +5,5 @@ mod saga; pub use inventory::Inventory; pub use order_aggregate::{Order, OrderItem, OrderStatus}; -pub use payment::{Payment, PaymentStatus}; +pub use payment::Payment; pub use saga::{OrderFulfillmentSaga, SagaStatus}; diff --git a/tests/sourced/domain_events.rs b/tests/sourced/domain_events.rs index c1c1f2661..90f892666 100644 --- a/tests/sourced/domain_events.rs +++ b/tests/sourced/domain_events.rs @@ -286,3 +286,88 @@ fn derive_descriptors_match_frozen_schema_vectors() { "sha256:86a3954f27edecb9cc030479bd03e8d79e99d6c2c379dc961f12ca84ea4e1994" ); } + +mod declared_known_values { + use distributed::command::CommandEventSet; + use distributed::Entity; + use serde::{Deserialize, Serialize}; + + #[derive( + Clone, Debug, PartialEq, Eq, Serialize, Deserialize, distributed_macros::DomainState, + )] + #[domain_state(version = 1)] + pub struct TicketState { + status: String, + assignee_id: Option, + } + + #[derive(Default)] + pub struct Ticket { + entity: Entity, + status: String, + assignee_id: Option, + } + + impl From<&Ticket> for TicketState { + fn from(ticket: &Ticket) -> Self { + Self { + status: ticket.status.clone(), + assignee_id: ticket.assignee_id.clone(), + } + } + } + + #[distributed::sourced(entity, aggregate_type = "ticket", domain_state = TicketState)] + impl Ticket { + pub fn close(&mut self) -> distributed::SourcedResult { + self.record_closed()?; + Ok(()) + } + + pub fn shelve(&mut self) -> distributed::SourcedResult { + self.record_shelved()?; + Ok(()) + } + + #[event( + "ticket.closed", + version = 1, + domain, + known(status: "closed", assignee_id: null) + )] + fn record_closed(&mut self) { + self.status = "closed".into(); + self.assignee_id = None; + } + + #[event("ticket.shelved", version = 1, domain)] + fn record_shelved(&mut self) { + self.status = "shelved".into(); + self.assignee_id = None; + } + } + + #[test] + fn known_values_are_declared_not_read_from_the_recorder_body() { + assert_eq!( + domain_commands::Close::command_event_known_values(), + vec![distributed::state_preview! { + TicketClosedDomainEvent => TicketState { status: "closed", assignee_id: null, } + }] + ); + assert!( + domain_commands::Shelve::command_event_known_values().is_empty(), + "assignments in a recorder body predict nothing" + ); + + // Both transitions record the same state; only the declaration differs. + let (mut closed, mut shelved) = (Ticket::default(), Ticket::default()); + closed.entity.set_id("t1"); + shelved.entity.set_id("t2"); + closed.close().unwrap(); + shelved.shelve().unwrap(); + assert_eq!(closed.status, "closed"); + assert_eq!(shelved.status, "shelved"); + assert_eq!((closed.assignee_id, shelved.assignee_id), (None, None)); + } +} diff --git a/tests/sourced/flat_preview.rs b/tests/sourced/flat_preview.rs index 77d9ef799..39ea836b4 100644 --- a/tests/sourced/flat_preview.rs +++ b/tests/sourced/flat_preview.rs @@ -228,6 +228,19 @@ mod client_contract { }; } + #[test] + fn mutation_file_and_inline_mutation_compile_to_the_same_program() { + let inline: Mutation<()> = distributed::mutation! { + mutation SaveFlatReview { + upsert_flat_reviews(object: $input.review) + } + }; + assert_eq!( + SaveFlatReview().program().unwrap(), + inline.program().unwrap() + ); + } + #[allow(non_snake_case)] fn DeleteFlatMember() -> Mutation<()> { distributed::mutation_file!("tests/fixtures/flat_member_delete.graphql") @@ -414,11 +427,13 @@ mod client_contract { .manifest() .unwrap(); let projection = manifest.commands[0].extensions.projection.as_ref().unwrap(); - assert!(projection.preview_occurrences.iter().any(|occurrence| occurrence - .values + assert!(projection + .preview_occurrences .iter() - .any(|field| matches!(&field.source, ClientProjectionPreviewSource::Constant { - value: ClientProjectionValue::String(status) } if status == "archived")))); + .any(|occurrence| occurrence.values.iter().any( + |field| matches!(&field.source, ClientProjectionPreviewSource::Constant { + value: ClientProjectionValue::String(status) } if status == "archived") + ))); } #[test] diff --git a/tests/sourced/main.rs b/tests/sourced/main.rs index 43e4a8e09..be96d08ec 100644 --- a/tests/sourced/main.rs +++ b/tests/sourced/main.rs @@ -5,8 +5,7 @@ mod flat_preview; use aggregate::{Todo, TodoEvent}; use distributed::{ - Aggregate, AggregateBuilder, Entity, EventRecord, EventRecordError, InMemoryRepository, - Queueable, + AggregateBuilder, Entity, EventRecord, EventRecordError, InMemoryRepository, Queueable, }; use serde::ser::Error as _; use serde::Serialize; @@ -84,21 +83,6 @@ impl ExplicitlyValidatedRecorder { } } -#[test] -fn enum_variants_exist_and_compile() { - let init = TodoEvent::Initialized { - id: "1".into(), - user_id: "alice".into(), - task: "Buy milk".into(), - }; - let completed = TodoEvent::Completed; - - // Debug and Clone derives work - let _ = format!("{:?}", init); - let _ = init.clone(); - let _ = format!("{:?}", completed); -} - #[test] fn a_payload_that_fails_to_encode_records_nothing_and_skips_the_body() { let mut recorder = SafeRecorder::default(); @@ -220,26 +204,3 @@ fn non_event_methods_pass_through() { assert_eq!(snap.id, "t1"); assert_eq!(snap.user_id, "alice"); } - -#[test] -fn partial_equality_on_enum() { - let a = TodoEvent::Initialized { - id: "1".into(), - user_id: "alice".into(), - task: "Test".into(), - }; - let b = TodoEvent::Initialized { - id: "1".into(), - user_id: "alice".into(), - task: "Test".into(), - }; - let c = TodoEvent::Completed; - - assert_eq!(a, b); - assert_ne!(a, c); -} - -#[test] -fn no_upcasters_by_default() { - assert!(Todo::upcasters().is_empty()); -} diff --git a/tests/sourced_snapshot/aggregates.rs b/tests/sourced_snapshot/aggregates.rs index 915246d2f..256f601a7 100644 --- a/tests/sourced_snapshot/aggregates.rs +++ b/tests/sourced_snapshot/aggregates.rs @@ -119,11 +119,11 @@ impl Counter { } // ============================================================================ -// Custom entity field name +// Custom entity field name and snapshot version // ============================================================================ #[derive(Default, Snapshot)] -#[snapshot(entity = "my_entity")] +#[snapshot(entity = "my_entity", version = 3)] pub struct Widget { pub my_entity: Entity, pub name: String, diff --git a/tests/sourced_snapshot/main.rs b/tests/sourced_snapshot/main.rs index a71e2c036..38d508ceb 100644 --- a/tests/sourced_snapshot/main.rs +++ b/tests/sourced_snapshot/main.rs @@ -213,9 +213,15 @@ async fn sourced_attr_snapshot_roundtrip_via_repo() { } // ============================================================================ -// Custom entity field name +// Custom entity field name and snapshot version // ============================================================================ +#[test] +fn snapshot_version_is_declared_or_the_trait_default() { + assert_eq!(Widget::SNAPSHOT_VERSION, 3); + assert_eq!(Todo::SNAPSHOT_VERSION, 1); +} + #[test] fn custom_entity_field_snapshot() { let mut widget = Widget::new(); diff --git a/tests/sourced_upcasting/main.rs b/tests/sourced_upcasting/main.rs index e5360330f..99633b8cb 100644 --- a/tests/sourced_upcasting/main.rs +++ b/tests/sourced_upcasting/main.rs @@ -6,30 +6,6 @@ use distributed::{ StreamWrite, TransactionalCommit, }; -#[test] -fn v1_has_no_upcasters() { - assert!(TodoV1::upcasters().is_empty()); -} - -#[test] -fn v2_has_one_upcaster() { - let upcasters = TodoV2::upcasters(); - assert_eq!(upcasters.len(), 1); - assert_eq!(upcasters[0].event_type, "initialized"); - assert_eq!(upcasters[0].from_version, 1); - assert_eq!(upcasters[0].to_version, 2); -} - -#[test] -fn v3_has_two_upcasters() { - let upcasters = TodoV3::upcasters(); - assert_eq!(upcasters.len(), 2); - assert_eq!(upcasters[0].from_version, 1); - assert_eq!(upcasters[0].to_version, 2); - assert_eq!(upcasters[1].from_version, 2); - assert_eq!(upcasters[1].to_version, 3); -} - #[test] fn hydrate_v2_from_v1_events() { let mut v1 = TodoV1::default(); diff --git a/tests/sql_lock_manager/main.rs b/tests/sql_lock_manager/main.rs index 57e64b011..5aabdbbd4 100644 --- a/tests/sql_lock_manager/main.rs +++ b/tests/sql_lock_manager/main.rs @@ -139,13 +139,22 @@ const EXPIRY_MARGIN: Duration = Duration::from_millis(700); /// wait scales with it). async fn scenario_expired_lease_reclaim(m_holder: &M, m_other: &M, ttl: Duration) { let l1 = m_holder.get_lock("expiring").unwrap(); + // Taken before the lock: the lease's database-clock expiry is later than + // this instant plus `ttl`, so any steal observed before that is a bug. + let requested = std::time::Instant::now(); within(l1.lock()).await.unwrap(); // acquired, never released let l2 = m_other.get_lock("expiring").unwrap(); - assert!( - !within(l2.try_lock()).await.unwrap(), - "lease is still valid; must not be stealable yet" - ); + let stolen = within(l2.try_lock()).await.unwrap(); + // On a loaded runner the round trips can outlast the TTL; the lease may + // then have expired legitimately, and only an early steal is a failure. + // (A held, unexpired lease blocking another manager is asserted on its + // own, with the default TTL, by `scenario_two_managers_serialize`.) + if requested.elapsed() < ttl { + assert!(!stolen, "lease is still valid; must not be stealable yet"); + } else if stolen { + within(l2.unlock()).await.unwrap(); + } // Wait past the holder's TTL, then the lease is reclaimable. tokio::time::sleep(ttl + EXPIRY_MARGIN).await; diff --git a/tests/sqlite_repository/main.rs b/tests/sqlite_repository/main.rs index 77388dcf0..d6f31b390 100644 --- a/tests/sqlite_repository/main.rs +++ b/tests/sqlite_repository/main.rs @@ -17,39 +17,6 @@ use distributed::{ OUTBOX_MESSAGES_TABLE, }; use serde::{Deserialize, Serialize}; -use sqlx::migrate::{Migration, MigrationType, Migrator}; - -fn legacy_sqlite_migrator() -> Migrator { - Migrator::with_migrations(vec![ - Migration::new( - 1, - "initial".into(), - MigrationType::Simple, - sqlx::SqlSafeStr::into_sql_str(include_str!( - "../../migrations/sqlite/0001_initial.sql" - )), - false, - ), - Migration::new( - 2, - "command ledger".into(), - MigrationType::Simple, - sqlx::SqlSafeStr::into_sql_str(include_str!( - "../../migrations/sqlite/0002_command_ledger.sql" - )), - false, - ), - Migration::new( - 3, - "projection protocol".into(), - MigrationType::Simple, - sqlx::SqlSafeStr::into_sql_str(include_str!( - "../../migrations/sqlite/0003_projection_protocol.sql" - )), - false, - ), - ]) -} #[derive(Default)] struct Counter { @@ -165,72 +132,6 @@ async fn migration_is_idempotent_and_aggregate_stream_round_trips() { assert_eq!(loaded.entity().events()[0].correlation_id(), Some("corr-1")); } -#[tokio::test] -async fn projected_command_ledger_rows_upgrade_to_atomic_without_schema_drift() { - let repo = SqliteRepository::connect("sqlite::memory:").await.unwrap(); - legacy_sqlite_migrator().run(repo.pool()).await.unwrap(); - - sqlx::query( - r#" - INSERT INTO command_ledger ( - service_id, principal_partition, command_id, command_name, - command_contract_hash, input_hash, state, causation_id, - attempt_number, outcome, completed_at, retention_expires_at - ) VALUES (?, ?, ?, ?, zeroblob(32), zeroblob(32), 'projected', ?, 1, '{}', 1.0, 2.0) - "#, - ) - .bind("service") - .bind("principal") - .bind("command") - .bind("todo.complete") - .bind("cause") - .execute(repo.pool()) - .await - .unwrap(); - - repo.migrate().await.unwrap(); - - let state: String = sqlx::query_scalar( - "SELECT state FROM command_ledger WHERE service_id = 'service' AND command_id = 'command'", - ) - .fetch_one(repo.pool()) - .await - .unwrap(); - assert_eq!(state, "atomic"); - - let latest_version: i64 = sqlx::query_scalar("SELECT MAX(version) FROM _sqlx_migrations") - .fetch_one(repo.pool()) - .await - .unwrap(); - assert_eq!(latest_version, 14); - - let created_at_type: String = sqlx::query_scalar( - "SELECT typeof(created_at) FROM command_ledger WHERE service_id = 'service'", - ) - .fetch_one(repo.pool()) - .await - .unwrap(); - assert_eq!(created_at_type, "real"); - - let invalid_json = sqlx::query( - r#" - INSERT INTO command_ledger ( - service_id, principal_partition, command_id, command_name, - command_contract_hash, input_hash, state, causation_id, - attempt_number, outcome, completed_at, retention_expires_at - ) VALUES ('service', 'principal', 'bad-json', 'todo.complete', - zeroblob(32), zeroblob(32), 'atomic', 'bad-json-cause', - 1, '{', 1.0, 2.0) - "#, - ) - .execute(repo.pool()) - .await; - assert!( - invalid_json.is_err(), - "JSON validity CHECK must survive migration" - ); -} - #[tokio::test] async fn dev_bootstrap_applies_registered_table_schemas() { let repo = SqliteRepository::connect("sqlite::memory:").await.unwrap(); diff --git a/tests/sqlite_repository_conformance/main.rs b/tests/sqlite_repository_conformance/main.rs index b84b7df63..0f3eda9e9 100644 --- a/tests/sqlite_repository_conformance/main.rs +++ b/tests/sqlite_repository_conformance/main.rs @@ -5,14 +5,14 @@ mod conformance; use distributed::SqliteRepository; -async fn repository() -> Option { +async fn repository() -> Option<((), SqliteRepository)> { let repo = SqliteRepository::connect_and_migrate("sqlite::memory:") .await .expect("sqlite conformance repository should migrate"); repo.bootstrap_table_schema_for_dev(&conformance::read_models::conformance_table_registry()) .await .expect("read-model conformance table should bootstrap"); - Some(repo) + Some(((), repo)) } conformance::repository_conformance_tests!(); diff --git a/tests/support/graphql.rs b/tests/support/graphql.rs index b95dd4b6f..8e6146f41 100644 --- a/tests/support/graphql.rs +++ b/tests/support/graphql.rs @@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "postgres")] #[path = "postgres.rs"] -mod postgres; +pub mod postgres; /// Run `$body` with `$repository` bound to the concrete repository in `$db`. macro_rules! with_repository { @@ -26,7 +26,7 @@ macro_rules! with_repository { match $db { Db::Sqlite($repository) => $body, #[cfg(feature = "postgres")] - Db::Postgres($repository) => $body, + Db::Postgres($repository, _) => $body, } }; } @@ -88,8 +88,12 @@ pub(crate) use on_each_dialect; #[derive(Clone)] pub enum Db { Sqlite(SqliteRepository), + /// The schema is shared by every clone and dropped with the last one. #[cfg(feature = "postgres")] - Postgres(distributed::PostgresRepository), + Postgres( + distributed::PostgresRepository, + std::sync::Arc, + ), } impl Db { @@ -111,7 +115,8 @@ impl Db { #[cfg(feature = "postgres")] pub async fn postgres(what: &str) -> Option { let schema = postgres::PostgresTestSchema::create_from_env("graphql", what).await?; - Some(Db::Postgres(schema.repository().await)) + let repository = schema.repository().await; + Some(Db::Postgres(repository, std::sync::Arc::new(schema))) } pub fn is_postgres(&self) -> bool { @@ -141,9 +146,10 @@ impl Db { Db::Sqlite(repository.with_projection_change_retention(retention)) } #[cfg(feature = "postgres")] - Db::Postgres(repository) => { - Db::Postgres(repository.with_projection_change_retention(retention)) - } + Db::Postgres(repository, schema) => Db::Postgres( + repository.with_projection_change_retention(retention), + schema, + ), } } diff --git a/tests/support/postgres.rs b/tests/support/postgres.rs index 3318495b5..8cacb4672 100644 --- a/tests/support/postgres.rs +++ b/tests/support/postgres.rs @@ -12,6 +12,13 @@ mod env_support; static NEXT_SCHEMA_ID: AtomicU64 = AtomicU64::new(1); +/// A fresh schema of `DATABASE_URL`, dropped (with everything in it) when this +/// value is dropped — including when the test panics. +/// +/// Keep it alive as long as any repository or pool made from it: those +/// connections resolve tables through `search_path`, so they stop working once +/// the schema is gone. Fixtures return it next to what they build +/// (`(schema, repo)`); bind it to a named variable, not `_`, which drops at once. pub struct PostgresTestSchema { database_url: String, schema_name: String, @@ -84,6 +91,53 @@ impl PostgresTestSchema { } } +impl Drop for PostgresTestSchema { + /// `Drop` cannot await, and the test's runtime may be the current thread, + /// so the drop runs on a short-lived thread with its own runtime. A + /// connection that still holds a lock in the schema (a transaction left + /// open by a panic) makes the drop give up after `lock_timeout` instead of + /// hanging the test; the schema is then left behind, as before. + fn drop(&mut self) { + let database_url = self.database_url.clone(); + let drop_schema = format!( + "DROP SCHEMA IF EXISTS {} CASCADE", + quote_identifier(&self.schema_name) + ); + let dropped = std::thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| error.to_string())?; + runtime.block_on(async move { + let pool = PgPoolOptions::new() + .max_connections(1) + .connect(&database_url) + .await + .map_err(|error| error.to_string())?; + let mut connection = pool.acquire().await.map_err(|error| error.to_string())?; + connection + .execute("SET lock_timeout = '5s'") + .await + .map_err(|error| error.to_string())?; + connection + .execute(audited_schema_sql(drop_schema)) + .await + .map_err(|error| error.to_string())?; + drop(connection); + pool.close().await; + Ok::<_, String>(()) + }) + }) + .join(); + let error = match dropped { + Ok(Ok(())) => return, + Ok(Err(error)) => error, + Err(_) => "the drop thread panicked".to_owned(), + }; + eprintln!("left test schema {} behind: {error}", self.schema_name); + } +} + fn unique_schema_name(prefix: &str) -> String { let prefix = sanitize_prefix(prefix); let nanos = SystemTime::now() diff --git a/tests/support/rustc_fail.rs b/tests/support/rustc_fail.rs new file mode 100644 index 000000000..fcd9776fc --- /dev/null +++ b/tests/support/rustc_fail.rs @@ -0,0 +1,110 @@ +//! Compile-fail checks that assert by substring instead of a full snapshot. +//! +//! trybuild pins the whole rustc rendering, which is right for a macro's own +//! `compile_error!` text and wrong for a trait-bound or type error: rustc's +//! notes, "and N others" lists and standard-library spans change between +//! releases. These cases only need to fail to build with a message that names +//! the cause, so each one lists the substrings its error must contain. +//! +//! Every fixture in `dir` becomes one binary of a scratch crate; a single +//! `cargo check --keep-going --message-format=json` reports each binary's +//! errors. The scratch crate builds in its own target directory (a nested +//! cargo must not wait on the outer build's lock) and reuses the workspace +//! `Cargo.lock`, so dependency versions match the workspace. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Assert that every fixture `/.rs` fails to build with errors that +/// contain each listed substring, and that `cases` names every fixture in `dir`. +/// +/// `dependencies` is the scratch crate's `[dependencies]` table body; the +/// placeholder `{workspace}` is replaced by the workspace root path. +pub fn assert_fail_with( + manifest_dir: &str, + dir: &str, + dependencies: &str, + cases: &[(&str, &[&str])], +) { + let manifest_dir = Path::new(manifest_dir); + let workspace = manifest_dir + .ancestors() + .find(|path| path.join("Cargo.lock").is_file()) + .expect("a workspace Cargo.lock above the crate"); + let fixtures = manifest_dir.join(dir); + + let on_disk: BTreeSet = std::fs::read_dir(&fixtures) + .unwrap_or_else(|error| panic!("read {}: {error}", fixtures.display())) + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "rs")) + .map(|path| path.file_stem().unwrap().to_string_lossy().into_owned()) + .collect(); + let listed: BTreeSet = cases.iter().map(|(name, _)| name.to_string()).collect(); + assert_eq!(on_disk, listed, "every fixture needs expected substrings"); + + let target_root = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| workspace.join("target")) + .join("tests") + .join("rustc-fail"); + let package = format!( + "{}-rustc-fail", + manifest_dir.file_name().unwrap().to_string_lossy() + ); + let project = target_root.join(&package); + std::fs::create_dir_all(&project).unwrap(); + + let mut manifest = format!( + "[package]\nname = \"{package}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\ + publish = false\nautobins = false\n\n[workspace]\n\n[dependencies]\n{}\n", + dependencies.replace("{workspace}", &workspace.display().to_string()) + ); + for (name, _) in cases { + manifest.push_str(&format!( + "\n[[bin]]\nname = \"{name}\"\npath = \"{}\"\n", + fixtures.join(format!("{name}.rs")).display() + )); + } + std::fs::write(project.join("Cargo.toml"), manifest).unwrap(); + std::fs::copy(workspace.join("Cargo.lock"), project.join("Cargo.lock")).unwrap(); + + let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); + let output = Command::new(cargo) + .args(["check", "--bins", "--keep-going", "--message-format=json"]) + .arg("--manifest-path") + .arg(project.join("Cargo.toml")) + .env("CARGO_TARGET_DIR", target_root.join("target")) + .output() + .expect("run cargo check"); + let stderr = String::from_utf8_lossy(&output.stderr); + + let mut errors: BTreeMap> = BTreeMap::new(); + for line in String::from_utf8_lossy(&output.stdout).lines() { + let Ok(message) = serde_json::from_str::(line) else { + continue; + }; + if message["reason"] != "compiler-message" || message["message"]["level"] != "error" { + continue; + } + let target = message["target"]["name"].as_str().unwrap_or_default(); + let rendered = message["message"]["rendered"].as_str().unwrap_or_default(); + errors + .entry(target.to_owned()) + .or_default() + .push(rendered.to_owned()); + } + + for (name, expected) in cases { + let rendered = errors + .get(*name) + .map(|errors| errors.join("\n")) + .unwrap_or_else(|| panic!("`{name}` built without an error; cargo stderr:\n{stderr}")); + for needle in *expected { + assert!( + rendered.contains(needle), + "`{name}` failed without `{needle}`:\n{rendered}" + ); + } + } +} diff --git a/tests/upcasting/main.rs b/tests/upcasting/main.rs index 460c5a3e6..24910e622 100644 --- a/tests/upcasting/main.rs +++ b/tests/upcasting/main.rs @@ -75,18 +75,12 @@ fn event_version_serializes_when_not_v1() { } #[test] -fn old_events_without_event_version_deserialize_as_v1() { - let json = r#"{"event_name":"old_event","payload_codec":"bitcode","payload_codec_version":1,"payload":"","sequence":1,"timestamp":{"secs_since_epoch":0,"nanos_since_epoch":0},"metadata":{}}"#; - let record: EventRecord = serde_json::from_str(json).unwrap(); - assert_eq!(record.event_version, 1); -} - -#[test] -fn old_events_without_metadata_deserialize_with_empty_metadata() { - let json = r#"{"event_name":"old_event","payload_codec":"bitcode","payload_codec_version":1,"payload":"","sequence":1,"timestamp":{"secs_since_epoch":0,"nanos_since_epoch":0}}"#; - let record: EventRecord = serde_json::from_str(json).unwrap(); - assert_eq!(record.event_version, 1); - assert!(record.metadata.is_empty()); +fn v1_event_version_survives_a_round_trip_that_omits_it() { + let record = EventRecord::new("tested", vec![1, 2, 3], 1); + let json = serde_json::to_string(&record).unwrap(); + let deserialized: EventRecord = serde_json::from_str(&json).unwrap(); + assert_eq!(deserialized.event_version, 1); + assert_eq!(deserialized, record); } #[test] @@ -150,21 +144,6 @@ fn hydrate_v2_from_v1_events() { assert!(v2.completed); } -#[test] -fn v2_aggregate_has_upcasters() { - let upcasters = TodoV2::upcasters(); - assert_eq!(upcasters.len(), 1); - assert_eq!(upcasters[0].event_type, "initialized"); - assert_eq!(upcasters[0].from_version, 1); - assert_eq!(upcasters[0].to_version, 2); -} - -#[test] -fn v1_aggregate_has_no_upcasters() { - let upcasters = TodoV1::upcasters(); - assert!(upcasters.is_empty()); -} - // ============================================================================= // Chained upcasters: v1 → v2 → v3 // ============================================================================= @@ -226,16 +205,6 @@ fn hydrate_v3_from_native_v3_events_no_upcasting_needed() { assert_eq!(loaded.due_date, "2025-12-31"); } -#[test] -fn v3_aggregate_has_two_upcasters() { - let upcasters = TodoV3::upcasters(); - assert_eq!(upcasters.len(), 2); - assert_eq!(upcasters[0].from_version, 1); - assert_eq!(upcasters[0].to_version, 2); - assert_eq!(upcasters[1].from_version, 2); - assert_eq!(upcasters[1].to_version, 3); -} - // ============================================================================= // Mixed events: some need upcasting, some don't // =============================================================================