hexeract-core 0.5.0

Core traits and types for the Hexeract messaging framework
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
use std::sync::Arc;

use crate::command::Command;
use crate::context::HandlerContext;
use crate::error::HexeractError;
use crate::notification::Notification;
use crate::query::Query;

/// Asynchronous handler for a [`Command`].
///
/// Each [`Command`] type has exactly one registered `CommandHandler`. The
/// handler receives an immutable reference to itself, the command value and
/// a [`HandlerContext`] carrying tracing and cancellation information.
///
/// # Example
///
/// ```
/// use hexeract_core::{Command, CommandHandler, HandlerContext, HexeractError};
/// use uuid::Uuid;
///
/// struct CreateUser {
///     pub email: String,
/// }
///
/// impl Command for CreateUser {
///     type Output = Uuid;
/// }
///
/// struct UserRepository;
///
/// impl CommandHandler<CreateUser> for UserRepository {
///     type Error = HexeractError;
///
///     async fn handle(
///         &self,
///         cmd: CreateUser,
///         _ctx: &HandlerContext,
///     ) -> Result<Uuid, Self::Error> {
///         let _ = cmd.email;
///         Ok(Uuid::new_v4())
///     }
/// }
/// ```
#[trait_variant::make(Send)]
pub trait CommandHandler<C: Command>: Send + Sync + 'static {
    /// The handler-defined error type, convertible into [`HexeractError`].
    type Error: Into<HexeractError> + Send + Sync + 'static;

    /// Handles the command and produces its output.
    async fn handle(&self, command: C, ctx: &HandlerContext) -> Result<C::Output, Self::Error>;
}

/// Asynchronous handler for a [`Query`].
#[trait_variant::make(Send)]
pub trait QueryHandler<Q: Query>: Send + Sync + 'static {
    /// The handler-defined error type, convertible into [`HexeractError`].
    type Error: Into<HexeractError> + Send + Sync + 'static;

    /// Handles the query and produces its output.
    async fn handle(&self, query: Q, ctx: &HandlerContext) -> Result<Q::Output, Self::Error>;
}

