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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
/********************************************************************************
 * Copyright (c) 2024 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Apache License Version 2.0 which is available at
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * SPDX-License-Identifier: Apache-2.0
 ********************************************************************************/

use bytes::Bytes;
use protobuf::{well_known_types::any::Any, Enum, EnumOrUnknown, Message, MessageFull};

use crate::uattributes::NotificationValidator;
use crate::{
    PublishValidator, RequestValidator, ResponseValidator, UAttributes, UAttributesValidator,
    UCode, UMessage, UMessageError, UMessageType, UPayloadFormat, UPriority, UUri, UUID,
};

const PRIORITY_DEFAULT: UPriority = UPriority::UPRIORITY_CS1;

/// A builder for creating [`UMessage`]s.
///
/// Messages are being used by a uEntity to inform other entities about the occurrence of events
/// and/or to invoke service operations provided by other entities.
pub struct UMessageBuilder {
    comm_status: Option<EnumOrUnknown<UCode>>,
    message_id: Option<UUID>,
    message_type: UMessageType,
    payload: Option<Bytes>,
    payload_format: UPayloadFormat,
    permission_level: Option<u32>,
    priority: UPriority,
    request_id: Option<UUID>,
    sink: Option<UUri>,
    source: Option<UUri>,
    token: Option<String>,
    traceparent: Option<String>,
    ttl: Option<u32>,
    validator: Box<dyn UAttributesValidator>,
}

impl Default for UMessageBuilder {
    fn default() -> Self {
        UMessageBuilder {
            comm_status: None,
            message_id: None,
            message_type: UMessageType::UMESSAGE_TYPE_UNSPECIFIED,
            payload: None,
            payload_format: UPayloadFormat::UPAYLOAD_FORMAT_UNSPECIFIED,
            permission_level: None,
            priority: UPriority::UPRIORITY_UNSPECIFIED,
            request_id: None,
            sink: None,
            source: None,
            token: None,
            traceparent: None,
            ttl: None,
            validator: Box::new(PublishValidator),
        }
    }
}

