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
use crate::{EventData, ExpectedRevision, Position};
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
use futures::channel::oneshot;
use futures::{SinkExt, StreamExt};

#[derive(Debug)]
pub(crate) struct In {
    req: Req,
    sender: oneshot::Sender<crate::Result<BatchWriteResult>>,
}

#[derive(Debug)]
pub(crate) struct Req {
    pub(crate) id: uuid::Uuid,
    pub(crate) stream_name: String,
    pub(crate) events: Vec<EventData>,
    pub(crate) expected_revision: ExpectedRevision,
}

#[derive(Debug)]
pub(crate) struct Out {
    pub(crate) correlation_id: uuid::Uuid,
    pub(crate) result: crate::Result<BatchWriteResult>,
}

#[derive(Debug)]
pub(crate) enum BatchMsg {
    In(In),
    Out(Out),
    Error(crate::Error),
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct BatchWriteResult {
    stream_name: String,
    current_revision: Option<u64>,
    current_position: Option<Position>,
    expected_revision: Option<ExpectedRevision>,
}

impl BatchWriteResult {
    pub fn new(
        stream_name: String,
        current_revision: Option<u64>,
        current_position: Option<Position>,
        expected_revision: Option<ExpectedRevision>,
    ) -> Self {
        Self {
            stream_name,
            current_position,
            current_revision,
            expected_revision,
        }
    }

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

    pub fn current_revision(&self) -> Option<u64> {
        self.current_revision
    }

    pub fn current_position(&self) -> Option<Position> {
        self.current_position
    }

    pub fn expected_version(&self) -> Option<ExpectedRevision> {
        self.expected_revision
    }
}

pub struct BatchAppendClient {
    sender: UnboundedSender<BatchMsg>,
}

impl BatchAppendClient {
    pub(crate) fn new(
        sender: UnboundedSender<BatchMsg>,
        mut receiver: UnboundedReceiver<BatchMsg>,
        mut forward: UnboundedSender<Req>,
    ) -> Self {
        tokio::spawn(async move {
            let mut reg = std::collections::HashMap::<
                uuid::Uuid,
                oneshot::Sender<crate::Result<BatchWriteResult>>,
            >::new();
            while let Some(msg) = receiver.next().await {
                match msg {
                    BatchMsg::In(msg) => {
                        let correlation_id = msg.req.id;
                        if forward.send(msg.req).await.is_ok() {
                            reg.insert(correlation_id, msg.sender);
                            debug!("Send batch-append request {}", correlation_id);

                            continue;
                        }

                        error!("Batch-append session has been closed");
                        break;
                    }

                    BatchMsg::Out(resp) => {
                        if let Some(entry) = reg.remove(&resp.correlation_id) {
                            let failed = resp.result.is_err();
                            let _ = entry.send(resp.result);

                            if failed {
                                break;
                            }

                            continue;
                        }

                        warn!(
                            "Unknown batch-append response correlation id: {}",
                            resp.correlation_id
                        );
                    }

                    BatchMsg::Error(e) => {
                        for (_, resp_sender) in reg {
                            let _ = resp_sender.send(Err(e.clone()));
                        }

                        break;
                    }
                }
            }
        });

        Self { sender }
    }

    pub async fn append_to_stream<S: AsRef<str>>(
        &self,
        stream_name: S,
        expected_revision: ExpectedRevision,
        events: Vec<EventData>,
    ) -> crate::Result<BatchWriteResult> {
        let (sender, receiver) = oneshot::channel();
        let req = Req {
            id: uuid::Uuid::new_v4(),
            stream_name: stream_name.as_ref().to_string(),
            events,
            expected_revision,
        };

        let req = In { sender, req };

        if let Err(e) = self.sender.clone().send(BatchMsg::In(req)).await {
            error!("[sending-end] Batch-append stream is closed: {}", e);

            let status = tonic::Status::cancelled("Batch-append stream has been closed");
            return Err(crate::Error::ServerError(status.to_string()));
        }

        match receiver.await {
            Err(e) => {
                error!("[receiving-end] Batch-append stream is closed: {}", e);

                let status = tonic::Status::cancelled("Batch-append stream has been closed");

                Err(crate::Error::ServerError(status.to_string()))
            }

            Ok(result) => result,
        }
    }
}