Skip to main content

sierradb_server/request/
emappend.rs

1use std::time::{SystemTime, UNIX_EPOCH};
2
3use combine::error::StreamError;
4use combine::{Parser, attempt, choice, easy, many, many1};
5use indexmap::indexmap;
6use redis_protocol::resp3::types::BytesFrame;
7use sierradb::StreamId;
8use sierradb::bucket::PartitionId;
9use sierradb::database::{NewEvent, Transaction};
10use sierradb::id::{uuid_to_partition_hash, uuid_v7_with_partition_hash};
11use sierradb_cluster::write::execute::ExecuteTransaction;
12use sierradb_protocol::{ErrorCode, ExpectedVersion};
13use smallvec::SmallVec;
14use uuid::Uuid;
15
16use crate::error::MapRedisError;
17use crate::parser::{
18    FrameStream, data, event_id, expected_version, keyword, number_u64, partition_key, stream_id,
19    string,
20};
21use crate::request::{HandleRequest, array, map, number, simple_str};
22use crate::server::Conn;
23
24/// Append multiple events to streams in a single transaction.
25///
26/// # Syntax
27/// ```text
28/// EMAPPEND <partition_key> <stream_id1> <event_name1> [EVENT_ID <event_id1>] [EXPECTED_VERSION <version1>] [TIMESTAMP <timestamp>] [PAYLOAD <payload1>] [METADATA <metadata1>] [<stream_id2> <event_name2> ...]
29/// ```
30///
31/// # Parameters
32/// - `partition_key`: UUID that determines which partition all events will be
33///   written to
34/// - For each event:
35///   - `stream_id`: Stream identifier to append the event to
36///   - `event_name`: Name/type of the event
37///   - `event_id` (optional): UUID for the event (auto-generated if not
38///     provided)
39///   - `expected_version`: Expected stream version (`empty` for new streams, or
40///     version number). By default, `any` and `exists` are rejected unless
41///     `append.strict_versioning` is disabled.
42///   - `timestamp` (optional): Event timestamp in milliseconds
43///   - `payload` (optional): Event payload data
44///   - `metadata` (optional): Event metadata
45///
46/// # Example
47/// ```text
48/// EMAPPEND 550e8400-e29b-41d4-a716-446655440000 stream1 EventA EXPECTED_VERSION empty PAYLOAD '{"data":"value1"}' stream2 EventB EXPECTED_VERSION 0 PAYLOAD '{"data":"value2"}'
49/// ```
50///
51/// **Note:** All events are appended atomically in a single transaction.
52#[derive(Clone, Debug, Default, PartialEq, Eq)]
53pub struct EMAppend {
54    pub partition_key: Uuid,
55    pub events: Vec<Event>,
56}
57
58#[derive(Clone, Debug, Default, PartialEq, Eq)]
59pub struct Event {
60    pub stream_id: StreamId,
61    pub event_name: String,
62    pub event_id: Option<Uuid>,
63    pub expected_version: ExpectedVersion,
64    pub timestamp: Option<u64>,
65    pub payload: Vec<u8>,
66    pub metadata: Vec<u8>,
67}
68
69impl Event {
70    fn parser<'a>() -> impl Parser<FrameStream<'a>, Output = Event> + 'a {
71        (
72            stream_id(),
73            string().expected("event name"),
74            many::<Vec<_>, _, _>(OptionalArg::parser()),
75        )
76            .and_then(|(stream_id, event_name, args)| {
77                let mut cmd = Event {
78                    stream_id,
79                    event_name: event_name.to_string(),
80                    ..Default::default()
81                };
82
83                for arg in args {
84                    match arg {
85                        OptionalArg::EventId(event_id) => {
86                            if cmd.event_id.is_some() {
87                                return Err(easy::Error::message_format(
88                                    "event id already specified",
89                                ));
90                            }
91
92                            cmd.event_id = Some(event_id);
93                        }
94                        OptionalArg::ExpectedVersion(expected_version) => {
95                            if !matches!(cmd.expected_version, ExpectedVersion::Any) {
96                                return Err(easy::Error::message_format(
97                                    "expected version already specified",
98                                ));
99                            }
100
101                            cmd.expected_version = expected_version;
102                        }
103                        OptionalArg::Timestamp(timestamp) => {
104                            if cmd.timestamp.is_some() {
105                                return Err(easy::Error::message_format(
106                                    "timestamp already specified",
107                                ));
108                            }
109
110                            cmd.timestamp = Some(timestamp);
111                        }
112                        OptionalArg::Payload(payload) => {
113                            if !cmd.payload.is_empty() {
114                                return Err(easy::Error::message_format(
115                                    "payload already specified",
116                                ));
117                            }
118
119                            cmd.payload = payload.to_vec();
120                        }
121                        OptionalArg::Metadata(metadata) => {
122                            if !cmd.metadata.is_empty() {
123                                return Err(easy::Error::message_format(
124                                    "metadata already specified",
125                                ));
126                            }
127
128                            cmd.metadata = metadata.to_vec();
129                        }
130                    }
131                }
132
133                Ok(cmd)
134            })
135    }
136}
137
138#[derive(Debug, Clone, PartialEq)]
139enum OptionalArg<'a> {
140    EventId(Uuid),
141    ExpectedVersion(ExpectedVersion),
142    Timestamp(u64),
143    Payload(&'a [u8]),
144    Metadata(&'a [u8]),
145}
146
147impl<'a> OptionalArg<'a> {
148    fn parser() -> impl Parser<FrameStream<'a>, Output = OptionalArg<'a>> + 'a {
149        let event_id = keyword("EVENT_ID")
150            .with(event_id())
151            .map(OptionalArg::EventId);
152        let expected_version = keyword("EXPECTED_VERSION")
153            .with(expected_version())
154            .map(OptionalArg::ExpectedVersion);
155        let timestamp = keyword("TIMESTAMP")
156            .with(number_u64())
157            .map(OptionalArg::Timestamp);
158        let payload = keyword("PAYLOAD").with(data()).map(OptionalArg::Payload);
159        let metadata = keyword("METADATA").with(data()).map(OptionalArg::Metadata);
160
161        choice!(
162            attempt(event_id),
163            attempt(expected_version),
164            attempt(timestamp),
165            attempt(payload),
166            attempt(metadata)
167        )
168    }
169}
170
171impl EMAppend {
172    pub fn parser<'a>() -> impl Parser<FrameStream<'a>, Output = EMAppend> + 'a {
173        (partition_key(), many1::<Vec<_>, _, _>(Event::parser())).map(|(partition_key, events)| {
174            EMAppend {
175                partition_key,
176                events,
177            }
178        })
179    }
180}
181
182impl HandleRequest for EMAppend {
183    type Error = String;
184    type Ok = EMAppendResp;
185
186    async fn handle_request(self, conn: &mut Conn) -> Result<Option<Self::Ok>, Self::Error> {
187        if conn.strict_versioning {
188            for event in &self.events {
189                if !event.expected_version.is_strict_allowed() {
190                    return Err(ErrorCode::InvalidArg
191                        .with_message(format!(
192                            "strict versioning mode rejects EXPECTED_VERSION {}",
193                            event.expected_version
194                        ))
195                        .to_string());
196                }
197            }
198        }
199
200        let partition_hash = uuid_to_partition_hash(self.partition_key);
201        let partition_id = partition_hash % conn.num_partitions;
202        let now = SystemTime::now()
203            .duration_since(UNIX_EPOCH)
204            .map_redis_err()?
205            .as_nanos() as u64;
206
207        let events: SmallVec<[_; 4]> = self.events
208            .into_iter()
209            .map(|event| {
210                let event_id = event
211                    .event_id
212                    .unwrap_or_else(|| uuid_v7_with_partition_hash(partition_hash));
213                let timestamp = event
214                    .timestamp
215                    .map(|timestamp| {
216                        timestamp.checked_mul(1_000_000).ok_or(
217                            ErrorCode::InvalidArg
218                                .with_message(
219                                    "invalid timestamp format: expected milliseconds, got nanoseconds",
220                                )
221                                .to_string(),
222                        )
223                    })
224                    .transpose()?
225                    .unwrap_or(now);
226                Ok(NewEvent {
227                    event_id,
228                    stream_id: event.stream_id,
229                    stream_version: event.expected_version,
230                    event_name: event.event_name,
231                    timestamp,
232                    metadata: event.metadata,
233                    payload: event.payload,
234                })
235            })
236            .collect::<Result<_, String>>()?;
237        let event_ids_timestamps_streams: SmallVec<[_; 4]> = events
238            .iter()
239            .map(|event| (event.event_id, event.timestamp, event.stream_id.clone()))
240            .collect();
241
242        let transaction = Transaction::new(self.partition_key, partition_id, events)
243            .map_err(|err| ErrorCode::InvalidArg.with_message(err))?;
244
245        let result = conn
246            .cluster_ref
247            .ask(ExecuteTransaction::new(transaction))
248            .await
249            .map_redis_err()?;
250
251        let mut stream_current_version = result.stream_versions;
252        let mut events: Vec<EventInfo> = event_ids_timestamps_streams
253            .into_iter()
254            .rev()
255            .map(|(event_id, timestamp, stream_id)| {
256                let version = stream_current_version.get_mut(&stream_id).unwrap();
257                let stream_version = *version;
258                *version -= 1;
259                EventInfo {
260                    event_id,
261                    stream_id,
262                    stream_version,
263                    timestamp,
264                }
265            })
266            .collect();
267
268        events.reverse();
269
270        Ok(Some(EMAppendResp {
271            partition_key: self.partition_key,
272            partition_id,
273            first_partition_sequence: result.first_partition_sequence,
274            last_partition_sequence: result.last_partition_sequence,
275            events,
276        }))
277    }
278}
279
280pub struct EMAppendResp {
281    partition_key: Uuid,
282    partition_id: PartitionId,
283    first_partition_sequence: u64,
284    last_partition_sequence: u64,
285    events: Vec<EventInfo>,
286}
287
288struct EventInfo {
289    event_id: Uuid,
290    stream_id: StreamId,
291    stream_version: u64,
292    timestamp: u64,
293}
294
295impl From<EMAppendResp> for BytesFrame {
296    fn from(resp: EMAppendResp) -> Self {
297        map(indexmap! {
298            simple_str("partition_key") => simple_str(resp.partition_key.to_string()),
299            simple_str("partition_id") => number(resp.partition_id as i64),
300            simple_str("first_partition_sequence") => number(resp.first_partition_sequence as i64),
301            simple_str("last_partition_sequence") => number(resp.last_partition_sequence as i64),
302            simple_str("events") => array(resp.events.into_iter().map(BytesFrame::from).collect()),
303        })
304    }
305}
306
307impl From<EventInfo> for BytesFrame {
308    fn from(info: EventInfo) -> Self {
309        map(indexmap! {
310            simple_str("event_id") => simple_str(info.event_id.to_string()),
311            simple_str("stream_id") => simple_str(info.stream_id.to_string()),
312            simple_str("stream_version") => number(info.stream_version as i64),
313            simple_str("timestamp") => number((info.timestamp / 1_000_000) as i64),
314        })
315    }
316}