soaprs-core 0.2.0

Core contracts for soaprs
Documentation
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
//! Strongly typed dispatch and runtime-independent middleware pipelines.

use std::{fmt, sync::Arc};

use crate::{BoxFuture, Command, CommandHandler, Query, QueryHandler, SoapResult};

/// Dispatches one concrete command type while preserving its output type.
///
/// Every [`CommandHandler<C>`] implements this port automatically. It exists
/// so application boundaries can use dispatch terminology without introducing
/// a runtime service locator or erasing message and output types.
pub trait CommandDispatcher<C>: Send + Sync
where
    C: Command,
{
    /// Dispatches the command to its typed handler or pipeline.
    fn dispatch(&self, command: C) -> BoxFuture<'_, SoapResult<C::Output>>;
}

impl<C, H> CommandDispatcher<C> for H
where
    C: Command,
    H: CommandHandler<C> + ?Sized,
{
    fn dispatch(&self, command: C) -> BoxFuture<'_, SoapResult<C::Output>> {
        self.command(command)
    }
}

/// Dispatches one concrete query type while preserving its output type.
///
/// Every [`QueryHandler<Q>`] implements this port automatically.
pub trait QueryDispatcher<Q>: Send + Sync
where
    Q: Query,
{
    /// Dispatches the query to its typed handler or pipeline.
    fn dispatch(&self, query: Q) -> BoxFuture<'_, SoapResult<Q::Output>>;
}

impl<Q, H> QueryDispatcher<Q> for H
where
    Q: Query,
    H: QueryHandler<Q> + ?Sized,
{
    fn dispatch(&self, query: Q) -> BoxFuture<'_, SoapResult<Q::Output>> {
        self.query(query)
    }
}

/// Remaining command middleware followed by the final typed handler.
///
/// Middleware calls [`run`](Self::run) exactly when it wants processing to
/// continue. It may validate and short-circuit before that call, or inspect and
/// transform the result after it completes.
pub struct CommandNext<'a, C>
where
    C: Command + 'static,
{
    middleware: &'a [Arc<dyn CommandMiddleware<C>>],
    handler: &'a dyn CommandHandler<C>,
}

impl<C> fmt::Debug for CommandNext<'_, C>
where
    C: Command + 'static,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CommandNext")
            .field("remaining_middleware", &self.middleware.len())
            .finish_non_exhaustive()
    }
}

impl<'a, C> CommandNext<'a, C>
where
    C: Command + 'static,
{
    /// Continues the pipeline with the next middleware or final handler.
    pub fn run(self, command: C) -> BoxFuture<'a, SoapResult<C::Output>> {
        if let Some((middleware, remaining)) = self.middleware.split_first() {
            middleware.handle(
                command,
                Self {
                    middleware: remaining,
                    handler: self.handler,
                },
            )
        } else {
            self.handler.command(command)
        }
    }
}

/// Intercepts one concrete command type around its next processing step.
pub trait CommandMiddleware<C>: Send + Sync
where
    C: Command + 'static,
{
    /// Processes, delegates, or short-circuits the command.
    fn handle<'a>(
        &'a self,
        command: C,
        next: CommandNext<'a, C>,
    ) -> BoxFuture<'a, SoapResult<C::Output>>;
}

/// Ordered middleware pipeline ending in one typed command handler.
///
/// Middleware runs in registration order before the handler and unwinds in
/// reverse order after it. The pipeline also implements [`CommandHandler<C>`],
/// so existing application services and saga processors can receive it without
/// depending on a new abstraction.
pub struct CommandPipeline<C>
where
    C: Command + 'static,
{
    handler: Arc<dyn CommandHandler<C>>,
    middleware: Vec<Arc<dyn CommandMiddleware<C>>>,
}

impl<C> fmt::Debug for CommandPipeline<C>
where
    C: Command + 'static,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CommandPipeline")
            .field("middleware", &self.middleware.len())
            .finish_non_exhaustive()
    }
}

impl<C> CommandPipeline<C>
where
    C: Command + 'static,
{
    /// Creates an empty pipeline ending in `handler`.
    pub fn new(handler: Arc<dyn CommandHandler<C>>) -> Self {
        Self {
            handler,
            middleware: Vec::new(),
        }
    }

    /// Appends middleware and returns the updated pipeline.
    #[must_use]
    pub fn with_middleware(mut self, middleware: Arc<dyn CommandMiddleware<C>>) -> Self {
        self.middleware.push(middleware);
        self
    }

    /// Appends middleware after every previously registered layer.
    pub fn push_middleware(&mut self, middleware: Arc<dyn CommandMiddleware<C>>) {
        self.middleware.push(middleware);
    }

    /// Returns the number of registered middleware layers.
    pub fn middleware_count(&self) -> usize {
        self.middleware.len()
    }
}

