a3s-boot 0.1.1

Adapter-first modular Rust web framework for A3S inspired by Nest.js
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
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
use super::{MessageTransport, TransportMessage, TransportReply};
use crate::{BootApplication, BootError, BoxFuture, Result};
use futures_util::StreamExt;
use lapin::{
    options::{BasicAckOptions, BasicConsumeOptions, BasicPublishOptions, QueueDeclareOptions},
    types::FieldTable,
    BasicProperties, Channel, Connection, ConnectionProperties,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

static NEXT_RABBITMQ_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
static NEXT_RABBITMQ_CONSUMER_ID: AtomicU64 = AtomicU64::new(1);

/// Options for the RabbitMQ message transport.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RabbitMqTransportOptions {
    request_queue: String,
    event_queue: String,
    reply_queue_prefix: String,
    consumer_tag_prefix: String,
    request_timeout: Duration,
    durable: bool,
    auto_delete: bool,
}

impl RabbitMqTransportOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn request_queue(&self) -> &str {
        &self.request_queue
    }

    pub fn event_queue(&self) -> &str {
        &self.event_queue
    }

    pub fn reply_queue_prefix(&self) -> &str {
        &self.reply_queue_prefix
    }

    pub fn consumer_tag_prefix(&self) -> &str {
        &self.consumer_tag_prefix
    }

    pub fn request_timeout(&self) -> Duration {
        self.request_timeout
    }

    pub fn durable(&self) -> bool {
        self.durable
    }

    pub fn auto_delete(&self) -> bool {
        self.auto_delete
    }

    pub fn with_queue_prefix(mut self, prefix: impl Into<String>) -> Self {
        let prefix = prefix.into();
        self.request_queue = format!("{prefix}.requests");
        self.event_queue = format!("{prefix}.events");
        self.reply_queue_prefix = format!("{prefix}.replies");
        self.consumer_tag_prefix = format!("{prefix}.consumer");
        self
    }

    pub fn with_request_queue(mut self, queue: impl Into<String>) -> Self {
        self.request_queue = queue.into();
        self
    }

    pub fn with_event_queue(mut self, queue: impl Into<String>) -> Self {
        self.event_queue = queue.into();
        self
    }

    pub fn with_reply_queue_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.reply_queue_prefix = prefix.into();
        self
    }

    pub fn with_consumer_tag_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.consumer_tag_prefix = prefix.into();
        self
    }

    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = timeout.max(Duration::from_millis(1));
        self
    }

    pub fn with_durable(mut self, durable: bool) -> Self {
        self.durable = durable;
        self
    }

    pub fn with_auto_delete(mut self, auto_delete: bool) -> Self {
        self.auto_delete = auto_delete;
        self
    }
}

impl Default for RabbitMqTransportOptions {
    fn default() -> Self {
        Self {
            request_queue: "a3s.boot.requests".to_string(),
            event_queue: "a3s.boot.events".to_string(),
            reply_queue_prefix: "a3s.boot.replies".to_string(),
            consumer_tag_prefix: "a3s.boot.consumer".to_string(),
            request_timeout: Duration::from_secs(5),
            durable: false,
            auto_delete: false,
        }
    }
}

/// RabbitMQ transport for Boot message patterns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RabbitMqTransport {
    uri: String,
    options: RabbitMqTransportOptions,
}

impl RabbitMqTransport {
    pub fn new(uri: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            options: RabbitMqTransportOptions::default(),
        }
    }

    pub fn with_options(uri: impl Into<String>, options: RabbitMqTransportOptions) -> Self {
        Self {
            uri: uri.into(),
            options,
        }
    }

    pub fn uri(&self) -> &str {
        &self.uri
    }

    pub fn options(&self) -> &RabbitMqTransportOptions {
        &self.options
    }
}

impl MessageTransport for RabbitMqTransport {
    type Output = RabbitMqTransportClient;

