rocketmq-model 1.0.0

Runtime-neutral RocketMQ domain models
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
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Debug;

use bytes::Bytes;
use cheetah_string::CheetahString;
// Use new unified error system

use crate::common::message::message_ext_broker_inner::MessageExtBrokerInner;
use crate::common::message::message_property::MessageProperties;
use crate::common::message::message_single::Message;
use crate::common::message::MessageTrait;
use crate::common::mix_all;

#[derive(Clone, Default, Debug)]
pub struct MessageBatch {
    ///`final_message` stores the batch-encoded messages.
    pub final_message: Message,

    ///`messages` stores the batch of initialized messages.
    pub messages: Vec<Message>,
}

impl MessageBatch {
    #[inline]
    fn has_delay_property(message: &Message) -> bool {
        message.delay_time_level() > 0
            || message.properties().delay_time_ms().unwrap_or(0) > 0
            || message.properties().delay_time_sec().unwrap_or(0) > 0
            || message.properties().deliver_time_ms().unwrap_or(0) > 0
    }

    /// Get an iterator over the messages in the batch.
    #[inline]
    pub fn iter(&self) -> std::slice::Iter<'_, Message> {
        self.messages.iter()
    }

    /// Get the number of messages in the batch.
    #[inline]
    pub fn len(&self) -> usize {
        self.messages.len()
    }

    /// Check if the batch is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.messages.is_empty()
    }

    pub fn generate_from_vec<M>(messages: Vec<M>) -> rocketmq_error::Result<MessageBatch>
    where
        M: MessageTrait,
    {
        if messages.is_empty() {
            return Err(crate::error::invalid_argument(
                "MessageBatch::generate_from_vec: messages is empty",
            ));
        }

        let message_list = messages.into_iter().map(MessageTrait::into_message).collect();

        Self::generate_from_messages(message_list)
    }

    /// Build a batch from owned [`Message`] values without cloning each message again.
    ///
    /// This keeps the same Java-compatible validation as [`Self::generate_from_vec`], but it is
    /// the preferred hot path when callers already normalized inputs to concrete `Message`s.
    pub fn generate_from_messages(messages: Vec<Message>) -> rocketmq_error::Result<MessageBatch> {
        if messages.is_empty() {
            return Err(crate::error::invalid_argument(
                "MessageBatch::generate_from_vec: messages is empty",
            ));
        }

        let mut first: Option<&Message> = None;
        for message in &messages {
            if Self::has_delay_property(message) {
                return Err(crate::error::invalid_argument(
                    "Delayed messages are not supported for batching",
                ));
            }
            if message.topic().starts_with(mix_all::RETRY_GROUP_TOPIC_PREFIX) {
                return Err(crate::error::invalid_argument(
                    "Retry group topic is not supported for batching",
                ));
            }

            if let Some(first_message) = first {
                if first_message.topic() != message.topic() {
                    return Err(crate::error::invalid_argument(
                        "The topic of the messages in one batch should be the same",
                    ));
                }
                if first_message.is_wait_store_msg_ok() != message.is_wait_store_msg_ok() {
                    return Err(crate::error::invalid_argument(
                        "The waitStoreMsgOK of the messages in one batch should the same",
                    ));
                }
            } else {
                first = Some(message);
            }
        }
        let Some(first) = first else {
            return Err(crate::error::invalid_argument(
                "MessageBatch::generate_from_vec: messages is empty",
            ));
        };
        let mut final_message = Message::default();
        final_message.set_topic(first.topic().clone());
        final_message.set_wait_store_msg_ok(first.is_wait_store_msg_ok());
        Ok(MessageBatch {
            final_message,
            messages,
        })
    }
}

impl IntoIterator for MessageBatch {
    type Item = Message;
    type IntoIter = std::vec::IntoIter<Message>;

    fn into_iter(self) -> Self::IntoIter {
        self.messages.into_iter()
    }
}

impl<'a> IntoIterator for &'a MessageBatch {
    type Item = &'a Message;
    type IntoIter = std::slice::Iter<'a, Message>;

    fn into_iter(self) -> Self::IntoIter {
        self.messages.iter()
    }
}

impl fmt::Display for MessageBatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let messages_str = self
            .messages
            .iter()
            .map(|msg| msg.to_string())
            .collect::<Vec<_>>()
            .join(", ");

        write!(
            f,
            "MessageBatch {{ final_message: {}, messages: {} }}",
            self.final_message, messages_str
        )
    }
}

#[allow(unused_variables)]
impl MessageTrait for MessageBatch {
    #[inline]
    fn put_property(&mut self, key: CheetahString, value: CheetahString) {
        self.final_message.properties_mut().as_map_mut().insert(key, value);
    }