impl<C> CommandHandler<C> for CommandPipeline<C>
where
    C: Command + 'static,
{
    fn command(&self, command: C) -> BoxFuture<'_, SoapResult<C::Output>> {
        CommandNext {
            middleware: &self.middleware,
            handler: self.handler.as_ref(),
        }
        .run(command)
    }
}

/// Remaining query middleware followed by the final typed handler.
pub struct QueryNext<'a, Q>
where
    Q: Query + 'static,
{
    middleware: &'a [Arc<dyn QueryMiddleware<Q>>],
    handler: &'a dyn QueryHandler<Q>,
}

impl<Q> fmt::Debug for QueryNext<'_, Q>
where
    Q: Query + 'static,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("QueryNext")
            .field("remaining_middleware", &self.middleware.len())
            .finish_non_exhaustive()
    }
}

impl<'a, Q> QueryNext<'a, Q>
where
    Q: Query + 'static,
{
    /// Continues the pipeline with the next middleware or final handler.
    pub fn run(self, query: Q) -> BoxFuture<'a, SoapResult<Q::Output>> {
        if let Some((middleware, remaining)) = self.middleware.split_first() {
            middleware.handle(
                query,
                Self {
                    middleware: remaining,
                    handler: self.handler,
                },
            )
        } else {
            self.handler.query(query)
        }
    }
}

/// Intercepts one concrete query type around its next processing step.
pub trait QueryMiddleware<Q>: Send + Sync
where
    Q: Query + 'static,
{
    /// Processes, delegates, or short-circuits the query.
    fn handle<'a>(
        &'a self,
        query: Q,
        next: QueryNext<'a, Q>,
    ) -> BoxFuture<'a, SoapResult<Q::Output>>;
}

/// Ordered middleware pipeline ending in one typed query handler.
pub struct QueryPipeline<Q>
where
    Q: Query + 'static,
{
    handler: Arc<dyn QueryHandler<Q>>,
    middleware: Vec<Arc<dyn QueryMiddleware<Q>>>,
}

impl<Q> fmt::Debug for QueryPipeline<Q>
where
    Q: Query + 'static,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("QueryPipeline")
            .field("middleware", &self.middleware.len())
            .finish_non_exhaustive()
    }
}

impl<Q> QueryPipeline<Q>
where
    Q: Query + 'static,
{
    /// Creates an empty pipeline ending in `handler`.
    pub fn new(handler: Arc<dyn QueryHandler<Q>>) -> Self {
        Self {
            handler,
            middleware: Vec::new(),
        }
    }

    /// Appends middleware and returns the updated pipeline.
    #[must_use]
    pub fn with_middleware(mut self, middleware: Arc<dyn QueryMiddleware<Q>>) -> Self {
        self.middleware.push(middleware);
        self
    }

    /// Appends middleware after every previously registered layer.
    pub fn push_middleware(&mut self, middleware: Arc<dyn QueryMiddleware<Q>>) {
        self.middleware.push(middleware);
    }

    /// Returns the number of registered middleware layers.
    pub fn middleware_count(&self) -> usize {
        self.middleware.len()
    }
}