    fn build(&self, _app: BootApplication) -> Result<Self::Output> {
        Ok(RabbitMqTransportClient {
            uri: self.uri.clone(),
            options: self.options.clone(),
        })
    }

    fn serve(&self, app: BootApplication) -> BoxFuture<'static, Result<()>> {
        let uri = self.uri.clone();
        let options = self.options.clone();
        Box::pin(async move {
            let connection = rabbitmq_connection(&uri).await?;
            let request_channel = connection.create_channel().await.map_err(rabbitmq_error)?;
            let event_channel = connection.create_channel().await.map_err(rabbitmq_error)?;
            let publish_channel = connection.create_channel().await.map_err(rabbitmq_error)?;

            declare_queue(&request_channel, options.request_queue.as_str(), &options).await?;
            declare_queue(&event_channel, options.event_queue.as_str(), &options).await?;

            let request_consumer = request_channel
                .basic_consume(
                    options.request_queue.clone().into(),
                    next_consumer_tag(options.consumer_tag_prefix.as_str(), "requests").into(),
                    BasicConsumeOptions::default(),
                    FieldTable::default(),
                )
                .await
                .map_err(rabbitmq_error)?;
            let event_consumer = event_channel
                .basic_consume(
                    options.event_queue.clone().into(),
                    next_consumer_tag(options.consumer_tag_prefix.as_str(), "events").into(),
                    BasicConsumeOptions::default(),
                    FieldTable::default(),
                )
                .await
                .map_err(rabbitmq_error)?;

            let request_loop =
                serve_request_deliveries(app.clone(), publish_channel, request_consumer);
            let event_loop = serve_event_deliveries(app, event_consumer);
            futures_util::future::try_join(request_loop, event_loop).await?;
            Ok(())
        })
    }
}

/// RabbitMQ client for Boot message patterns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RabbitMqTransportClient {
    uri: String,
    options: RabbitMqTransportOptions,
}