impl UMessageBuilder {
    /// Gets a builder for creating *publish* messages.
    ///
    /// A publish message is used to notify all interested consumers of an event that has occurred.
    /// Consumers usually indicate their interest by *subscribing* to a particular topic.
    ///
    /// # Arguments
    ///
    /// * `topic` - The topic to publish the message to.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let topic = UUri::try_from("//my-vehicle/4210/1/B24D")?;
    /// let message = UMessageBuilder::publish(topic.clone())
    ///                    .build_with_payload("closed", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert_eq!(message.attributes.type_, UMessageType::UMESSAGE_TYPE_PUBLISH.into());
    /// assert_eq!(message.attributes.priority, UPriority::UPRIORITY_UNSPECIFIED.into());
    /// assert_eq!(message.attributes.source, Some(topic).into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn publish(topic: UUri) -> UMessageBuilder {
        UMessageBuilder {
            validator: Box::new(PublishValidator),
            message_type: UMessageType::UMESSAGE_TYPE_PUBLISH,
            source: Some(topic),
            ..Default::default()
        }
    }

    /// Gets a builder for creating *notification* messages.
    ///
    /// A notification is used to inform a specific consumer about an event that has occurred.
    ///
    /// # Arguments
    ///
    /// * `origin` - The component that the notification originates from.
    /// * `destination` - The URI identifying the destination to send the notification to.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let origin = UUri::try_from("//my-vehicle/4210/5/F20B")?;
    /// let destination = UUri::try_from("//my-cloud/CCDD/2/0")?;
    /// let message = UMessageBuilder::notification(origin.clone(), destination.clone())
    ///                    .build_with_payload("unexpected movement", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert_eq!(message.attributes.type_, UMessageType::UMESSAGE_TYPE_NOTIFICATION.into());
    /// assert_eq!(message.attributes.priority, UPriority::UPRIORITY_UNSPECIFIED.into());
    /// assert_eq!(message.attributes.source, Some(origin).into());
    /// assert_eq!(message.attributes.sink, Some(destination).into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn notification(origin: UUri, destination: UUri) -> UMessageBuilder {
        UMessageBuilder {
            validator: Box::new(NotificationValidator),
            message_type: UMessageType::UMESSAGE_TYPE_NOTIFICATION,
            source: Some(origin),
            sink: Some(destination),
            ..Default::default()
        }
    }

    /// Gets a builder for creating RPC *request* messages.
    ///
    /// A request message is used to invoke a service's method with some input data, expecting
    /// the service to reply with a response message which is correlated by means of the `request_id`.
    ///
    /// The builder will be initialized with [`UPriority::UPRIORITY_CS4`].
    ///
    /// # Arguments
    ///
    /// * `method_to_invoke` - The URI identifying the method to invoke.
    /// * `reply_to_address` - The URI that the sender of the request expects the response message at.
    /// * `ttl` - The number of milliseconds after which the request should no longer be processed
    ///           by the target service. The value is capped at [`i32::MAX`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let method_to_invoke = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let message = UMessageBuilder::request(method_to_invoke.clone(), reply_to_address.clone(), 5000)
    ///                    .build_with_payload("lock", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert_eq!(message.attributes.type_, UMessageType::UMESSAGE_TYPE_REQUEST.into());
    /// assert_eq!(message.attributes.priority, UPriority::UPRIORITY_CS4.into());
    /// assert_eq!(message.attributes.source, Some(reply_to_address).into());
    /// assert_eq!(message.attributes.sink, Some(method_to_invoke).into());
    /// assert_eq!(message.attributes.ttl, Some(5000));
    /// # Ok(())
    /// # }
    /// ```
    pub fn request(method_to_invoke: UUri, reply_to_address: UUri, ttl: u32) -> UMessageBuilder {
        UMessageBuilder {
            validator: Box::new(RequestValidator),
            message_type: UMessageType::UMESSAGE_TYPE_REQUEST,
            source: Some(reply_to_address),
            sink: Some(method_to_invoke),
            ttl: Some(ttl),
            priority: UPriority::UPRIORITY_CS4,
            ..Default::default()
        }
    }

    /// Gets a builder for creating RPC *response* messages.
    ///
    /// A response message is used to send the outcome of processing a request message
    /// to the original sender of the request message.
    ///
    /// The builder will be initialized with [`UPriority::UPRIORITY_CS4`].
    ///
    /// # Arguments
    ///
    /// * `reply_to_address` - The URI that the sender of the request expects to receive the response message at.
    /// * `request_id` - The identifier of the request that this is the response to.
    /// * `invoked_method` - The URI identifying the method that has been invoked and which the created message is
    ///                      the outcome of.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let invoked_method = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let request_id = UUID::build();
    /// // a service implementation would normally use
    /// // `UMessageBuilder::response_for_request(&request_message.attributes)` instead
    /// let message = UMessageBuilder::response(reply_to_address.clone(), request_id.clone(), invoked_method.clone())
    ///                    .build()?;
    /// assert_eq!(message.attributes.type_, UMessageType::UMESSAGE_TYPE_RESPONSE.into());
    /// assert_eq!(message.attributes.priority, UPriority::UPRIORITY_CS4.into());
    /// assert_eq!(message.attributes.source, Some(invoked_method).into());
    /// assert_eq!(message.attributes.sink, Some(reply_to_address).into());
    /// assert_eq!(message.attributes.reqid, Some(request_id).into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn response(
        reply_to_address: UUri,
        request_id: UUID,
        invoked_method: UUri,
    ) -> UMessageBuilder {
        UMessageBuilder {
            validator: Box::new(ResponseValidator),
            message_type: UMessageType::UMESSAGE_TYPE_RESPONSE,
            source: Some(invoked_method),
            sink: Some(reply_to_address),
            request_id: Some(request_id),
            priority: UPriority::UPRIORITY_CS4,
            ..Default::default()
        }
    }

    /// Gets a builder for creating RPC *response* messages in reply to a *request*.
    ///
    /// A response message is used to send the outcome of processing a request message
    /// to the original sender of the request message.
    ///
    /// The builder will be initialized with values from the given request attributes.
    ///
    /// # Arguments
    ///
    /// * `request_attributes` - The attributes from the request message. The response message builder will be initialized
    ///                          with the corresponding attribute values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let method_to_invoke = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let request_message_id = UUID::build();
    /// let request_message = UMessageBuilder::request(method_to_invoke.clone(), reply_to_address.clone(), 5000)
    ///                           .with_message_id(request_message_id.clone()) // normally not needed, used only for asserts below
    ///                           .build_with_payload("lock", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    ///
    /// let response_message = UMessageBuilder::response_for_request(&request_message.attributes)
    ///                           .with_priority(UPriority::UPRIORITY_CS5)
    ///                           .build()?;
    /// assert_eq!(response_message.attributes.type_, UMessageType::UMESSAGE_TYPE_RESPONSE.into());
    /// assert_eq!(response_message.attributes.priority, UPriority::UPRIORITY_CS5.into());
    /// assert_eq!(response_message.attributes.source, Some(method_to_invoke).into());
    /// assert_eq!(response_message.attributes.sink, Some(reply_to_address).into());
    /// assert_eq!(response_message.attributes.reqid, Some(request_message_id).into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn response_for_request(request_attributes: &UAttributes) -> UMessageBuilder {
        UMessageBuilder {
            validator: Box::new(ResponseValidator),
            message_type: UMessageType::UMESSAGE_TYPE_RESPONSE,
            source: request_attributes.sink.as_ref().cloned(),
            sink: request_attributes.source.as_ref().cloned(),
            request_id: request_attributes.id.as_ref().cloned(),
            priority: request_attributes
                .priority
                .enum_value_or(UPriority::UPRIORITY_CS4),
            ..Default::default()
        }
    }

    /// Sets the message's identifier.
    ///
    /// Every message must have an identifier. If this function is not used, an identifier will be
    /// generated and set on the message when one of the `build` functions is called on the
    /// `UMessageBuilder`.
    ///
    /// It's more typical to _not_ use this function, but could have edge case uses.
    ///
    /// # Arguments
    ///
    /// * `message_id` - The identifier to use.
    ///
    /// # Returns
    ///
    /// The builder.
    ///
    /// # Panics
    ///
    /// Panics if the given UUID is not a [valid uProtocol UUID](`UUID::is_uprotocol_uuid`).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let topic = UUri::try_from("//my-vehicle/4210/1/B24D")?;
    /// let mut builder = UMessageBuilder::publish(topic);
    /// builder.with_priority(UPriority::UPRIORITY_CS2);
    /// let message_one = builder
    ///                     .with_message_id(UUID::build())
    ///                     .build_with_payload("closed", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// let message_two = builder
    ///                     // use new message ID but retain all other attributes
    ///                     .with_message_id(UUID::build())
    ///                     .build_with_payload("open", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert_ne!(message_one.attributes.id, message_two.attributes.id);
    /// assert_eq!(message_one.attributes.source, message_two.attributes.source);
    /// assert_eq!(message_one.attributes.priority, UPriority::UPRIORITY_CS2.into());
    /// assert_eq!(message_two.attributes.priority, UPriority::UPRIORITY_CS2.into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_message_id(&mut self, message_id: UUID) -> &mut UMessageBuilder {
        assert!(
            message_id.is_uprotocol_uuid(),
            "Message ID must be a valid uProtocol UUID"
        );
        self.message_id = Some(message_id);
        self
    }

    /// Sets the message's priority.
    ///
    /// If not set explicitly, the default priority as defined in the
    /// [uProtocol specification](https://github.com/eclipse-uprotocol/up-spec/blob/main/basics/qos.adoc)
    /// is used.
    ///
    /// # Arguments
    ///
    /// * `priority` - The priority to be used for sending the message.
    ///
    /// # Returns
    ///
    /// The builder.
    ///
    /// # Panics
    ///
    /// if the builder is used for creating an RPC message but the given priority is less than CS4.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let topic = UUri::try_from("//my-vehicle/4210/1/B24D")?;
    /// let message = UMessageBuilder::publish(topic)
    ///                   .with_priority(UPriority::UPRIORITY_CS5)
    ///                   .build_with_payload("closed", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert_eq!(message.attributes.priority, UPriority::UPRIORITY_CS5.into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_priority(&mut self, priority: UPriority) -> &mut UMessageBuilder {
        if self.message_type == UMessageType::UMESSAGE_TYPE_REQUEST
            || self.message_type == UMessageType::UMESSAGE_TYPE_RESPONSE
        {
            assert!(priority.value() >= UPriority::UPRIORITY_CS4.value())
        }
        if priority != PRIORITY_DEFAULT {
            // only set priority explicitly if it differs from the default priority
            self.priority = priority;
        } else {
            // in all other cases set to UNSPECIFIED which will result in the
            // priority not being included in the serialized protobuf
            self.priority = UPriority::UPRIORITY_UNSPECIFIED;
        }
        self
    }

    /// Sets the message's time-to-live.
    ///
    /// # Arguments
    ///
    /// * `ttl` - The time-to-live in milliseconds. The value is capped at [`i32::MAX`].
    ///
    /// # Returns
    ///
    /// The builder.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let invoked_method = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let request_msg_id = UUID::build();
    /// // a service implementation would normally use
    /// // `UMessageBuilder::response_for_request(&request_message.attributes)` instead
    /// let message = UMessageBuilder::response(reply_to_address, request_msg_id, invoked_method)
    ///                     .with_ttl(2000)
    ///                     .build()?;
    /// assert_eq!(message.attributes.ttl, Some(2000));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_ttl(&mut self, ttl: u32) -> &mut UMessageBuilder {
        self.ttl = Some(ttl);
        self
    }

    /// Sets the message's authorization token used for TAP.
    ///
    /// # Arguments
    ///
    /// * `token` - The token.
    ///
    /// # Returns
    ///
    /// The builder.
    ///
    /// # Panics
    ///
    /// * if the message is not an RPC request message
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let method_to_invoke = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let token = String::from("this-is-my-token");
    /// let message = UMessageBuilder::request(method_to_invoke, reply_to_address, 5000)
    ///                     .with_token(token.clone())
    ///                     .build_with_payload("lock", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert_eq!(message.attributes.token, Some(token));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_token<T: Into<String>>(&mut self, token: T) -> &mut UMessageBuilder {
        assert!(self.message_type == UMessageType::UMESSAGE_TYPE_REQUEST);
        self.token = Some(token.into());
        self
    }

    /// Sets the message's permission level.
    ///
    /// # Arguments
    ///
    /// * `level` - The level.
    ///
    /// # Returns
    ///
    /// The builder.
    ///
    /// # Panics
    ///
    /// * if the given level is greater than [`i32::MAX`]
    /// * if the message is not an RPC request message
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UCode, UMessageBuilder, UPayloadFormat, UPriority, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let method_to_invoke = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let message = UMessageBuilder::request(method_to_invoke, reply_to_address, 5000)
    ///                     .with_permission_level(12)
    ///                     .build_with_payload("lock", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert_eq!(message.attributes.permission_level, Some(12));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_permission_level(&mut self, level: u32) -> &mut UMessageBuilder {
        assert!(self.message_type == UMessageType::UMESSAGE_TYPE_REQUEST);
        self.permission_level = Some(level);
        self
    }

    /// Sets the message's communication status.
    ///
    /// # Arguments
    ///
    /// * `comm_status` - The status.
    ///
    /// # Returns
    ///
    /// The builder.
    ///
    /// # Panics
    ///
    /// * if the message is not an RPC response message
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UCode, UMessageBuilder, UPriority, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let invoked_method = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let request_msg_id = UUID::build();
    /// // a service implementation would normally use
    /// // `UMessageBuilder::response_for_request(&request_message.attributes)` instead
    /// let message = UMessageBuilder::response(reply_to_address, request_msg_id, invoked_method)
    ///                     .with_comm_status(UCode::OK)
    ///                     .build()?;
    /// assert_eq!(message.attributes.commstatus, Some(UCode::OK.into()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_comm_status(&mut self, comm_status: UCode) -> &mut UMessageBuilder {
        assert!(self.message_type == UMessageType::UMESSAGE_TYPE_RESPONSE);
        self.comm_status = Some(comm_status.into());
        self
    }

    /// Sets the identifier of the W3C Trace Context to convey in the message.
    ///
    /// # Arguments
    ///
    /// * `traceparent` - The identifier.
    ///
    /// # Returns
    ///
    /// The builder.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let topic = UUri::try_from("//my-vehicle/4210/1/B24D")?;
    /// let traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
    /// let message = UMessageBuilder::publish(topic.clone())
    ///                    .with_traceparent(traceparent)
    ///                    .build_with_payload("closed", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert_eq!(message.attributes.traceparent, Some(traceparent.to_string()));
    /// # Ok(())
    /// # }
    pub fn with_traceparent<T: Into<String>>(&mut self, traceparent: T) -> &mut UMessageBuilder {
        self.traceparent = Some(traceparent.into());
        self
    }

    /// Creates the message based on the builder's state.
    ///
    /// # Returns
    ///
    /// A message ready to be sent using [`crate::UTransport::send`].
    ///
    /// # Errors
    ///
    /// If the properties set on the builder do not represent a consistent set of [`UAttributes`],
    /// a [`UMessageError::AttributesValidationError`] is returned.
    ///
    /// # Examples
    ///
    /// ## Not setting `id` explicitly with [`UMessageBuilder::with_message_id()']
    ///
    /// The recommended way to use the `UMessageBuilder`.
    ///
    /// ```rust
    /// use up_rust::{UAttributes, UAttributesValidators, UMessageBuilder, UMessageError, UMessageType, UPriority, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let invoked_method = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// // a service implementation would normally use
    /// // `UMessageBuilder::response_for_request(&request_message.attributes)` instead
    /// let result = UMessageBuilder::response(reply_to_address, UUID::build(), invoked_method)
    ///                     .build();
    /// assert!(result.is_ok());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Setting `id` explicitly with [`UMessageBuilder::with_message_id()']
    ///
    /// Note that explicitly using [`UMessageBuilder::with_message_id()'] is not required as shown
    /// above.
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPriority, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let invoked_method = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let message_id = UUID::build();
    /// // a service implementation would normally use
    /// // `UMessageBuilder::response_for_request(&request_message.attributes)` instead
    /// let message = UMessageBuilder::response(reply_to_address, UUID::build(), invoked_method)
    ///                     .with_message_id(message_id.clone())
    ///                     .build()?;
    /// assert_eq!(message.attributes.id, Some(message_id).into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(&self) -> Result<UMessage, UMessageError> {
        let message_id = self
            .message_id
            .clone()
            .map_or_else(|| Some(UUID::build()), Some);
        let attributes = UAttributes {
            commstatus: self.comm_status,
            id: message_id.into(),
            payload_format: self.payload_format.into(),
            permission_level: self.permission_level,
            priority: self.priority.into(),
            reqid: self.request_id.clone().into(),
            sink: self.sink.clone().into(),
            source: self.source.clone().into(),
            token: self.token.clone(),
            traceparent: self.traceparent.clone(),
            ttl: self.ttl,
            type_: self.message_type.into(),
            ..Default::default()
        };
        self.validator
            .validate(&attributes)
            .map_err(UMessageError::from)
            .map(|_| UMessage {
                attributes: Some(attributes).into(),
                payload: self.payload.to_owned(),
                ..Default::default()
            })
    }

    /// Creates the message based on the builder's state and some payload.
    ///
    /// # Arguments
    ///
    /// * `payload` - The data to set as payload.
    /// * `format` - The payload format.
    ///
    /// # Returns
    ///
    /// A message ready to be sent using [`crate::UTransport::send`].
    ///
    /// # Errors
    ///
    /// If the properties set on the builder do not represent a consistent set of [`UAttributes`],
    /// a [`UMessageError::AttributesValidationError`] is returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let topic = UUri::try_from("//my-vehicle/4210/1/B24D")?;
    /// let message = UMessageBuilder::publish(topic)
    ///                    .build_with_payload("locked", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)?;
    /// assert!(message.payload.is_some());
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_with_payload<T: Into<Bytes>>(
        &mut self,
        payload: T,
        format: UPayloadFormat,
    ) -> Result<UMessage, UMessageError> {
        self.payload = Some(payload.into());
        self.payload_format = format;

        self.build()
    }

    /// Creates the message based on the builder's state and some payload.
    ///
    /// # Arguments
    ///
    /// * `payload` - The data to set as payload.
    ///
    /// # Returns
    ///
    /// A message ready to be sent using [`crate::UTransport::send`]. The message will have
    /// [`UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF`] set as its payload format.
    ///
    /// # Errors
    ///
    /// If the given payload cannot be serialized into a protobuf byte array, a [`UMessageError::DataSerializationError`] is returned.
    /// If the properties set on the builder do not represent a consistent set of [`UAttributes`],
    /// a [`UMessageError::AttributesValidationError`] is returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UCode, UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UStatus, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let invoked_method = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let request_id = UUID::build();
    /// // a service implementation would normally use
    /// // `UMessageBuilder::response_for_request(&request_message.attributes)` instead
    /// let message = UMessageBuilder::response(reply_to_address, request_id, invoked_method)
    ///                    .with_comm_status(UCode::INVALID_ARGUMENT)
    ///                    .build_with_protobuf_payload(&UStatus::fail("failed to parse request"))?;
    /// assert!(message.payload.is_some());
    /// assert_eq!(message.attributes.payload_format.enum_value().unwrap(), UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF);
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_with_protobuf_payload<T: Message>(
        &mut self,
        payload: &T,
    ) -> Result<UMessage, UMessageError> {
        payload
            .write_to_bytes()
            .map_err(UMessageError::from)
            .and_then(|serialized_payload| {
                self.build_with_payload(
                    serialized_payload,
                    UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF,
                )
            })
    }

    /// Creates the message based on the builder's state and some payload.
    ///
    /// # Arguments
    ///
    /// * `payload` - The data to set as payload.
    ///
    /// # Returns
    ///
    /// A message ready to be sent using [`crate::UTransport::send`]. The message will have
    /// [`UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF_WRAPPED_IN_ANY`] set as its payload format.
    ///
    /// # Errors
    ///
    /// If the given payload cannot be serialized into a protobuf byte array, a [`UMessageError::DataSerializationError`] is returned.
    /// If the properties set on the builder do not represent a consistent set of [`UAttributes`],
    /// a [`UMessageError::AttributesValidationError`] is returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UCode, UMessageBuilder, UMessageType, UPayloadFormat, UPriority, UStatus, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let invoked_method = UUri::try_from("//my-vehicle/4210/5/64AB")?;
    /// let reply_to_address = UUri::try_from("//my-cloud/BA4C/1/0")?;
    /// let request_id = UUID::build();
    /// // a service implementation would normally use
    /// // `UMessageBuilder::response_for_request(&request_message.attributes)` instead
    /// let message = UMessageBuilder::response(reply_to_address, request_id, invoked_method)
    ///                    .with_comm_status(UCode::INVALID_ARGUMENT)
    ///                    .build_with_wrapped_protobuf_payload(&UStatus::fail("failed to parse request"))?;
    /// assert!(message.payload.is_some());
    /// assert_eq!(message.attributes.payload_format.enum_value().unwrap(), UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF_WRAPPED_IN_ANY);
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_with_wrapped_protobuf_payload<T: MessageFull>(
        &mut self,
        payload: &T,
    ) -> Result<UMessage, UMessageError> {
        Any::pack(payload)
            .map_err(UMessageError::DataSerializationError)
            .and_then(|any| any.write_to_bytes().map_err(UMessageError::from))
            .and_then(|serialized_payload| {
                self.build_with_payload(
                    serialized_payload,
                    UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF_WRAPPED_IN_ANY,
                )
            })
    }
}