    #[inline]
    fn clear_property(&mut self, name: &str) {
        self.final_message.properties_mut().as_map_mut().remove(name);
    }

    #[inline]
    fn property(&self, name: &CheetahString) -> Option<CheetahString> {
        self.final_message.properties().as_map().get(name).cloned()
    }

    fn property_ref(&self, name: &CheetahString) -> Option<&CheetahString> {
        self.final_message.properties().as_map().get(name)
    }

    #[inline]
    fn topic(&self) -> &CheetahString {
        self.final_message.topic()
    }

    #[inline]
    fn set_topic(&mut self, topic: CheetahString) {
        self.final_message.set_topic(topic);
    }

    #[inline]
    fn get_flag(&self) -> i32 {
        self.final_message.flag()
    }

    #[inline]
    fn set_flag(&mut self, flag: i32) {
        self.final_message.set_flag(flag);
    }

    #[inline]
    fn get_body(&self) -> Option<&Bytes> {
        self.final_message.get_body()
    }

    #[inline]
    fn set_body(&mut self, body: Bytes) {
        self.final_message.set_body(Some(body));
    }

    #[inline]
    fn get_properties(&self) -> &HashMap<CheetahString, CheetahString> {
        self.final_message.properties().as_map()
    }

    #[inline]
    fn set_properties(&mut self, properties: HashMap<CheetahString, CheetahString>) {
        *self.final_message.properties_mut() = MessageProperties::from_map(properties);
    }

    #[inline]
    fn transaction_id(&self) -> Option<&CheetahString> {
        MessageTrait::transaction_id(&self.final_message)
    }

    #[inline]
    fn set_transaction_id(&mut self, transaction_id: CheetahString) {
        *self.final_message.transaction_id_mut() = Some(transaction_id);
    }

    #[inline]
    fn get_compressed_body_mut(&mut self) -> Option<&mut Bytes> {
        self.final_message.body_mut().compressed_mut().as_mut()
    }

    #[inline]
    fn get_compressed_body(&self) -> Option<&Bytes> {
        self.final_message.compressed_body()
    }

    #[inline]
    fn set_compressed_body_mut(&mut self, compressed_body: Bytes) {
        self.final_message.set_compressed_body_mut(compressed_body);
    }

    #[inline]
    fn take_body(&mut self) -> Option<Bytes> {
        self.final_message.take_body()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;
    use cheetah_string::CheetahString;

    use super::*;

    fn create_test_message(topic: &str) -> Message {
        let mut msg = Message::default();
        msg.set_topic(CheetahString::from_slice(topic));
        msg.set_body(Some(Bytes::from_static(b"test body")));
        msg
    }

    #[test]
    fn test_generate_from_vec_ok() {
        let messages = vec![create_test_message("topic1"), create_test_message("topic1")];
        let result = MessageBatch::generate_from_vec(messages);
        assert!(result.is_ok());
        let batch = result.unwrap();
        assert_eq!(batch.messages.len(), 2);
        assert_eq!(batch.len(), 2);
        assert!(!batch.is_empty());
    }

    #[test]
    fn generate_from_vec_moves_concrete_message_body_storage() {
        let mut message = create_test_message("topic1");
        let body = Bytes::from(vec![b'x'; 128]);
        let body_ptr = body.as_ptr();
        message.set_body(Some(body));

        let batch = MessageBatch::generate_from_vec(vec![message]).expect("batch should build");

        assert_eq!(batch.messages[0].get_body().expect("message body").as_ptr(), body_ptr);
    }

    #[test]
    fn test_generate_from_messages_ok() {
        let messages = vec![create_test_message("topic1"), create_test_message("topic1")];
        let batch = MessageBatch::generate_from_messages(messages).unwrap();

        assert_eq!(batch.messages.len(), 2);
        assert_eq!(batch.final_message.topic().as_str(), "topic1");
    }

    #[test]
    fn test_generate_from_vec_empty() {
        let messages: Vec<Message> = vec![];
        let result = MessageBatch::generate_from_vec(messages);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.descriptor(), &rocketmq_error::CORE_ARGUMENT_INVALID);
    }