impl RabbitMqTransportClient {
    pub fn new(uri: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            options: RabbitMqTransportOptions::default(),
        }
    }

    pub fn with_options(uri: impl Into<String>, options: RabbitMqTransportOptions) -> Self {
        Self {
            uri: uri.into(),
            options,
        }
    }

    pub fn uri(&self) -> &str {
        &self.uri
    }

    pub fn options(&self) -> &RabbitMqTransportOptions {
        &self.options
    }

    pub async fn send(&self, message: TransportMessage) -> Result<Option<TransportReply>> {
        let connection = rabbitmq_connection(self.uri.as_str()).await?;
        let channel = connection.create_channel().await.map_err(rabbitmq_error)?;
        declare_queue(&channel, self.options.request_queue.as_str(), &self.options).await?;
        let request_id = next_request_id();
        let reply_to = self.reply_queue(&request_id);
        declare_reply_queue(&channel, reply_to.as_str()).await?;

        let mut consumer = channel
            .basic_consume(
                reply_to.clone().into(),
                next_consumer_tag(self.options.consumer_tag_prefix.as_str(), "reply").into(),
                BasicConsumeOptions::default(),
                FieldTable::default(),
            )
            .await
            .map_err(rabbitmq_error)?;
        let envelope = RabbitMqRequestEnvelope {
            id: request_id.clone(),
            reply_to: reply_to.clone(),
            message,
        };
        publish_to_queue(
            &channel,
            self.options.request_queue.as_str(),
            &encode(&envelope)?,
            BasicProperties::default(),
        )
        .await?;

        let response = tokio::time::timeout(self.options.request_timeout, async {
            while let Some(delivery) = consumer.next().await {
                let delivery = delivery.map_err(rabbitmq_error)?;
                let response = decode_response(&delivery.data)?;
                delivery
                    .ack(BasicAckOptions::default())
                    .await
                    .map_err(rabbitmq_error)?;
                if response.id() == request_id {
                    return Ok::<RabbitMqResponseEnvelope, BootError>(response);
                }
            }

            Err(BootError::Adapter(
                "rabbitmq transport reply queue closed".to_string(),
            ))
        })
        .await
        .map_err(|_| {
            BootError::Adapter(format!(
                "rabbitmq transport response timed out after {:?}",
                self.options.request_timeout
            ))
        })??;

        response.into_result()
    }

    pub async fn emit(&self, message: TransportMessage) -> Result<()> {
        let connection = rabbitmq_connection(self.uri.as_str()).await?;
        let channel = connection.create_channel().await.map_err(rabbitmq_error)?;
        declare_queue(&channel, self.options.event_queue.as_str(), &self.options).await?;
        publish_to_queue(
            &channel,
            self.options.event_queue.as_str(),
            &encode(&message)?,
            BasicProperties::default(),
        )
        .await
    }

    fn reply_queue(&self, request_id: &str) -> String {
        format!("{}.{}", self.options.reply_queue_prefix, request_id)
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct RabbitMqRequestEnvelope {
    id: String,
    reply_to: String,
    message: TransportMessage,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum RabbitMqResponseEnvelope {
    Reply {
        id: String,
        data: Value,
    },
    NoReply {
        id: String,
    },
    Error {
        id: String,
        status: u16,
        message: String,
    },
}

impl RabbitMqResponseEnvelope {
    fn from_result(id: &str, result: Result<Option<TransportReply>>) -> Self {
        match result {
            Ok(Some(reply)) => Self::Reply {
                id: id.to_string(),
                data: reply.data,
            },
            Ok(None) => Self::NoReply { id: id.to_string() },
            Err(error) => Self::from_error(id, error),
        }
    }

    fn from_error(id: &str, error: BootError) -> Self {
        Self::Error {
            id: id.to_string(),
            status: error.http_status_code(),
            message: error.http_response_message(),
        }
    }

    fn id(&self) -> &str {
        match self {
            Self::Reply { id, .. } | Self::NoReply { id } | Self::Error { id, .. } => id,
        }
    }

    fn into_result(self) -> Result<Option<TransportReply>> {
        match self {
            Self::Reply { data, .. } => Ok(Some(TransportReply::new(data))),
            Self::NoReply { .. } => Ok(None),
            Self::Error {
                status, message, ..
            } => Err(error_from_status(status, message)),
        }
    }
}

async fn serve_request_deliveries(
    app: BootApplication,
    publish_channel: Channel,
    mut consumer: lapin::Consumer,
) -> Result<()> {
    while let Some(delivery) = consumer.next().await {
        let delivery = delivery.map_err(rabbitmq_error)?;
        let app = app.clone();
        let publish_channel = publish_channel.clone();
        tokio::spawn(async move {
            let _ = handle_request_delivery(app, publish_channel, delivery).await;
        });
    }

    Err(BootError::Adapter(
        "rabbitmq transport request consumer closed".to_string(),
    ))
}

async fn serve_event_deliveries(app: BootApplication, mut consumer: lapin::Consumer) -> Result<()> {
    while let Some(delivery) = consumer.next().await {
        let delivery = delivery.map_err(rabbitmq_error)?;
        let Ok(message) = decode_event(&delivery.data) else {
            delivery
                .ack(BasicAckOptions::default())
                .await
                .map_err(rabbitmq_error)?;
            continue;
        };
        let app = app.clone();
        tokio::spawn(async move {
            let _ = app.emit_message(message).await;
            let _ = delivery.ack(BasicAckOptions::default()).await;
        });
    }

    Err(BootError::Adapter(
        "rabbitmq transport event consumer closed".to_string(),
    ))
}

async fn handle_request_delivery(
    app: BootApplication,
    channel: Channel,
    delivery: lapin::message::Delivery,
) -> Result<()> {
    let envelope = match decode_request(&delivery.data) {
        Ok(envelope) => envelope,
        Err(_) => {
            delivery
                .ack(BasicAckOptions::default())
                .await
                .map_err(rabbitmq_error)?;
            return Ok(());
        }
    };
    let response = RabbitMqResponseEnvelope::from_result(
        &envelope.id,
        app.dispatch_message(envelope.message).await,
    );
    publish_to_queue(
        &channel,
        envelope.reply_to.as_str(),
        &encode(&response)?,
        BasicProperties::default(),
    )
    .await?;
    delivery
        .ack(BasicAckOptions::default())
        .await
        .map_err(rabbitmq_error)?;
    Ok(())
}

async fn rabbitmq_connection(uri: &str) -> Result<Connection> {
    Connection::connect(uri, ConnectionProperties::default())
        .await
        .map_err(rabbitmq_error)
}

async fn declare_queue(
    channel: &Channel,
    queue: &str,
    options: &RabbitMqTransportOptions,
) -> Result<()> {
    channel
        .queue_declare(
            queue.into(),
            QueueDeclareOptions {
                durable: options.durable,
                auto_delete: options.auto_delete,
                ..QueueDeclareOptions::default()
            },
            FieldTable::default(),
        )
        .await
        .map_err(rabbitmq_error)?;
    Ok(())
}

async fn declare_reply_queue(channel: &Channel, queue: &str) -> Result<()> {
    channel
        .queue_declare(
            queue.into(),
            QueueDeclareOptions {
                exclusive: true,
                auto_delete: true,
                ..QueueDeclareOptions::default()
            },
            FieldTable::default(),
        )
        .await
        .map_err(rabbitmq_error)?;
    Ok(())
}

async fn publish_to_queue(
    channel: &Channel,
    queue: &str,
    payload: &[u8],
    properties: BasicProperties,
) -> Result<()> {
    channel
        .basic_publish(
            "".into(),
            queue.into(),
            BasicPublishOptions::default(),
            payload,
            properties,
        )
        .await
        .map_err(rabbitmq_error)?
        .await
        .map_err(rabbitmq_error)?;
    Ok(())
}

fn encode<T>(value: &T) -> Result<Vec<u8>>
where
    T: Serialize,
{
    serde_json::to_vec(value).map_err(|err| BootError::Internal(err.to_string()))
}

fn decode_request(payload: &[u8]) -> Result<RabbitMqRequestEnvelope> {
    serde_json::from_slice(payload).map_err(|err| BootError::BadRequest(err.to_string()))
}

fn decode_event(payload: &[u8]) -> Result<TransportMessage> {
    serde_json::from_slice(payload).map_err(|err| BootError::BadRequest(err.to_string()))
}

fn decode_response(payload: &[u8]) -> Result<RabbitMqResponseEnvelope> {
    serde_json::from_slice(payload).map_err(|err| BootError::Adapter(err.to_string()))
}

fn rabbitmq_error(error: impl fmt::Display) -> BootError {
    BootError::Adapter(error.to_string())
}

fn next_request_id() -> String {
    let counter = NEXT_RABBITMQ_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or_default();
    format!("{}-{nanos}-{counter}", std::process::id())
}

fn next_consumer_tag(prefix: &str, role: &str) -> String {
    let counter = NEXT_RABBITMQ_CONSUMER_ID.fetch_add(1, Ordering::Relaxed);
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or_default();
    format!("{prefix}.{role}.{}.{nanos}.{counter}", std::process::id())
}

fn error_from_status(status: u16, message: String) -> BootError {
    match status {
        400 => BootError::BadRequest(message),
        401 => BootError::Unauthorized(message),
        403 => BootError::Forbidden(message),
        404 => BootError::NotFound(message),
        406 => BootError::NotAcceptable(message),
        413 => BootError::PayloadTooLarge(message),
        415 => BootError::UnsupportedMediaType(message),
        429 => BootError::TooManyRequests(message),
        500 => BootError::Internal(message),
        _ => BootError::Adapter(message),
    }
}