#[cfg(test)]
mod tests {
    use crate::UCode;

    use super::*;

    use test_case::test_case;

    const METHOD_TO_INVOKE: &str = "//my-vehicle/4D123/2/6FA3";
    const REPLY_TO_ADDRESS: &str = "//my-cloud/9CB3/1/0";
    const TOPIC: &str = "//my-vehicle/4210/1/B24D";

    #[test]
    #[should_panic]
    fn test_with_message_id_panics_for_invalid_uuid() {
        let invalid_message_id = UUID {
            msb: 0x00000000000000ab_u64,
            lsb: 0x0000000000018000_u64,
            ..Default::default()
        };
        let topic = UUri::try_from(TOPIC).expect("should have been able to create UUri");
        UMessageBuilder::publish(topic).with_message_id(invalid_message_id);
    }

    #[test_case(Some(5), None, None; "with permission level")]
    #[test_case(None, Some(UCode::NOT_FOUND), None; "with commstatus")]
    #[test_case(None, None, Some(String::from("my-token")); "with token")]
    #[should_panic]
    fn test_publish_message_builder_panics(
        perm_level: Option<u32>,
        comm_status: Option<UCode>,
        token: Option<String>,
    ) {
        let topic = UUri::try_from(TOPIC).expect("should have been able to create UUri");
        let mut builder = UMessageBuilder::publish(topic);
        if let Some(level) = perm_level {
            builder.with_permission_level(level);
        } else if let Some(status_code) = comm_status {
            builder.with_comm_status(status_code);
        } else if let Some(t) = token {
            builder.with_token(t);
        }
    }