impl<Q> QueryHandler<Q> for QueryPipeline<Q>
where
    Q: Query + 'static,
{
    fn query(&self, query: Q) -> BoxFuture<'_, SoapResult<Q::Output>> {
        QueryNext {
            middleware: &self.middleware,
            handler: self.handler.as_ref(),
        }
        .run(query)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        future::Future,
        sync::{Arc, Mutex},
        task::{Context, Poll, Waker},
    };

    use crate::{
        BoxFuture, Command, CommandDispatcher, CommandHandler, CommandMiddleware, CommandNext,
        CommandPipeline, Query, QueryDispatcher, QueryHandler, QueryMiddleware, QueryNext,
        QueryPipeline, SoapError, SoapErrorKind, SoapResult,
    };

    fn block_on<F>(future: F) -> F::Output
    where
        F: Future,
    {
        let mut context = Context::from_waker(Waker::noop());
        let mut future = Box::pin(future);
        loop {
            match future.as_mut().poll(&mut context) {
                Poll::Ready(output) => return output,
                Poll::Pending => std::thread::yield_now(),
            }
        }
    }

    #[derive(Debug)]
    struct Add(i32);

    impl Command for Add {
        type Output = i32;
    }

    struct AddHandler {
        trace: Arc<Mutex<Vec<&'static str>>>,
    }

    impl CommandHandler<Add> for AddHandler {
        fn command(&self, command: Add) -> BoxFuture<'_, SoapResult<i32>> {
            Box::pin(async move {
                self.trace
                    .lock()
                    .map_err(|_| SoapError::infrastructure("command test trace lock poisoned"))?
                    .push("handler");
                Ok(command.0)
            })
        }
    }

    struct AroundCommand {
        before: &'static str,
        after: &'static str,
        add: i32,
        trace: Arc<Mutex<Vec<&'static str>>>,
    }

    impl CommandMiddleware<Add> for AroundCommand {
        fn handle<'a>(
            &'a self,
            command: Add,
            next: CommandNext<'a, Add>,
        ) -> BoxFuture<'a, SoapResult<i32>> {
            Box::pin(async move {
                self.trace
                    .lock()
                    .map_err(|_| SoapError::infrastructure("command test trace lock poisoned"))?
                    .push(self.before);
                let output = next.run(command).await?;
                self.trace
                    .lock()
                    .map_err(|_| SoapError::infrastructure("command test trace lock poisoned"))?
                    .push(self.after);
                Ok(output + self.add)
            })
        }
    }

    #[test]
    fn command_pipeline_preserves_types_and_around_order() {
        let trace = Arc::new(Mutex::new(Vec::new()));
        let handler: Arc<dyn CommandHandler<Add>> = Arc::new(AddHandler {
            trace: Arc::clone(&trace),
        });
        let pipeline = CommandPipeline::new(handler)
            .with_middleware(Arc::new(AroundCommand {
                before: "outer-before",
                after: "outer-after",
                add: 1,
                trace: Arc::clone(&trace),
            }))
            .with_middleware(Arc::new(AroundCommand {
                before: "inner-before",
                after: "inner-after",
                add: 10,
                trace: Arc::clone(&trace),
            }));

        assert_eq!(pipeline.middleware_count(), 2);
        assert_eq!(block_on(pipeline.dispatch(Add(5))).ok(), Some(16));
        assert_eq!(
            trace.lock().ok().map(|items| items.clone()),
            Some(vec![
                "outer-before",
                "inner-before",
                "handler",
                "inner-after",
                "outer-after"
            ])
        );
    }

    struct RejectCommand;

    impl CommandMiddleware<Add> for RejectCommand {
        fn handle<'a>(
            &'a self,
            _command: Add,
            _next: CommandNext<'a, Add>,
        ) -> BoxFuture<'a, SoapResult<i32>> {
            Box::pin(async { Err(SoapError::validation("command rejected by middleware")) })
        }
    }

    #[test]
    fn command_middleware_can_short_circuit_the_handler() {
        let trace = Arc::new(Mutex::new(Vec::new()));
        let handler: Arc<dyn CommandHandler<Add>> = Arc::new(AddHandler {
            trace: Arc::clone(&trace),
        });
        let pipeline = CommandPipeline::new(handler).with_middleware(Arc::new(RejectCommand));

        let result = block_on(pipeline.dispatch(Add(5)));
        assert_eq!(
            result.as_ref().map_err(SoapError::kind),
            Err(SoapErrorKind::Validation)
        );
        assert_eq!(trace.lock().ok().map(|items| items.is_empty()), Some(true));
    }

    struct Double(i32);

    impl Query for Double {
        type Output = i32;
    }

    struct DoubleHandler;

    impl QueryHandler<Double> for DoubleHandler {
        fn query(&self, query: Double) -> BoxFuture<'_, SoapResult<i32>> {
            Box::pin(async move { Ok(query.0 * 2) })
        }
    }

    struct AddToQuery(i32);

    impl QueryMiddleware<Double> for AddToQuery {
        fn handle<'a>(
            &'a self,
            query: Double,
            next: QueryNext<'a, Double>,
        ) -> BoxFuture<'a, SoapResult<i32>> {
            Box::pin(async move { Ok(next.run(query).await? + self.0) })
        }
    }

    #[test]
    fn query_pipeline_and_direct_handlers_share_typed_dispatch() {
        assert_eq!(block_on(DoubleHandler.dispatch(Double(4))).ok(), Some(8));

        let handler: Arc<dyn QueryHandler<Double>> = Arc::new(DoubleHandler);
        let mut pipeline = QueryPipeline::new(handler);
        pipeline.push_middleware(Arc::new(AddToQuery(3)));
        assert_eq!(pipeline.middleware_count(), 1);
        assert_eq!(block_on(pipeline.dispatch(Double(4))).ok(), Some(11));
    }
}