    #[test]
    fn test_generate_from_vec_different_topic() {
        let messages = vec![
            create_test_message("topic1"),
            create_test_message("topic2"), // Different topic
        ];
        let result = MessageBatch::generate_from_vec(messages);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.descriptor(), &rocketmq_error::CORE_ARGUMENT_INVALID);
    }

    #[test]
    fn test_generate_from_vec_delay_message() {
        let msg1 = create_test_message("topic1");
        let mut msg2 = create_test_message("topic1");
        msg2.set_delay_time_level(1); // Set delay level

        let messages = vec![msg1, msg2];
        let result = MessageBatch::generate_from_vec(messages);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.descriptor(), &rocketmq_error::CORE_ARGUMENT_INVALID);
    }

    #[test]
    fn test_generate_from_vec_delay_millis_message_matches_java_rejection() {
        let msg1 = create_test_message("topic1");
        let msg2 = Message::builder()
            .topic("topic1")
            .body(Bytes::from_static(b"test body"))
            .delay_millis(1000)
            .build_unchecked();

        let result = MessageBatch::generate_from_vec(vec![msg1, msg2]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.descriptor(), &rocketmq_error::CORE_ARGUMENT_INVALID);
    }

    #[test]
    fn test_generate_from_vec_delay_secs_message_matches_java_rejection() {
        let msg1 = create_test_message("topic1");
        let msg2 = Message::builder()
            .topic("topic1")
            .body(Bytes::from_static(b"test body"))
            .delay_secs(1)
            .build_unchecked();

        let result = MessageBatch::generate_from_vec(vec![msg1, msg2]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.descriptor(), &rocketmq_error::CORE_ARGUMENT_INVALID);
    }

    #[test]
    fn test_generate_from_vec_deliver_time_message_matches_java_rejection() {
        let msg1 = create_test_message("topic1");
        let msg2 = Message::builder()
            .topic("topic1")
            .body(Bytes::from_static(b"test body"))
            .deliver_time_ms(1000)
            .build_unchecked();

        let result = MessageBatch::generate_from_vec(vec![msg1, msg2]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.descriptor(), &rocketmq_error::CORE_ARGUMENT_INVALID);
    }

    #[test]
    fn test_generate_from_vec_retry_group() {
        let messages = vec![
            create_test_message("topic1"),
            create_test_message("%RETRY%topic1"), // Retry group
        ];
        let result = MessageBatch::generate_from_vec(messages);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.descriptor(), &rocketmq_error::CORE_ARGUMENT_INVALID);
    }

    #[test]
    fn test_generate_from_vec_different_wait_store_msg_ok() {
        let mut msg1 = create_test_message("topic1");
        let mut msg2 = create_test_message("topic1");
        msg1.set_wait_store_msg_ok(true);
        msg2.set_wait_store_msg_ok(false); // Different waitStoreMsgOK

        let messages = vec![msg1, msg2];
        let result = MessageBatch::generate_from_vec(messages);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.descriptor(), &rocketmq_error::CORE_ARGUMENT_INVALID);
    }

    #[test]
    fn test_iterator_slice() {
        let messages = vec![
            create_test_message("topic1"),
            create_test_message("topic1"),
            create_test_message("topic1"),
        ];
        let batch = MessageBatch::generate_from_vec(messages).unwrap();

        let count = batch.iter().count();
        assert_eq!(count, 3);
    }

    #[test]
    fn test_into_iterator() {
        let messages = vec![
            create_test_message("topic1"),
            create_test_message("topic1"),
            create_test_message("topic1"),
        ];
        let batch = MessageBatch::generate_from_vec(messages).unwrap();

        let count = batch.into_iter().count();
        assert_eq!(count, 3);
    }

    #[test]
    fn test_into_iterator_ref() {
        let messages = vec![
            create_test_message("topic1"),
            create_test_message("topic1"),
            create_test_message("topic1"),
        ];
        let batch = MessageBatch::generate_from_vec(messages).unwrap();

        let count = (&batch).into_iter().count();
        assert_eq!(count, 3);

        // Can still use batch after borrowing
        assert_eq!(batch.len(), 3);
    }

    #[test]
    fn test_batch_properties_inherited() {
        let mut msg1 = create_test_message("topic1");
        msg1.set_wait_store_msg_ok(true);

        let messages = vec![msg1.clone(), msg1];
        let batch = MessageBatch::generate_from_vec(messages).unwrap();

        assert_eq!(batch.final_message.topic().as_str(), "topic1");
        assert!(batch.final_message.is_wait_store_msg_ok());
    }

    #[test]
    fn test_display_format() {
        let messages = vec![create_test_message("topic1"), create_test_message("topic1")];
        let batch = MessageBatch::generate_from_vec(messages).unwrap();

        let display = format!("{}", batch);
        assert!(display.contains("MessageBatch"));
        assert!(display.contains("topic1"));
    }
}

#[derive(Debug, Default)]
pub struct MessageExtBatch {
    pub message_ext_broker_inner: MessageExtBrokerInner,
    pub is_inner_batch: bool,
    pub encoded_buff: Option<bytes::BytesMut>,
}

impl MessageExtBatch {
    pub fn wrap(&self) -> Option<Bytes> {
        self.message_ext_broker_inner.body()
    }

    pub fn get_tags(&self) -> Option<CheetahString> {
        self.message_ext_broker_inner.get_tags()
    }
}