    #[test_case(Some(5), None; "with permission level")]
    #[test_case(None, Some(String::from("my-token")); "with token")]
    #[should_panic]
    fn test_response_message_builder_panics(perm_level: Option<u32>, token: Option<String>) {
        let request_id = UUID::build();
        let method_to_invoke = UUri::try_from(METHOD_TO_INVOKE)
            .expect("should have been able to create destination UUri");
        let reply_to_address = UUri::try_from(REPLY_TO_ADDRESS)
            .expect("should have been able to create reply-to UUri");
        let mut builder = UMessageBuilder::response(reply_to_address, request_id, method_to_invoke);

        if let Some(level) = perm_level {
            builder.with_permission_level(level);
        } else if let Some(t) = token {
            builder.with_token(t);
        }
    }

    #[test_case(Some(UCode::NOT_FOUND), None; "for comm status")]
    #[should_panic]
    fn test_request_message_builder_panics(comm_status: Option<UCode>, perm_level: Option<u32>) {
        let method_to_invoke = UUri::try_from(METHOD_TO_INVOKE)
            .expect("should have been able to create destination UUri");
        let reply_to_address = UUri::try_from(REPLY_TO_ADDRESS)
            .expect("should have been able to create reply-to UUri");
        let mut builder = UMessageBuilder::request(method_to_invoke, reply_to_address, 5000);

        if let Some(status) = comm_status {
            builder.with_comm_status(status);
        } else if let Some(level) = perm_level {
            builder.with_permission_level(level);
        }
    }

