Skip to main content

ulo_rpc_conformance/
lib.rs

1#![doc = include_str!("../README.md")]
2//!
3//! ## What the scenarios assert
4//!
5//! A scenario asserts kinds and reason strings, never message text, with one exception: the
6//! spent-cap scenario compares the shutdown phrase, through the `ulo_transport::SHUTDOWN_MESSAGE`
7//! constant and never a literal, the only thing telling the server's `unavailable` from the
8//! client's own for a connection that closed. A scenario a link's capabilities exclude asserts the
9//! refusal the capability declares instead: a streamed shape on UDP is refused at startup, and the
10//! scenarios below the server that open a streamed request are declared not applicable there, a
11//! binary payload on a JSON link before any I/O and its handler at startup, a miss on a link without
12//! `miss_signal` is the client's `Timeout`, the two-instance scenarios run one instance on an
13//! `Addressed` link, where a second cannot share the address, a request runs on both instances on a
14//! link without `single_delivery`, and an event declared `every_instance` is refused at startup on
15//! a link without `every_instance`. A scenario that needs a capability to run at all,
16//! `cancel_follows_its_request` on `ordered_control` and `an_event_reaches_one_instance` on
17//! `single_delivery`, is skipped on a link declared without it, writing the declared reason to
18//! standard error through [`skipped`].
19//!
20//! No scenario passes on silence. The client's own `Timeout` passes only where it is the declared
21//! answer: a scenario about the client's timeout or `deadline-ms`, a call nothing takes on a link
22//! without `miss_signal`, a call reaching a draining server on a link that declares
23//! `unserved_hold`, where an event emitted then has to reach the next instance, and a call sent
24//! during the drain on a link declared without `confirmed_drain`, where a call sent once the
25//! server has closed has to be refused `Unavailable`; a link that does not declare it is held to
26//! the confirmed drain. A scenario that cannot apply to a link is declared not applicable in
27//! [`conformance_suite!`] and reported as ignored; run on that link, it fails.
28//!
29//! ## Runtimes
30//!
31//! The suite names no runtime. A broker's [`Harness`] is its runtime half, as the HTTP and runtime
32//! suites' are: the app's runtime, which every server and client in a scenario runs on and every
33//! wait and task of the scenario's own goes through, and a `block_on` each scenario runs inside,
34//! beside a one-thread `block_on` for the scenario that shows a link's connect does not stall its
35//! thread. `OnTokio`, behind the `tokio` feature, is the harness of every link built on tokio;
36//! `OnSmol`, behind `smol`, runs the scenarios on an `async-executor` `Executor`. The [`relay`]
37//! runs on threads of its own, on `std` sockets, so it carries a link on either.
38//!
39//! A host short of memory bounds how many scenarios hold an environment at once by setting
40//! [`PARALLEL_VAR`], `ULO_CONFORMANCE_PARALLEL`, to a positive integer: the bound is the smaller of
41//! it and the broker's own [`Broker::PARALLEL`], or it alone when the broker declares none. Unset
42//! or empty, it bounds nothing, and libtest's `--test-threads` still applies on top of either.
43//!
44//! ```text
45//! ULO_CONFORMANCE_PARALLEL=6 cargo test -p ulo-rpc-rabbitmq --features integration --test conformance
46//! ```
47
48use std::future::Future;
49use std::num::NonZeroUsize;
50
51use ulo::BoundAddr;
52use ulo_rpc::Link;
53use ulo_rpc::link::ClientProbe;
54
55pub mod cases;
56mod rt;
57
58pub use cases::deadlines::Stamped;
59// The harness pieces live in `ulo-conformance-support`, shared with the database suite, and are
60// re-exported here, so a link's `tests/conformance.rs` depends on this crate alone.
61#[cfg(feature = "smol")]
62pub use ulo_conformance_support::OnSmol;
63#[cfg(feature = "tokio")]
64pub use ulo_conformance_support::OnTokio;
65pub use ulo_conformance_support::{Budget, Harness, PARALLEL_VAR, Slots, failures_dir, relay, report, skipped, startup_failed};
66
67use crate::relay::Outage;
68
69/// One link's environment for the suite: a broker, or, for TCP and UDP, the server's own socket,
70/// bound at port 0 and read back.
71pub trait Broker: Sized + Send + Sync + 'static {
72    /// The runtime the scenarios run on: `OnTokio`, behind the `tokio` feature, for a link built on
73    /// tokio.
74    type Harness: Harness;
75
76    /// The link under test, which [`link`](Self::link) answers for the server and
77    /// [`client_link`](Self::client_link) for the client.
78    type Link: Link;
79
80    /// How many scenarios hold an environment at once; `None`, the default, leaves the scenarios
81    /// to libtest's parallelism. An environment heavy enough that starting one per scenario at
82    /// once starves any host, such as a broker container per scenario, bounds it: the stamped
83    /// tests then wait for a slot before `start` and keep it until the scenario has returned and
84    /// dropped its environment. What one host's memory allows is not the broker's to declare;
85    /// that host sets [`PARALLEL_VAR`], and the smaller of the two applies.
86    const PARALLEL: Option<NonZeroUsize> = None;
87
88    /// Starts the environment for one scenario, so no state leaks between scenarios. Every
89    /// scenario uses the same patterns, and on a broker the same default group and control lane,
90    /// and the stamped tests run in parallel, up to the bound [`PARALLEL`](Self::PARALLEL) and
91    /// [`PARALLEL_VAR`] set, so each
92    /// start answers a broker or a namespace no other scenario shares: a fresh container, or, on
93    /// TCP and UDP, a server link on port 0, whose port the OS chooses at the server's bind and
94    /// [`client_link`](Self::client_link) receives. A container reached at a port published on the host is started
95    /// through [`relay::unshadowed`], so a host listener on the same port does not answer in its
96    /// place, and a start that fails does so through [`startup_failed!`].
97    fn start() -> impl Future<Output = Self> + Send;
98
99    /// A link for the server, configured for this environment; called once per server instance,
100    /// and for the link's `capabilities`, which the scenarios read to choose what they assert.
101    /// Every link it answers declares the same capabilities. A link that binds a socket binds port
102    /// 0, so no two servers, and no other process, contend for one the suite chose.
103    fn link(&self) -> Self::Link;
104
105    /// A link for the client, called once per client, after the scenario's servers are bound:
106    /// `server` holds every address they bound, `App<Bound>::addresses()` in the order they
107    /// started, empty on a broker link, whose servers bind nothing. The server's link unless the
108    /// environment puts something between the two, such as a proxy `disrupt` cuts, or the client
109    /// has to be given the port the server's bind chose. It declares the capabilities `link` does.
110    fn client_link(&self, server: &[BoundAddr]) -> Self::Link {
111        let _ = server;
112        self.link()
113    }
114
115    /// Severs the client's connection however the environment allows, for the recovery scenario:
116    /// the calls waiting on it fail `Unavailable`, and the client connects again for the next. On
117    /// a link declaring `durable_replies` the waiting call is answered instead, so a `disrupt` that
118    /// severed nothing would pass unnoticed: there `disrupt` fails when it closed no connection
119    /// (`Relay::cut_for` answers how many), and keeps the client out until the waiting call's
120    /// reply is published, three seconds after it begins, which [`outage`](Self::outage) shows.
121    fn disrupt(&self) -> impl Future<Output = ()> + Send;
122
123    /// The client's outage from the last `disrupt`, observed: when its connections had closed, and
124    /// when the environment first let one through again. A link declaring `durable_replies`
125    /// reports it, and the recovery scenario requires the held call's answer to fall inside it, so
126    /// the reply is shown to wait for a client that was gone. `None`, the default, elsewhere.
127    fn outage(&self) -> Option<Outage> {
128        None
129    }
130
131    /// How many connections the client's link holds open through the environment, for the
132    /// client-close scenario, which requires them to end with the client's app and stay ended:
133    /// `Relay::open` counts them where a relay carries the client. `None`, the default, where the
134    /// environment cannot count them; UDP holds no connection to count.
135    fn client_connections(&self) -> impl Future<Output = Option<usize>> + Send {
136        async { None }
137    }
138
139    /// How long this environment takes, which a slow broker raises.
140    fn budget(&self) -> Budget {
141        Budget::default()
142    }
143
144    /// The client side of `link` as the held-`cancel` scenarios read it, on a link that holds a
145    /// streamed request's `cancel` until the server acknowledges its `open`: NATS, RabbitMQ, MQTT
146    /// and Kafka answer the link's own probe. `None`, the default, elsewhere: a link carrying
147    /// streamed requests and holding no `cancel` declares those scenarios not applicable, and so
148    /// does one carrying none, whose streamed scenarios assert its startup refusal of a streamed
149    /// handler.
150    ///
151    /// Hidden from the documentation and outside the crate's semver promise, as `ClientProbe` is:
152    /// `ulo-rpc`'s test support under its `conformance-probe` feature, which the first-party broker
153    /// links attach. A link that answers no probe declares the held-`cancel` scenarios not
154    /// applicable.
155    #[doc(hidden)]
156    fn probe(link: &Self::Link) -> Option<&ClientProbe> {
157        let _ = link;
158        None
159    }
160}
161
162/// Stamps every scenario as a `#[test]` for the broker type `$broker`, each running its scenario
163/// through the broker's [`Harness::block_on`].
164///
165/// A scenario that cannot apply to a link is declared with its reason, and stamped
166/// `#[ignore = "<reason>"]`, so the test report counts it as ignored rather than passed and prints
167/// the reason beside it:
168///
169/// ```ignore
170/// # // reason: names a link type defined in the transport crate's own tests/conformance.rs
171/// ulo_rpc_conformance::conformance_suite!(UdpLoopback; not_applicable {
172///     recovery_after_disrupt: "UDP holds no connection to lose",
173/// });
174/// ```
175///
176/// A declared name that is no scenario fails to compile. A scenario run on a link it does not
177/// apply to fails rather than passing, so a link leaving out a declaration it needs fails too;
178/// `cargo test -- --ignored` runs the declared ones, which then fail the same way.
179#[macro_export]
180macro_rules! conformance_suite {
181    ($broker:ty $(,)?) => {
182        $crate::conformance_suite!($broker; not_applicable {});
183    };
184    ($broker:ty; not_applicable { $($skip:ident : $why:literal),* $(,)? } $(,)?) => {
185        $crate::conformance_suite!(@stamper [$] $broker; $($skip : $why),*);
186    };
187    (@stamper [$d:tt] $broker:ty; $($skip:ident : $why:literal),*) => {
188        macro_rules! __ulo_rpc_conformance_stamp {
189            $(
190                ($skip, $d($d test:tt)*) => {
191                    #[test]
192                    // A literal: libtest prints an `ignore` reason only when it is one, and drops
193                    // a `concat!`'s.
194                    #[ignore = $why]
195                    $d($d test)*
196                };
197            )*
198            ($d other:ident, $d($d test:tt)*) => {
199                #[test]
200                $d($d test)*
201            };
202        }
203        // A declared name that is no scenario names no constant in `__ulo_rpc_conformance_scenarios`,
204        // a test build or any other: the stamped functions exist in a test build alone, and a
205        // doctest is none.
206        $(const _: () = __ulo_rpc_conformance_scenarios::$skip;)*
207        $crate::conformance_suite!(@cases $broker;
208            unary_round_trip => unary::round_trip,
209            handler_takes_its_context => unary::context_parameter,
210            domain_error_envelope => errors::domain_error,
211            error_handler_answers_its_own_value => errors::substituted,
212            unencodable_reply_is_internal => errors::unencodable_reply,
213            guard_refusal_is_forbidden => errors::guard_refusal,
214            panic_is_internal => errors::panic,
215            undecodable_payload_is_bad_request => errors::undecodable_payload,
216            headers_reach_call_headers => headers::reach_call_headers,
217            event_reaches_its_handler => events::reaches_handler,
218            a_refused_event_is_never_redelivered => events::refused_event_is_not_redelivered,
219            an_event_carries_none_of_its_emitter_s_deadline => events::emitter_s_deadline_is_not_the_event_s,
220            an_event_emitted_in_a_cancelled_execution_is_not_sent => events::cancelled_before_the_emit_is_not_sent,
221            an_event_sent_before_its_emitter_is_cancelled_is_handled => events::cancelled_after_the_send_is_handled,
222            unhandled_pattern => misses::unhandled_pattern,
223            unhandled_event_is_acknowledged => misses::unhandled_event,
224            server_stream_in_order => streams::server_stream,
225            client_stream => streams::client_stream,
226            client_stream_in_order => streams::client_stream_in_order,
227            bidi_stream => streams::bidi_stream,
228            cancel_mid_stream => cancel::mid_stream,
229            a_reply_stream_its_caller_does_not_read_ends_overflow => queues::reply_overflow,
230            a_streamed_request_its_handler_does_not_read_ends_overflow => queues::request_overflow,
231            deadline_ms_fires_deadline => deadlines::deadline_ms,
232            client_timeout_is_timeout => deadlines::client_timeout,
233            a_call_s_timeout_is_the_server_s_deadline => deadlines::timeout_is_the_server_s_deadline,
234            a_stream_s_idle_timeout_is_per_frame => deadlines::stream_idle_timeout_is_per_frame,
235            a_stream_s_idle_timeout_ends_it_on_silence => deadlines::idle_timeout_ends_a_silent_stream,
236            a_stream_s_deadline_is_the_server_s_deadline => deadlines::stream_deadline_is_the_server_s,
237            a_stream_with_neither_bound_runs_past_both => deadlines::stream_with_neither_bound_runs_on,
238            a_stream_s_unbounded_idle_timeout_outlasts_the_client_s => deadlines::unbounded_idle_timeout_outlasts_the_client_s,
239            a_stream_s_default_idle_timeout_is_the_client_s => deadlines::default_idle_timeout_is_the_client_s,
240            a_stream_s_shorter_idle_timeout_replaces_the_client_s => deadlines::shorter_idle_timeout_replaces_the_client_s,
241            a_stream_s_zero_idle_timeout_is_refused_before_any_frame => deadlines::zero_idle_timeout_is_refused_before_any_frame,
242            a_stream_s_longest_idle_timeout_does_not_panic => deadlines::longest_idle_timeout_does_not_panic,
243            a_call_s_zero_timeout_is_refused_before_the_server_sees_it => deadlines::zero_call_timeout_is_refused_before_the_server_sees_it,
244            a_stream_s_zero_deadline_is_refused_before_the_server_sees_it => deadlines::zero_stream_deadline_is_refused_before_the_server_sees_it,
245            a_call_past_its_execution_s_deadline_is_refused_before_the_server_sees_it => deadlines::passed_deadline_is_refused_before_the_server_sees_it,
246            a_call_in_a_cancelled_execution_is_refused_before_the_server_sees_it => deadlines::cancelled_execution_s_call_is_refused_before_the_server_sees_it,
247            a_call_s_deadline_is_measured_once_its_connection_is_made => deadlines::measured_once_connected,
248            a_call_whose_connect_outlasts_its_deadline_is_refused_before_the_server_sees_it => deadlines::connect_past_the_deadline_is_refused_before_the_server_sees_it,
249            a_call_s_timer_ends_with_its_bound_after_a_blocked_connect => deadlines::blocked_connect_s_timer_ends_with_its_bound,
250            connecting_does_not_stall_the_thread => threads::connecting_does_not_stall_the_thread [block_on_one_thread],
251            binary_payload => payloads::binary,
252            oversized_payload => payloads::oversized,
253            drain => drain::drain,
254            drain_window => drain::window,
255            a_call_held_past_a_spent_cap_is_answered_unavailable => drain::spent_cap,
256            a_call_held_past_a_spent_cap_is_answered_unavailable_on_one_thread => drain::spent_cap [block_on_one_thread],
257            recovery_after_disrupt => recovery::after_disrupt,
258            client_close => client_close::client_close,
259            an_event_reaches_one_instance => delivery::one_instance,
260            an_every_instance_event_reaches_each_instance => delivery::every_instance,
261            two_instances_answering_requests => delivery::requests_across_two_instances,
262            over_the_bound => admission::over_the_bound,
263            client_on_a_thread_without_a_runtime => threads::plain_thread,
264            cancel_follows_its_request => order::cancel_follows_its_request,
265            cancel_before_opened => order::cancel_before_opened,
266            a_late_opened_releases_the_held_cancel => order::late_opened,
267            a_held_cancel_is_dropped_when_its_hold_runs_out => order::hold_runs_out,
268            a_held_cancel_lasts_until_its_call_s_deadline => order::held_until_deadline,
269        );
270    };
271    (@cases $broker:ty; $($name:ident => $module:ident :: $case:ident $([$runner:ident])?),* $(,)?) => {
272        static __ULO_RPC_CONFORMANCE_SLOTS: $crate::Slots = $crate::Slots::new();
273        #[allow(dead_code, non_upper_case_globals)]
274        mod __ulo_rpc_conformance_scenarios {
275            $(pub(super) const $name: () = ();)*
276        }
277        $(
278            __ulo_rpc_conformance_stamp!($name, fn $name() {
279                let _slot = __ULO_RPC_CONFORMANCE_SLOTS.hold(<$broker as $crate::Broker>::PARALLEL);
280                $crate::conformance_suite!(@run $broker, $crate::cases::$module::$case::<$broker>() $(, $runner)?);
281            });
282        )*
283    };
284    // A case runs through `Harness::block_on` unless its entry names another runner.
285    (@run $broker:ty, $case:expr) => {
286        $crate::conformance_suite!(@run $broker, $case, block_on)
287    };
288    (@run $broker:ty, $case:expr, $runner:ident) => {
289        <<$broker as $crate::Broker>::Harness as $crate::Harness>::$runner($case)
290    };
291}