1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! The broker side of the harness: [`InProcess`], the transition that runs a production broker
//! inside the test process, and [`TestableBroker`], the view of its connected form the
//! [`TestApp`](super::TestApp) harness and the [`conformance`](crate::conformance) suite drive.
use ;
use fmt;
use Future;
use Duration;
use crate;
use crate::;
use Coordinator;
/// A broker that runs inside the test process.
///
/// [`connect_in_process`](Self::connect_in_process) is the consuming transition a test takes
/// instead of [`connect`](Broker::connect): it produces the broker's own connected form, backed
/// by an in-process transport, with no I/O. The connected form is the one production gets, so the
/// app's routes, publish policies and subscription descriptors resolve against it unchanged, and
/// [`TestApp`](super::TestApp) runs the service's production app as it is.
///
/// The transport has no configuration of its own. It reads every setting from the broker it was
/// built from (default group, prefetch, topology declaration, whatever the real broker applies),
/// so a test cannot run against settings production does not have. It never succeeds where the
/// real broker fails: a publish, a settlement or a subscription the server would reject is
/// rejected in process the same way.
///
/// A broker crate implements this under its `testing` feature, next to
/// [`TestableBroker`] on the connected form, and registers the broker with
/// [`register_testable_broker!`](crate::register_testable_broker).
/// [`MemoryBroker`](crate::memory::MemoryBroker) is the reference: it has no server, so its
/// in-process transition is its ordinary `connect`.
///
/// The in-process mode lives in the production types: the connected form, its subscriber, its
/// publishers and its delivery each gain an in-process variant that exists only under the
/// `testing` feature. Without the feature there is one variant and no branch, and a service's
/// production build is unchanged, because Cargo does not enable a dev-dependency's features in a
/// production binary. A mount that compiles against the broker compiles in process, and a
/// capability is the same type in both.
///
/// The same test also runs against a stand: [`TestApp::start_live`](super::TestApp::start_live)
/// connects the broker through its ordinary `connect` and needs nothing beyond the connected form
/// and its [`DefaultPublish`] policy, through which the harness publishes a test's input.
///
/// # Writing one you can trust
///
/// A service's whole test suite runs against this transport, so every difference from the real
/// one is a green test for behaviour production does not have.
///
/// - Run the [`conformance`](crate::conformance) suites in process, not only against a server:
/// [`run_suite`](crate::conformance::harness::run_suite), then `lifecycle` and the capability
/// suites through [`InProcessBroker`](crate::conformance::harness::InProcessBroker). `lifecycle`
/// asks what an in-process transport is rarely asked: whether a publisher created before the
/// shutdown errors afterwards. A transport whose publish is a channel send accepts the message
/// instead.
/// - Settle the way the transport settles. Where the real `ack` answers
/// [`AckError::Unsupported`](crate::AckError::Unsupported), the in-process one answers the same;
/// `Ok(())` there is how a handler returning `retry()` passes in a test and loses the message in
/// production.
/// - Reproduce what the client does; do not fake what the broker does. Competing consumers, group
/// distribution, correlation, reply routing and buffering until commit are client-side or
/// routing-level, and an in-process copy of them is exact. Cluster atomicity, fencing,
/// broker-held timeouts and exactly-once are broker-side, and the live mode covers them.
/// Competing consumers matter most: handing every message of a queue to every subscriber of it
/// is a fan-out, and two workers sharing the queue then each run the whole stream with no error
/// anywhere.
/// - Keep what the real broker keeps. A queue or a log that exists before the subscription
/// delivers what reached it earlier; declare that with [`TestableBroker::backlog`], and read a
/// setting that decides it (an earliest offset, a deliver-all consumer) off the connected form.
/// [`backlog_matches_server`](crate::conformance::in_process::backlog_matches_server) checks the
/// declaration against the server.
/// - Read the production wiring. A check the real broker makes at subscribe or publish time (a
/// declaration it refuses, a name too long for the protocol, a header it cannot carry) runs in
/// process through the same code.
/// - Give every gap a comment naming the assertion it makes unsound and what covers it instead,
/// and pin the gap with a test asserting the handler is not reached, which fails the day
/// someone routes what the transport deliberately does not.
///
/// ```text
/// // No fencing: a second producer claiming the same transactional id is not rejected here, so a
/// // test cannot assert the first one is fenced out. `capabilities::transactions` against a real
/// // server is what covers that.
/// ```
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "memory")]
/// # mod demo {
/// use std::future::Future;
///
/// use ruststream::Broker;
/// use ruststream::memory::{ConnectedMemoryBroker, MemoryBroker, MemoryError};
/// use ruststream::testing::InProcess;
///
/// /// A broker crate built over the in-memory bus: its connected form is the bus's own, so its
/// /// in-process transition is the bus's too.
/// pub struct EdgeBroker(MemoryBroker);
///
/// impl Broker for EdgeBroker {
/// type Error = MemoryError;
/// type Connected = ConnectedMemoryBroker;
///
/// fn connect(
/// self,
/// ) -> impl Future<Output = Result<ConnectedMemoryBroker, MemoryError>> + Send {
/// self.0.connect()
/// }
/// }
///
/// impl InProcess for EdgeBroker {
/// fn connect_in_process(
/// self,
/// ) -> impl Future<Output = Result<ConnectedMemoryBroker, MemoryError>> + Send {
/// self.0.connect_in_process()
/// }
/// }
///
/// // Under the crate's `testing` feature: `TestApp::start` now runs an app on `EdgeBroker`.
/// ruststream::register_testable_broker!(EdgeBroker);
/// # }
/// # fn main() {}
/// ```
/// The view of a connected broker the test tooling drives.
///
/// Implemented on the **connected form** a broker's [`InProcess`] transition produces: the
/// [`TestApp`](super::TestApp) harness connects every broker of the app in process, then drives
/// it through this, and
/// [`conformance::harness::run_suite`](crate::conformance::harness::run_suite) checks the
/// routing contract through the same surface.
///
/// The transport answers settlement the way the real transport answers it. A transport that cannot
/// acknowledge (`ZeroMQ`, MQTT `QoS 0`, Redis pub/sub, Core NATS) reports
/// [`AckError::Unsupported`](crate::AckError::Unsupported) from its deliveries in production, so
/// the in-process one reports it too: both the harness and
/// [`run_suite`](crate::conformance::harness::run_suite) accept that answer, while a transport that
/// claims success makes a handler's retry look settled in a test and lose the message in
/// production. Either way the delivery is released to [`Coordinator::consumed`] once (from its
/// `Drop`, which a refused settlement reaches like any other).
///
/// To plug into the harness, the transport also calls [`Coordinator::enqueued`] on every live
/// enqueue into a subscriber and [`Coordinator::consumed`] when a delivery is acked, nacked, or
/// dropped (so the harness can tell when the reaction has settled), and routes delayed
/// redeliveries through [`Coordinator::schedule_redelivery`].
///
/// [`ConnectedMemoryBroker`](crate::memory::ConnectedMemoryBroker) is the in-tree reference
/// implementation.
///
/// It is a separate, object-safe capability rather than a
/// [`ConnectedBroker`](crate::ConnectedBroker) supertrait: the broker traits are not
/// dyn-compatible, and the harness holds `&dyn TestableBroker`.
///
/// # Examples
///
/// ```no_run
/// # #[cfg(all(feature = "memory", feature = "conformance"))]
/// # async fn run() {
/// use ruststream::conformance::harness;
/// use ruststream::memory::MemoryBroker;
///
/// // A broker crate's conformance test: the suite drives the connected form through this view
/// // and checks its answers against what the transport does.
/// harness::run_suite(MemoryBroker::new).await;
/// # }
/// ```
/// What a subscription opened by name receives of the messages published to that name before it
/// opened: the answer a broker gives through [`TestableBroker::backlog`].
///
/// # Examples
///
/// A queue broker's in-process transport keeps what reaches an existing queue with no consumer yet,
/// as the server does, and says so:
///
/// ```
/// use ruststream::testing::Backlog;
///
/// # struct QueueBus;
/// # impl QueueBus {
/// fn backlog(&self) -> Backlog {
/// Backlog::Delivered
/// }
/// # }
/// # assert_eq!(QueueBus.backlog(), Backlog::Delivered);
/// ```
/// The harness's record of one [`InProcess`] broker type: how to recognise it in a built app, how
/// to connect it in process, and how to reach the [`TestableBroker`] view of what that produced.
///
/// Built by [`register_testable_broker!`](crate::register_testable_broker), once per broker type;
/// the harness looks each broker of the app up here by its type.
/// Publishes a test's input onto a connected broker, the connected form erased: what an injection
/// is in live mode, where no in-process transport takes it. Built for one broker type, which it
/// downcasts the connected form back to.
pub type LivePublish = for<'m> fn ;
/// Publishes `msg` onto `connected`, the connected form of `B`, through the broker's own
/// [`DefaultPublish`] policy: the way an external producer reaches a live broker.
pub
/// `B`'s in-process transition over erased values: the harness hands it the broker it found under
/// `B`'s type, and gets the connected form back the same way.
/// The [`TestableBroker`] view of `B`'s connected form, when `any` is one.
collect!;
/// Registers a production broker type with the test harness, so
/// [`TestApp`](crate::testing::TestApp) runs every broker of that type in process.
///
/// It registers two things for the type: its [`InProcess`] transition, which the harness connects
/// it through instead of [`connect`](crate::Broker::connect), and the [`TestableBroker`] view of
/// the connected form that transition produces. Call it once at broker-crate scope, under the
/// crate's `testing` feature, with the type a service builds its app on.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "memory")]
/// # mod demo {
/// use std::future::Future;
///
/// use ruststream::Broker;
/// use ruststream::memory::{ConnectedMemoryBroker, MemoryBroker, MemoryError};
/// use ruststream::testing::InProcess;
///
/// /// A broker crate built over the in-memory bus: its connected form is the bus's own, so its
/// /// in-process transition is the bus's too.
/// pub struct EdgeBroker(MemoryBroker);
///
/// impl Broker for EdgeBroker {
/// type Error = MemoryError;
/// type Connected = ConnectedMemoryBroker;
///
/// fn connect(
/// self,
/// ) -> impl Future<Output = Result<ConnectedMemoryBroker, MemoryError>> + Send {
/// self.0.connect()
/// }
/// }
///
/// impl InProcess for EdgeBroker {
/// fn connect_in_process(
/// self,
/// ) -> impl Future<Output = Result<ConnectedMemoryBroker, MemoryError>> + Send {
/// self.0.connect_in_process()
/// }
/// }
///
/// ruststream::register_testable_broker!(EdgeBroker);
/// # }
/// # fn main() {}
/// ```
/// Waits until at least `count` messages have been published to `name` on `broker`.
///
/// Returns all observed messages; on timeout it returns those seen so far (so assert on the returned
/// messages, not just on length). For application tests prefer [`TestApp`](super::TestApp), which
/// drives to quiescence without polling; this helper is for tests that run a service via
/// [`run_until`](crate::runtime::RustStream::run_until) directly.
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "memory", feature = "json"))]
/// # async fn demo() -> Result<(), ruststream::memory::MemoryError> {
/// use std::time::Duration;
/// use ruststream::memory::MemoryBroker;
/// use ruststream::testing::{InProcess, TestableBroker, expect_published};
/// use ruststream::OutgoingMessage;
///
/// let connected = MemoryBroker::new().connect_in_process().await?;
/// connected.inject(OutgoingMessage::new("out", b"x".as_slice()));
/// let seen = expect_published(&connected, "out", 1, Duration::from_secs(1)).await;
/// assert_eq!(seen.len(), 1);
/// # Ok(())
/// # }
/// ```
pub async