    #[test]
    fn test_build_supports_repeated_invocation() {
        let topic = UUri::try_from(TOPIC).expect("should have been able to create UUri");
        let mut builder = UMessageBuilder::publish(topic);
        let message_one = builder
            .with_message_id(UUID::build())
            .build_with_payload("locked", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)
            .expect("should have been able to create message");
        let message_two = builder
            .with_message_id(UUID::build())
            .build_with_payload("unlocked", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)
            .expect("should have been able to create message");
        assert_eq!(message_one.attributes.type_, message_two.attributes.type_);
        assert_ne!(message_one.attributes.id, message_two.attributes.id);
        assert_eq!(message_one.attributes.source, message_two.attributes.source);
        assert_ne!(message_one.payload, message_two.payload);
    }

    #[test]
    fn test_build_retains_all_publish_attributes() {
        let message_id = UUID::build();
        let topic = UUri::try_from(TOPIC).expect("should have been able to create UUri");
        let message = UMessageBuilder::publish(topic.clone())
            .with_message_id(message_id.clone())
            .with_priority(UPriority::UPRIORITY_CS2)
            .with_ttl(5000)
            .build_with_payload("locked", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)
            .expect("should have been able to create message");
        assert_eq!(message.attributes.id, Some(message_id).into());
        assert_eq!(message.attributes.priority, UPriority::UPRIORITY_CS2.into());
        assert_eq!(message.attributes.source, Some(topic).into());
        assert_eq!(message.attributes.ttl, Some(5000));
        assert_eq!(
            message.attributes.type_,
            UMessageType::UMESSAGE_TYPE_PUBLISH.into()
        );
    }

