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
use std::{
    sync::Arc,
    task::{Context, Poll},
};

use futures_util::TryFutureExt;

use crate::sinks::prelude::*;

use super::{config::NatsPublisher, request_builder::NatsRequest, NatsError};

#[derive(Clone)]
pub(super) struct NatsService {
    pub(super) publisher: Arc<NatsPublisher>,
}

pub(super) struct NatsResponse {
    metadata: RequestMetadata,
}

impl DriverResponse for NatsResponse {
    fn event_status(&self) -> EventStatus {
        EventStatus::Delivered
    }

    fn events_sent(&self) -> &GroupedCountByteSize {
        self.metadata.events_estimated_json_encoded_byte_size()
    }

    fn bytes_sent(&self) -> Option<usize> {
        Some(self.metadata.request_encoded_size())
    }
}

impl Service<NatsRequest> for NatsService {
    type Response = NatsResponse;

    type Error = NatsError;

    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: NatsRequest) -> Self::Future {
        let publisher = Arc::clone(&self.publisher);

        Box::pin(async move {
            match publisher
                .publish(req.subject, req.bytes)
                .map_err(async_nats::Error::from)
                .await
            {
                Err(error) => Err(NatsError::ServerError { source: error }),
                Ok(_) => Ok(NatsResponse {
                    metadata: req.metadata,
                }),
            }
        })
    }
}