/// Asynchronous handler for a [`Notification`].
///
/// Multiple handlers may be registered for the same notification type; the
/// mediator delivers the notification to each of them. A handler failure does
/// not interrupt the fan-out: every registered handler is invoked regardless
/// of sibling outcomes.
#[trait_variant::make(Send)]
pub trait NotificationHandler<N: Notification>: Send + Sync + 'static {
    /// The handler-defined error type, convertible into [`HexeractError`].
    type Error: Into<HexeractError> + Send + Sync + 'static;

    /// Handles the notification.
    ///
    /// The notification is shared across every registered handler as an
    /// [`Arc`], so it is never deep-cloned per handler. Clone out of the `Arc`
    /// if an owned value is needed.
    async fn handle(&self, notification: Arc<N>, ctx: &HandlerContext) -> Result<(), Self::Error>;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ids::{CorrelationId, MessageId};
    use std::time::Duration;
    use uuid::Uuid;

    fn fresh_ctx() -> HandlerContext {
        HandlerContext::new(MessageId::new(), CorrelationId::new())
    }

    fn assert_send<T: Send>(_: &T) {}

    #[derive(Debug, PartialEq, Eq, Clone)]
    struct UserCreated {
        id: Uuid,
        email: String,
    }

    struct CreateUser {
        email: String,
    }

    impl Command for CreateUser {
        type Output = UserCreated;
    }

    #[derive(Debug, thiserror::Error)]
    enum UserError {
        #[error("invalid email")]
        InvalidEmail,
    }

    impl From<UserError> for HexeractError {
        fn from(value: UserError) -> Self {
            Self::handler_failed(value)
        }
    }

    struct UserRepo {
        prefix: String,
    }

    impl CommandHandler<CreateUser> for UserRepo {
        type Error = UserError;
        async fn handle(
            &self,
            cmd: CreateUser,
            _ctx: &HandlerContext,
        ) -> Result<UserCreated, Self::Error> {
            if cmd.email.is_empty() {
                return Err(UserError::InvalidEmail);
            }
            Ok(UserCreated {
                id: Uuid::new_v4(),
                email: format!("{}-{}", self.prefix, cmd.email),
            })
        }
    }

    #[tokio::test]
    async fn command_handler_returns_complex_output() {
        let repo = UserRepo {
            prefix: "test".into(),
        };
        let ctx = fresh_ctx();
        let result = repo
            .handle(
                CreateUser {
                    email: "alice@example.com".into(),
                },
                &ctx,
            )
            .await
            .expect("handler should succeed");
        assert_eq!(result.email, "test-alice@example.com");
    }

    #[tokio::test]
    async fn command_handler_returns_typed_error_for_invalid_input() {
        let repo = UserRepo {
            prefix: "test".into(),
        };
        let ctx = fresh_ctx();
        let err = repo
            .handle(
                CreateUser {
                    email: String::new(),
                },
                &ctx,
            )
            .await
            .expect_err("empty email must fail");
        assert!(matches!(err, UserError::InvalidEmail));
        let framework_err: HexeractError = err.into();
        assert!(matches!(framework_err, HexeractError::HandlerFailed { .. }));
    }

    #[tokio::test]
    async fn handler_future_is_send() {
        let repo = UserRepo {
            prefix: "send".into(),
        };
        let ctx = fresh_ctx();
        let future = repo.handle(
            CreateUser {
                email: "send@test".into(),
            },
            &ctx,
        );
        assert_send(&future);
        let _ = future.await;
    }

    #[tokio::test]
    async fn handler_runs_in_spawned_task() {
        let repo = Arc::new(UserRepo {
            prefix: "spawn".into(),
        });
        let cloned = Arc::clone(&repo);
        let result = tokio::spawn(async move {
            let ctx = fresh_ctx();
            cloned.handle(CreateUser { email: "ok".into() }, &ctx).await
        })
        .await
        .expect("task panicked");
        assert!(result.is_ok());
    }

    struct DirectErrorHandler;
    impl CommandHandler<CreateUser> for DirectErrorHandler {
        type Error = HexeractError;
        async fn handle(
            &self,
            _cmd: CreateUser,
            _ctx: &HandlerContext,
        ) -> Result<UserCreated, Self::Error> {
            Err(HexeractError::Dispatch("forced".into()))
        }
    }

    #[tokio::test]
    async fn handler_can_use_hexeract_error_directly_as_error_type() {
        let handler = DirectErrorHandler;
        let ctx = fresh_ctx();
        let err = handler
            .handle(
                CreateUser {
                    email: "any".into(),
                },
                &ctx,
            )
            .await
            .expect_err("must fail");
        assert!(matches!(err, HexeractError::Dispatch(_)));
    }

    struct EchoIdsHandler;
    struct EchoIds;
    impl Command for EchoIds {
        type Output = (MessageId, CorrelationId);
    }

    impl CommandHandler<EchoIds> for EchoIdsHandler {
        type Error = HexeractError;
        async fn handle(
            &self,
            _cmd: EchoIds,
            ctx: &HandlerContext,
        ) -> Result<(MessageId, CorrelationId), Self::Error> {
            Ok((ctx.message_id, ctx.correlation_id))
        }
    }

    #[tokio::test]
    async fn handler_reads_message_and_correlation_ids_from_context() {
        let message_id = MessageId::new();
        let correlation_id = CorrelationId::new();
        let ctx = HandlerContext::new(message_id, correlation_id);

        let handler = EchoIdsHandler;
        let (got_msg, got_corr) = handler
            .handle(EchoIds, &ctx)
            .await
            .expect("handler should succeed");
        assert_eq!(got_msg, message_id);
        assert_eq!(got_corr, correlation_id);
    }

    struct SleepHandler;
    struct SleepFor(u64);
    impl Command for SleepFor {
        type Output = &'static str;
    }

    impl CommandHandler<SleepFor> for SleepHandler {
        type Error = HexeractError;
        async fn handle(
            &self,
            cmd: SleepFor,
            ctx: &HandlerContext,
        ) -> Result<&'static str, Self::Error> {
            tokio::select! {
                () = ctx.cancellation.cancelled() => Err(HexeractError::Dispatch("cancelled".into())),
                () = tokio::time::sleep(Duration::from_millis(cmd.0)) => Ok("completed"),
            }
        }
    }

    #[tokio::test]
    async fn handler_observes_external_cancellation() {
        let ctx = fresh_ctx();
        let token = ctx.cancellation.clone();

        let handle = tokio::spawn(async move {
            let handler = SleepHandler;
            handler.handle(SleepFor(5_000), &ctx).await
        });

        tokio::time::sleep(Duration::from_millis(50)).await;
        token.cancel();

        let result = handle.await.expect("task panicked");
        assert!(matches!(result, Err(HexeractError::Dispatch(ref m)) if m == "cancelled"));
    }

    #[tokio::test]
    async fn handler_is_shareable_via_arc() {
        let handler: Arc<UserRepo> = Arc::new(UserRepo {
            prefix: "arc".into(),
        });
        let h1 = Arc::clone(&handler);
        let h2 = Arc::clone(&handler);

        let t1 = tokio::spawn(async move {
            let ctx = fresh_ctx();
            h1.handle(CreateUser { email: "u1".into() }, &ctx).await
        });
        let t2 = tokio::spawn(async move {
            let ctx = fresh_ctx();
            h2.handle(CreateUser { email: "u2".into() }, &ctx).await
        });

        let (r1, r2) = tokio::join!(t1, t2);
        assert!(r1.unwrap().is_ok());
        assert!(r2.unwrap().is_ok());
    }

    #[derive(Debug)]
    struct UserSummary {
        id: Uuid,
    }

    struct FindUser {
        id: Uuid,
    }

    impl Query for FindUser {
        type Output = Option<UserSummary>;
    }

    struct UserFinder;

    impl QueryHandler<FindUser> for UserFinder {
        type Error = HexeractError;
        async fn handle(
            &self,
            query: FindUser,
            _ctx: &HandlerContext,
        ) -> Result<Option<UserSummary>, Self::Error> {
            Ok(Some(UserSummary { id: query.id }))
        }
    }

    #[tokio::test]
    async fn query_handler_returns_output() {
        let id = Uuid::new_v4();
        let handler = UserFinder;
        let ctx = fresh_ctx();
        let result = handler
            .handle(FindUser { id }, &ctx)
            .await
            .expect("query should succeed");
        assert_eq!(result.unwrap().id, id);
    }

    #[tokio::test]
    async fn query_handler_future_is_send() {
        let handler = UserFinder;
        let ctx = fresh_ctx();
        let future = handler.handle(FindUser { id: Uuid::new_v4() }, &ctx);
        assert_send(&future);
        let _ = future.await;
    }

    #[tokio::test]
    async fn query_handler_runs_in_spawned_task() {
        let handler = Arc::new(UserFinder);
        let cloned = Arc::clone(&handler);
        let result = tokio::spawn(async move {
            let ctx = fresh_ctx();
            cloned.handle(FindUser { id: Uuid::new_v4() }, &ctx).await
        })
        .await
        .expect("task panicked");
        assert!(result.is_ok());
    }

    struct FailingQuery;
    impl QueryHandler<FindUser> for FailingQuery {
        type Error = UserError;
        async fn handle(
            &self,
            _query: FindUser,
            _ctx: &HandlerContext,
        ) -> Result<Option<UserSummary>, Self::Error> {
            Err(UserError::InvalidEmail)
        }
    }

    #[tokio::test]
    async fn query_handler_error_converts_into_hexeract_error() {
        let handler = FailingQuery;
        let ctx = fresh_ctx();
        let err = handler
            .handle(FindUser { id: Uuid::new_v4() }, &ctx)
            .await
            .expect_err("must fail");
        let framework_err: HexeractError = err.into();
        assert!(matches!(framework_err, HexeractError::HandlerFailed { .. }));
    }
}