    #[test]
    fn test_build_retains_all_request_attributes() {
        let message_id = UUID::build();
        let token = String::from("token");
        let method_to_invoke = UUri::try_from(METHOD_TO_INVOKE)
            .expect("should have been able to create destination UUri");
        let reply_to_address = UUri::try_from(REPLY_TO_ADDRESS)
            .expect("should have been able to create reply-to UUri");
        let message =
            UMessageBuilder::request(method_to_invoke.clone(), reply_to_address.clone(), 5000)
                .with_message_id(message_id.clone())
                .with_permission_level(5)
                .with_priority(UPriority::UPRIORITY_CS4)
                .with_token(token.clone())
                .build_with_payload("unlock", UPayloadFormat::UPAYLOAD_FORMAT_TEXT)
                .expect("should have been able to create message");

        assert_eq!(message.attributes.id, Some(message_id).into());
        assert_eq!(message.attributes.permission_level, Some(5));
        assert_eq!(message.attributes.priority, UPriority::UPRIORITY_CS4.into());
        assert_eq!(message.attributes.sink, Some(method_to_invoke).into());
        assert_eq!(message.attributes.source, Some(reply_to_address).into());
        assert_eq!(message.attributes.token, Some(token));
        assert_eq!(message.attributes.ttl, Some(5000));
        assert_eq!(
            message.attributes.type_,
            UMessageType::UMESSAGE_TYPE_REQUEST.into()
        );
    }

    #[test]
    fn test_builder_copies_request_attributes() {
        let request_message_id = UUID::build();
        let response_message_id = UUID::build();
        let method_to_invoke = UUri::try_from(METHOD_TO_INVOKE)
            .expect("should have been able to create destination UUri");
        let reply_to_address = UUri::try_from(REPLY_TO_ADDRESS)
            .expect("should have been able to create reply-to UUri");
        let request_message =
            UMessageBuilder::request(method_to_invoke.clone(), reply_to_address.clone(), 5000)
                .with_message_id(request_message_id.clone())
                .with_priority(UPriority::UPRIORITY_CS5)
                .build()
                .expect("should have been able to create message");
        let message = UMessageBuilder::response_for_request(&request_message.attributes)
            .with_message_id(response_message_id.clone())
            .with_comm_status(UCode::DEADLINE_EXCEEDED)
            .with_ttl(4000)
            .build()
            .expect("should have been able to create message");
        assert_eq!(message.attributes.id, Some(response_message_id).into());
        assert_eq!(
            message.attributes.commstatus,
            Some(EnumOrUnknown::from(UCode::DEADLINE_EXCEEDED))
        );
        assert_eq!(message.attributes.priority, UPriority::UPRIORITY_CS5.into());
        assert_eq!(message.attributes.reqid, Some(request_message_id).into());
        assert_eq!(message.attributes.sink, Some(reply_to_address).into());
        assert_eq!(message.attributes.source, Some(method_to_invoke).into());
        assert_eq!(message.attributes.ttl, Some(4000));
        assert_eq!(
            message.attributes.type_,
            UMessageType::UMESSAGE_TYPE_RESPONSE.into()
        );
    }

    #[test]
    fn test_build_retains_all_response_attributes() {
        let message_id = UUID::build();
        let request_id = UUID::build();
        let method_to_invoke = UUri::try_from(METHOD_TO_INVOKE)
            .expect("should have been able to create destination UUri");
        let reply_to_address = UUri::try_from(REPLY_TO_ADDRESS)
            .expect("should have been able to create reply-to UUri");
        let message = UMessageBuilder::response(
            reply_to_address.clone(),
            request_id.clone(),
            method_to_invoke.clone(),
        )
        .with_message_id(message_id.clone())
        .with_comm_status(UCode::DEADLINE_EXCEEDED)
        .with_priority(UPriority::UPRIORITY_CS5)
        .with_ttl(0)
        .build()
        .expect("should have been able to create message");
        assert_eq!(message.attributes.id, Some(message_id).into());
        assert_eq!(
            message.attributes.commstatus,
            Some(EnumOrUnknown::from(UCode::DEADLINE_EXCEEDED))
        );
        assert_eq!(message.attributes.priority, UPriority::UPRIORITY_CS5.into());
        assert_eq!(message.attributes.reqid, Some(request_id).into());
        assert_eq!(message.attributes.sink, Some(reply_to_address).into());
        assert_eq!(message.attributes.source, Some(method_to_invoke).into());
        assert_eq!(message.attributes.ttl, Some(0));
        assert_eq!(
            message.attributes.type_,
            UMessageType::UMESSAGE_TYPE_RESPONSE.into()
        );
    }
}