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
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
/********************************************************************************
 * Copyright (c) 2023 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 std::time::SystemTime;

use protobuf::Enum;

use crate::{UAttributes, UMessageType, UPriority, UUri, UUID};

use crate::UAttributesError;

/// `UAttributes` is the struct that defines the Payload. It serves as the configuration for various aspects
/// like time to live, priority, security tokens, and more. Each variant of `UAttributes` defines a different
/// type of message payload. The payload could represent a simple published payload with some state change,
/// an RPC request payload, or an RPC response payload.
///
/// `UAttributesValidator` is a trait implemented by all validators for `UAttributes`. It provides functionality
/// to help validate that a given `UAttributes` instance is correctly configured to define the Payload.
pub trait UAttributesValidator: Send {
    /// Checks if a given set of attributes complies with the rules specified for
    /// the type of message they describe.
    ///
    /// # Errors
    ///
    /// Returns an error if the attributes are not consistent with the rules specified for the message type.
    fn validate(&self, attributes: &UAttributes) -> Result<(), UAttributesError>;

    /// Verifies that this validator is appropriate for a set of attributes.
    ///
    /// # Errors
    ///
    /// Returns an error if [`UAttributes::type_`] does not match the type returned by [`UAttributesValidator::message_type`].
    fn validate_type(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        let expected_type = self.message_type();
        match attributes.type_.enum_value() {
            Ok(mt) if mt == expected_type => Ok(()),
            Ok(mt) => Err(UAttributesError::validation_error(format!(
                "Wrong Message Type [{}]",
                mt.to_cloudevent_type()
            ))),
            Err(unknown_code) => Err(UAttributesError::validation_error(format!(
                "Unknown Message Type code [{}]",
                unknown_code
            ))),
        }
    }

    /// Verifies that a set of attributes contains a valid message ID.
    ///
    /// # Errors
    ///
    /// Returns an error if [`UAttributes::id`] does not contain a [valid uProtocol UUID](`UUID::is_uprotocol_uuid`).
    fn validate_id(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if attributes
            .id
            .as_ref()
            .map_or(false, |id| id.is_uprotocol_uuid())
        {
            Ok(())
        } else {
            Err(UAttributesError::validation_error(
                "Attributes must contain valid uProtocol UUID in id property",
            ))
        }
    }

    /// Returns the type of message that this validator can be used with.
    fn message_type(&self) -> UMessageType;

    /// Checks if the message that is described by these attributes should be considered expired.
    ///
    /// # Errors
    ///
    /// Returns an error if [`UAttributes::ttl`] (time-to-live) contains a value greater than 0, but
    /// * the message has expired according to the timestamp extracted from [`UAttributes::id`] and the time-to-live value, or
    /// * the current system time cannot be determined.
    fn is_expired(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        let ttl = match attributes.ttl {
            Some(t) if t > 0 => u64::from(t),
            _ => return Ok(()),
        };

        if let Some(time) = attributes.id.as_ref().and_then(UUID::get_time) {
            let delta = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
                Ok(duration) => {
                    if let Ok(duration) = u64::try_from(duration.as_millis()) {
                        duration - time
                    } else {
                        return Err(UAttributesError::validation_error("Invalid duration"));
                    }
                }
                Err(e) => return Err(UAttributesError::validation_error(e.to_string())),
            };
            if delta >= ttl {
                return Err(UAttributesError::validation_error("Payload is expired"));
            }
        }
        Ok(())
    }

    /// Verifies that a set of attributes contains a valid source URI.
    ///
    /// # Errors
    ///
    /// If the [`UAttributes::source`] property does not contain a valid URI as required by the type of message, an error is returned.
    fn validate_source(&self, attributes: &UAttributes) -> Result<(), UAttributesError>;

    /// Verifies that a set of attributes contains a valid sink URI.
    fn validate_sink(&self, attributes: &UAttributes) -> Result<(), UAttributesError>;
}

/// Verifies that a set of attributes contains a priority that is appropriate for an RPC request message.
///
/// # Errors
///
/// If [`UAttributes::priority`] contains a value that is less [`UPriority::UPRIORITY_CS4`].
pub fn validate_rpc_priority(attributes: &UAttributes) -> Result<(), UAttributesError> {
    attributes
        .priority
        .enum_value()
        .map_err(|unknown_code| {
            UAttributesError::ValidationError(format!(
                "RPC message must have a valid priority [{}]",
                unknown_code
            ))
        })
        .and_then(|prio| {
            if prio.value() < UPriority::UPRIORITY_CS4.value() {
                Err(UAttributesError::ValidationError(
                    "RPC message must have a priority of at least CS4".to_string(),
                ))
            } else {
                Ok(())
            }
        })
}

/// Enum that hold the implementations of uattributesValidator according to type.
pub enum UAttributesValidators {
    Publish,
    Notification,
    Request,
    Response,
}

impl UAttributesValidators {
    /// Gets the validator corresponding to this enum value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UAttributes, UAttributesValidators, UMessageBuilder, UMessageType, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let topic = UUri::try_from("//my-vehicle/D45/23/A001")?;
    /// let attributes = UAttributes {
    ///    type_: UMessageType::UMESSAGE_TYPE_PUBLISH.into(),
    ///    id: Some(UUID::build()).into(),
    ///    source: Some(topic).into(),
    ///    ..Default::default()
    /// };
    /// let validator = UAttributesValidators::Publish.validator();
    /// assert!(validator.validate(&attributes).is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn validator(&self) -> Box<dyn UAttributesValidator> {
        match self {
            UAttributesValidators::Publish => Box::new(PublishValidator),
            UAttributesValidators::Notification => Box::new(NotificationValidator),
            UAttributesValidators::Request => Box::new(RequestValidator),
            UAttributesValidators::Response => Box::new(ResponseValidator),
        }
    }

    /// Gets a validator that can be used to check a given set of attributes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UAttributes, UAttributesValidators, UMessageBuilder, UMessageType, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let topic = UUri::try_from("//my-vehicle/D45/23/A001")?;
    /// let attributes = UAttributes {
    ///    type_: UMessageType::UMESSAGE_TYPE_PUBLISH.into(),
    ///    id: Some(UUID::build()).into(),
    ///    source: Some(topic).into(),
    ///    ..Default::default()
    /// };
    /// let validator = UAttributesValidators::get_validator_for_attributes(&attributes);
    /// assert!(validator.validate(&attributes).is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_validator_for_attributes(attributes: &UAttributes) -> Box<dyn UAttributesValidator> {
        Self::get_validator(attributes.type_.enum_value_or_default())
    }

    /// Gets a validator that can be used to check attributes of a given type of message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use up_rust::{UAttributes, UAttributesValidators, UMessageBuilder, UMessageType, UUID, UUri};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let topic = UUri::try_from("//my-vehicle/D45/23/A001")?;
    /// let attributes = UAttributes {
    ///    type_: UMessageType::UMESSAGE_TYPE_PUBLISH.into(),
    ///    id: Some(UUID::build()).into(),
    ///    source: Some(topic).into(),
    ///    ..Default::default()
    /// };
    /// let validator = UAttributesValidators::get_validator(UMessageType::UMESSAGE_TYPE_PUBLISH);
    /// assert!(validator.validate(&attributes).is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_validator(message_type: UMessageType) -> Box<dyn UAttributesValidator> {
        match message_type {
            UMessageType::UMESSAGE_TYPE_REQUEST => Box::new(RequestValidator),
            UMessageType::UMESSAGE_TYPE_RESPONSE => Box::new(ResponseValidator),
            UMessageType::UMESSAGE_TYPE_NOTIFICATION => Box::new(NotificationValidator),
            _ => Box::new(PublishValidator),
        }
    }
}

/// Validates attributes describing a Publish message.
pub struct PublishValidator;

impl UAttributesValidator for PublishValidator {
    fn message_type(&self) -> UMessageType {
        UMessageType::UMESSAGE_TYPE_PUBLISH
    }

    /// Checks if a given set of attributes complies with the rules specified for
    /// publish messages.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the following checks fail for the given attributes:
    ///
    /// * [`UAttributesValidator::validate_type`]
    /// * [`UAttributesValidator::validate_id`]
    /// * [`UAttributesValidator::validate_source`]
    /// * [`UAttributesValidator::validate_sink`]
    fn validate(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        let error_message = vec![
            self.validate_type(attributes),
            self.validate_id(attributes),
            self.validate_source(attributes),
            self.validate_sink(attributes),
        ]
        .into_iter()
        .filter_map(Result::err)
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("; ");

        if error_message.is_empty() {
            Ok(())
        } else {
            Err(UAttributesError::validation_error(error_message))
        }
    }

    /// Verifies that attributes for a publish message contain a valid source URI.
    ///
    /// # Errors
    ///
    /// Returns an error
    ///
    /// * if the attributes do not contain a source URI, or
    /// * if the source URI contains any wildcards, or
    /// * if the source URI has a resource ID of 0.
    fn validate_source(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if let Some(source) = attributes.source.as_ref() {
            source.verify_event().map_err(|e| {
                UAttributesError::validation_error(format!("Invalid source URI: {}", e))
            })
        } else {
            Err(UAttributesError::validation_error(
                "Attributes for a publish message must contain a source URI",
            ))
        }
    }

    /// Verifies that attributes for a publish message do not contain a sink URI.
    ///
    /// # Errors
    ///
    /// If the [`UAttributes::sink`] property contains any URI, an error is returned.
    fn validate_sink(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if attributes.sink.as_ref().is_some() {
            Err(UAttributesError::validation_error(
                "Attributes for a publish message must not contain a sink URI",
            ))
        } else {
            Ok(())
        }
    }
}

/// Validates attributes describing a Notification message.
pub struct NotificationValidator;

impl UAttributesValidator for NotificationValidator {
    fn message_type(&self) -> UMessageType {
        UMessageType::UMESSAGE_TYPE_NOTIFICATION
    }

    /// Checks if a given set of attributes complies with the rules specified for
    /// notification messages.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the following checks fail for the given attributes:
    ///
    /// * [`UAttributesValidator::validate_type`]
    /// * [`UAttributesValidator::validate_id`]
    /// * [`UAttributesValidator::validate_source`]
    /// * [`UAttributesValidator::validate_sink`]
    fn validate(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        let error_message = vec![
            self.validate_type(attributes),
            self.validate_id(attributes),
            self.validate_source(attributes),
            self.validate_sink(attributes),
        ]
        .into_iter()
        .filter_map(Result::err)
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("; ");

        if error_message.is_empty() {
            Ok(())
        } else {
            Err(UAttributesError::validation_error(error_message))
        }
    }

    /// Verifies that attributes for a notification message contain a source URI.
    ///
    /// # Errors
    ///
    /// Returns an error
    ///
    /// * if the attributes do not contain a source URI, or
    /// * if the source URI is an RPC response URI, or
    /// * if the source URI contains any wildcards.
    fn validate_source(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if let Some(source) = attributes.source.as_ref() {
            if source.is_rpc_response() {
                Err(UAttributesError::validation_error(
                    "Origin must not be an RPC response URI",
                ))
            } else {
                source.verify_no_wildcards().map_err(|e| {
                    UAttributesError::validation_error(format!("Invalid source URI: {}", e))
                })
            }
        } else {
            Err(UAttributesError::validation_error(
                "Attributes must contain a source URI",
            ))
        }
    }

    /// Verifies that attributes for a notification message contain a sink URI.
    ///
    /// # Errors
    ///
    /// Returns an error
    ///
    /// * if the attributes do not contain a sink URI, or
    /// * if the sink URI's resource ID is != 0, or
    /// * if the sink URI contains any wildcards.
    fn validate_sink(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if let Some(sink) = attributes.sink.as_ref() {
            if !sink.is_notification_destination() {
                Err(UAttributesError::validation_error(
                    "Destination's resource ID must be 0",
                ))
            } else {
                sink.verify_no_wildcards().map_err(|e| {
                    UAttributesError::validation_error(format!("Invalid sink URI: {}", e))
                })
            }
        } else {
            Err(UAttributesError::validation_error(
                "Attributes for a notification message must contain a sink URI",
            ))
        }
    }
}

/// Validate `UAttributes` with type `UMessageType::Request`
pub struct RequestValidator;

impl RequestValidator {
    /// Verifies that a set of attributes representing an RPC request contain a valid time-to-live.
    ///
    /// # Errors
    ///
    /// Returns an error if [`UAttributes::ttl`] (time-to-live) is empty or contains a value less than 1.
    pub fn validate_ttl(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        match attributes.ttl {
            Some(ttl) if ttl > 0 => Ok(()),
            Some(invalid_ttl) => Err(UAttributesError::validation_error(format!(
                "RPC request message's TTL must be a positive integer [{invalid_ttl}]"
            ))),
            None => Err(UAttributesError::validation_error(
                "RPC request message must contain a TTL",
            )),
        }
    }
}

impl UAttributesValidator for RequestValidator {
    fn message_type(&self) -> UMessageType {
        UMessageType::UMESSAGE_TYPE_REQUEST
    }

    /// Checks if a given set of attributes complies with the rules specified for
    /// RPC request messages.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the following checks fail for the given attributes:
    ///
    /// * [`UAttributesValidator::validate_type`]
    /// * [`UAttributesValidator::validate_id`]
    /// * [`RequestValidator::validate_ttl`]
    /// * [`UAttributesValidator::validate_source`]
    /// * [`UAttributesValidator::validate_sink`]
    /// * `validate_rpc_priority`
    fn validate(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        let error_message = vec![
            self.validate_type(attributes),
            self.validate_id(attributes),
            self.validate_ttl(attributes),
            self.validate_source(attributes),
            self.validate_sink(attributes),
            validate_rpc_priority(attributes),
        ]
        .into_iter()
        .filter_map(Result::err)
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("; ");

        if error_message.is_empty() {
            Ok(())
        } else {
            Err(UAttributesError::validation_error(error_message))
        }
    }

    /// Verifies that attributes for a message representing an RPC request contain a reply-to-address.
    ///
    /// # Errors
    ///
    /// Returns an error if the [`UAttributes::source`] property does not contain a valid reply-to-address according to
    /// [`UUri::verify_rpc_response`].
    fn validate_source(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if let Some(source) = attributes.source.as_ref() {
            UUri::verify_rpc_response(source).map_err(|e| {
                UAttributesError::validation_error(format!("Invalid source URI: {}", e))
            })
        } else {
            Err(UAttributesError::validation_error("Attributes for a request message must contain a reply-to address in the source property"))
        }
    }

    /// Verifies that attributes for a message representing an RPC request indicate the method to invoke.
    ///
    /// # Errors
    ///
    /// Returns an erro if the [`UAttributes::sink`] property does not contain a URI representing a method according to
    /// [`UUri::verify_rpc_method`].
    fn validate_sink(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if let Some(sink) = attributes.sink.as_ref() {
            UUri::verify_rpc_method(sink)
                .map_err(|e| UAttributesError::validation_error(format!("Invalid sink URI: {}", e)))
        } else {
            Err(UAttributesError::validation_error("Attributes for a request message must contain a method-to-invoke in the sink property"))
        }
    }
}

/// Validate `UAttributes` with type `UMessageType::Response`
pub struct ResponseValidator;

impl ResponseValidator {
    /// Verifies that the attributes contain a valid request ID.
    ///
    /// # Errors
    ///
    /// Returns an error if [`UAttributes::reqid`] is empty or contains a value which is not
    /// a [valid uProtocol UUID](`UUID::is_uprotocol_uuid`).
    pub fn validate_reqid(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if !attributes
            .reqid
            .as_ref()
            .map_or(false, |id| id.is_uprotocol_uuid())
        {
            Err(UAttributesError::validation_error(
                "Request ID is not a valid uProtocol UUID",
            ))
        } else {
            Ok(())
        }
    }

    /// Verifies that a set of attributes contains a valid communication status.
    ///
    /// # Errors
    ///
    /// Returns an error if [`UAttributes::commstatus`] does not contain a value that is a `UCode`.
    pub fn validate_commstatus(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if let Some(status) = attributes.commstatus {
            match status.enum_value() {
                Ok(_) => {
                    return Ok(());
                }
                Err(e) => {
                    return Err(UAttributesError::validation_error(format!(
                        "Invalid Communication Status code: {e}"
                    )));
                }
            }
        }
        Ok(())
    }
}

impl UAttributesValidator for ResponseValidator {
    fn message_type(&self) -> UMessageType {
        UMessageType::UMESSAGE_TYPE_RESPONSE
    }

    /// Checks if a given set of attributes complies with the rules specified for
    /// RPC response messages.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the following checks fail for the given attributes:
    ///
    /// * [`UAttributesValidator::validate_type`]
    /// * [`UAttributesValidator::validate_id`]
    /// * [`UAttributesValidator::validate_source`]
    /// * [`UAttributesValidator::validate_sink`]
    /// * [`ResponseValidator::validate_reqid`]
    /// * [`ResponseValidator::validate_commstatus`]
    /// * `validate_rpc_priority`
    fn validate(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        let error_message = vec![
            self.validate_type(attributes),
            self.validate_id(attributes),
            self.validate_source(attributes),
            self.validate_sink(attributes),
            self.validate_reqid(attributes),
            self.validate_commstatus(attributes),
            validate_rpc_priority(attributes),
        ]
        .into_iter()
        .filter_map(Result::err)
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("; ");

        if error_message.is_empty() {
            Ok(())
        } else {
            Err(UAttributesError::validation_error(error_message))
        }
    }

    /// Verifies that attributes for a message representing an RPC response indicate the method that has
    /// been invoked.
    ///  
    /// # Errors
    ///
    /// Returns an error if the [`UAttributes::source`] property does not contain a URI representing a method according to
    /// [`UUri::verify_rpc_method`].
    fn validate_source(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if let Some(source) = attributes.source.as_ref() {
            UUri::verify_rpc_method(source).map_err(|e| {
                UAttributesError::validation_error(format!("Invalid source URI: {}", e))
            })
        } else {
            Err(UAttributesError::validation_error("Missing Source"))
        }
    }

    /// Verifies that attributes for a message representing an RPC response contain a valid
    /// reply-to-address.
    ///
    /// # Errors
    ///
    /// Returns an error if the [`UAttributes::sink`] property does not contain a valid reply-to-address according to
    /// [`UUri::verify_rpc_response`].
    fn validate_sink(&self, attributes: &UAttributes) -> Result<(), UAttributesError> {
        if let Some(sink) = &attributes.sink.as_ref() {
            UUri::verify_rpc_response(sink)
                .map_err(|e| UAttributesError::validation_error(format!("Invalid sink URI: {}", e)))
        } else {
            Err(UAttributesError::validation_error("Missing Sink"))
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        ops::Sub,
        time::{Duration, UNIX_EPOCH},
    };

    use protobuf::EnumOrUnknown;
    use test_case::test_case;

    use super::*;
    use crate::{UCode, UPriority, UUri, UUID};

    /// Creates a UUID n ms in the past.
    ///
    /// # Note
    ///
    /// For internal testing purposes only. For end-users, please use [`UUID::build()`]
    fn build_n_ms_in_past(n_ms_in_past: u64) -> UUID {
        let duration_since_unix_epoch = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("current system time is set to a point in time before UNIX Epoch");
        UUID::build_for_timestamp(
            duration_since_unix_epoch.sub(Duration::from_millis(n_ms_in_past)),
        )
    }

    #[test]
    fn test_validate_type_fails_for_unknown_type_code() {
        let attributes = UAttributes {
            type_: EnumOrUnknown::from_i32(20),
            ..Default::default()
        };
        assert!(UAttributesValidators::Publish
            .validator()
            .validate_type(&attributes)
            .is_err());
        assert!(UAttributesValidators::Notification
            .validator()
            .validate_type(&attributes)
            .is_err());
        assert!(UAttributesValidators::Request
            .validator()
            .validate_type(&attributes)
            .is_err());
        assert!(UAttributesValidators::Response
            .validator()
            .validate_type(&attributes)
            .is_err());
    }

    #[test_case(UMessageType::UMESSAGE_TYPE_UNSPECIFIED, UMessageType::UMESSAGE_TYPE_PUBLISH; "succeeds for Unspecified message")]
    #[test_case(UMessageType::UMESSAGE_TYPE_PUBLISH, UMessageType::UMESSAGE_TYPE_PUBLISH; "succeeds for Publish message")]
    #[test_case(UMessageType::UMESSAGE_TYPE_NOTIFICATION, UMessageType::UMESSAGE_TYPE_NOTIFICATION; "succeeds for Notification message")]
    #[test_case(UMessageType::UMESSAGE_TYPE_REQUEST, UMessageType::UMESSAGE_TYPE_REQUEST; "succeeds for Request message")]
    #[test_case(UMessageType::UMESSAGE_TYPE_RESPONSE, UMessageType::UMESSAGE_TYPE_RESPONSE; "succeeds for Response message")]
    fn test_get_validator_returns_matching_validator(
        message_type: UMessageType,
        expected_validator_type: UMessageType,
    ) {
        let validator: Box<dyn UAttributesValidator> =
            UAttributesValidators::get_validator(message_type);
        assert_eq!(validator.message_type(), expected_validator_type);
    }

    #[test_case(UMessageType::UMESSAGE_TYPE_PUBLISH, None, None, false; "for Publish message without ID nor TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_PUBLISH, None, Some(0), false; "for Publish message without ID with TTL 0")]
    #[test_case(UMessageType::UMESSAGE_TYPE_PUBLISH, None, Some(500), false; "for Publish message without ID with TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_PUBLISH, Some(build_n_ms_in_past(1000)), None, false; "for Publish message with ID without TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_PUBLISH, Some(build_n_ms_in_past(1000)), Some(0), false; "for Publish message with ID and TTL 0")]
    #[test_case(UMessageType::UMESSAGE_TYPE_PUBLISH, Some(build_n_ms_in_past(1000)), Some(500), true; "for Publish message with ID and expired TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_PUBLISH, Some(build_n_ms_in_past(1000)), Some(2000), false; "for Publish message with ID and non-expired TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_NOTIFICATION, None, None, false; "for Notification message without ID nor TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_NOTIFICATION, None, Some(0), false; "for Notification message without ID with TTL 0")]
    #[test_case(UMessageType::UMESSAGE_TYPE_NOTIFICATION, None, Some(500), false; "for Notification message without ID with TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_NOTIFICATION, Some(build_n_ms_in_past(1000)), None, false; "for Notification message with ID without TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_NOTIFICATION, Some(build_n_ms_in_past(1000)), Some(0), false; "for Notification message with ID and TTL 0")]
    #[test_case(UMessageType::UMESSAGE_TYPE_NOTIFICATION, Some(build_n_ms_in_past(1000)), Some(500), true; "for Notification message with ID and expired TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_NOTIFICATION, Some(build_n_ms_in_past(1000)), Some(2000), false; "for Notification message with ID and non-expired TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_REQUEST, None, None, false; "for Request message without ID nor TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_REQUEST, None, Some(0), false; "for Request message without ID with TTL 0")]
    #[test_case(UMessageType::UMESSAGE_TYPE_REQUEST, None, Some(500), false; "for Request message without ID with TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_REQUEST, Some(build_n_ms_in_past(1000)), None, false; "for Request message with ID without TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_REQUEST, Some(build_n_ms_in_past(1000)), Some(0), false; "for Request message with ID and TTL 0")]
    #[test_case(UMessageType::UMESSAGE_TYPE_REQUEST, Some(build_n_ms_in_past(1000)), Some(500), true; "for Request message with ID and expired TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_REQUEST, Some(build_n_ms_in_past(1000)), Some(2000), false; "for Request message with ID and non-expired TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_RESPONSE, None, None, false; "for Response message without ID nor TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_RESPONSE, None, Some(0), false; "for Response message without ID with TTL 0")]
    #[test_case(UMessageType::UMESSAGE_TYPE_RESPONSE, None, Some(500), false; "for Response message without ID with TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_RESPONSE, Some(build_n_ms_in_past(1000)), None, false; "for Response message with ID without TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_RESPONSE, Some(build_n_ms_in_past(1000)), Some(0), false; "for Response message with ID and TTL 0")]
    #[test_case(UMessageType::UMESSAGE_TYPE_RESPONSE, Some(build_n_ms_in_past(1000)), Some(500), true; "for Response message with ID and expired TTL")]
    #[test_case(UMessageType::UMESSAGE_TYPE_RESPONSE, Some(build_n_ms_in_past(1000)), Some(2000), false; "for Response message with ID and non-expired TTL")]
    fn test_is_expired(
        message_type: UMessageType,
        id: Option<UUID>,
        ttl: Option<u32>,
        should_be_expired: bool,
    ) {
        let attributes = UAttributes {
            type_: message_type.into(),
            priority: UPriority::UPRIORITY_CS1.into(),
            id: id.into(),
            ttl,
            ..Default::default()
        };

        let validator = UAttributesValidators::get_validator(message_type);
        assert!(validator.is_expired(&attributes).is_err() == should_be_expired);
    }

    #[test_case(Some(UUID::build()), Some(publish_topic()), None, None, true; "succeeds for topic only")]
    #[test_case(Some(UUID::build()), Some(publish_topic()), Some(destination()), None, false; "fails for message containing destination")]
    #[test_case(Some(UUID::build()), Some(publish_topic()), None, Some(100), true; "succeeds for valid attributes")]
    #[test_case(Some(UUID::build()), None, None, None, false; "fails for missing topic")]
    #[test_case(Some(UUID::build()), Some(UUri { resource_id: 0x54, ..Default::default()}), None, None, false; "fails for invalid topic")]
    #[test_case(None, Some(publish_topic()), None, None, false; "fails for missing message ID")]
    #[test_case(
        Some(UUID {
            // invalid UUID version (not 0b1000 but 0b1010)
            msb: 0x000000000001C000u64,
            lsb: 0x8000000000000000u64,
            ..Default::default()
        }),
        Some(publish_topic()),
        None,
        None,
        false;
        "fails for invalid message id")]
    fn test_validate_attributes_for_publish_message(
        id: Option<UUID>,
        source: Option<UUri>,
        sink: Option<UUri>,
        ttl: Option<u32>,
        expected_result: bool,
    ) {
        let attributes = UAttributes {
            type_: UMessageType::UMESSAGE_TYPE_PUBLISH.into(),
            id: id.into(),
            priority: UPriority::UPRIORITY_CS1.into(),
            source: source.into(),
            sink: sink.into(),
            ttl,
            ..Default::default()
        };
        let validator = UAttributesValidators::Publish.validator();
        let status = validator.validate(&attributes);
        assert!(status.is_ok() == expected_result);
        if status.is_ok() {
            assert!(UAttributesValidators::Notification
                .validator()
                .validate(&attributes)
                .is_err());
            assert!(UAttributesValidators::Request
                .validator()
                .validate(&attributes)
                .is_err());
            assert!(UAttributesValidators::Response
                .validator()
                .validate(&attributes)
                .is_err());
        }
    }

    #[test_case(Some(UUID::build()), Some(origin()), None, None, false; "fails for missing destination")]
    #[test_case(Some(UUID::build()), Some(origin()), Some(destination()), None, true; "succeeds for both origin and destination")]
    #[test_case(Some(UUID::build()), Some(origin()), Some(destination()), Some(100), true; "succeeds for valid attributes")]
    #[test_case(Some(UUID::build()), None, Some(destination()), None, false; "fails for missing origin")]
    #[test_case(Some(UUID::build()), Some(UUri::default()), Some(destination()), None, false; "fails for invalid origin")]
    #[test_case(Some(UUID::build()), Some(origin()), Some(UUri { ue_id: 0xabcd, ue_version_major: 0x01, resource_id: 0x0011, ..Default::default() }), None, false; "fails for invalid destination")]
    #[test_case(Some(UUID::build()), None, None, None, false; "fails for neither origin nor destination")]
    #[test_case(None, Some(origin()), Some(destination()), None, false; "fails for missing message ID")]
    #[test_case(
        Some(UUID {
            // invalid UUID version (not 0b1000 but 0b1010)
            msb: 0x000000000001C000u64,
            lsb: 0x8000000000000000u64,
            ..Default::default()
        }),
        Some(origin()),
        Some(destination()),
        None,
        false;
        "fails for invalid message id")]
    fn test_validate_attributes_for_notification_message(
        id: Option<UUID>,
        source: Option<UUri>,
        sink: Option<UUri>,
        ttl: Option<u32>,
        expected_result: bool,
    ) {
        let attributes = UAttributes {
            type_: UMessageType::UMESSAGE_TYPE_NOTIFICATION.into(),
            id: id.into(),
            priority: UPriority::UPRIORITY_CS1.into(),
            source: source.into(),
            sink: sink.into(),
            ttl,
            ..Default::default()
        };
        let validator = UAttributesValidators::Notification.validator();
        let status = validator.validate(&attributes);
        assert!(status.is_ok() == expected_result);
        if status.is_ok() {
            assert!(UAttributesValidators::Publish
                .validator()
                .validate(&attributes)
                .is_err());
            assert!(UAttributesValidators::Request
                .validator()
                .validate(&attributes)
                .is_err());
            assert!(UAttributesValidators::Response
                .validator()
                .validate(&attributes)
                .is_err());
        }
    }

    #[test_case(Some(UUID::build()), Some(method_to_invoke()), Some(reply_to_address()), None, Some(2000), Some(UPriority::UPRIORITY_CS4), None, true; "succeeds for mandatory attributes")]
    #[test_case(Some(UUID::build()), Some(method_to_invoke()), Some(reply_to_address()), Some(1), Some(2000), Some(UPriority::UPRIORITY_CS4), Some(String::from("token")), true; "succeeds for valid attributes")]
    #[test_case(None, Some(method_to_invoke()), Some(reply_to_address()), Some(1), Some(2000), Some(UPriority::UPRIORITY_CS4), Some(String::from("token")), false; "fails for missing message ID")]
    #[test_case(
        Some(UUID {
            // invalid UUID version (not 0b1000 but 0b1010)
            msb: 0x000000000001C000u64,
            lsb: 0x8000000000000000u64,
            ..Default::default()
        }),
        Some(method_to_invoke()),
        Some(reply_to_address()),
        None,
        Some(2000),
        Some(UPriority::UPRIORITY_CS4),
        None,
        false;
        "fails for invalid message id")]
    #[test_case(Some(UUID::build()), Some(method_to_invoke()), None, None, Some(2000), Some(UPriority::UPRIORITY_CS4), None, false; "fails for missing reply-to-address")]
    #[test_case(Some(UUID::build()), Some(method_to_invoke()), Some(UUri { resource_id: 0x0001, ..Default::default()}), None, Some(2000), Some(UPriority::UPRIORITY_CS4), None, false; "fails for invalid reply-to-address")]
    #[test_case(Some(UUID::build()), None, Some(reply_to_address()), None, Some(2000), Some(UPriority::UPRIORITY_CS4), None, false; "fails for missing method-to-invoke")]
    #[test_case(Some(UUID::build()), Some(UUri::default()), Some(reply_to_address()), None, Some(2000), Some(UPriority::UPRIORITY_CS4), None, false; "fails for invalid method-to-invoke")]
    #[test_case(Some(UUID::build()), Some(method_to_invoke()), Some(reply_to_address()), Some(1), Some(2000), None, None, false; "fails for missing priority")]
    #[test_case(Some(UUID::build()), Some(method_to_invoke()), Some(reply_to_address()), Some(1), Some(2000), Some(UPriority::UPRIORITY_CS3), None, false; "fails for invalid priority")]
    #[test_case(Some(UUID::build()), Some(method_to_invoke()), Some(reply_to_address()), None, None, Some(UPriority::UPRIORITY_CS4), None, false; "fails for missing ttl")]
    #[test_case(Some(UUID::build()), Some(method_to_invoke()), Some(reply_to_address()), None, Some(0), Some(UPriority::UPRIORITY_CS4), None, false; "fails for ttl < 1")]
    #[test_case(Some(UUID::build()), Some(method_to_invoke()), Some(reply_to_address()), Some(1), Some(2000), Some(UPriority::UPRIORITY_CS4), None, true; "succeeds for valid permission level")]
    #[allow(clippy::too_many_arguments)]
    fn test_validate_attributes_for_rpc_request_message(
        id: Option<UUID>,
        method_to_invoke: Option<UUri>,
        reply_to_address: Option<UUri>,
        perm_level: Option<u32>,
        ttl: Option<u32>,
        priority: Option<UPriority>,
        token: Option<String>,
        expected_result: bool,
    ) {
        let attributes = UAttributes {
            type_: UMessageType::UMESSAGE_TYPE_REQUEST.into(),
            id: id.into(),
            priority: priority.unwrap_or(UPriority::UPRIORITY_UNSPECIFIED).into(),
            source: reply_to_address.into(),
            sink: method_to_invoke.into(),
            permission_level: perm_level,
            ttl,
            token,
            ..Default::default()
        };
        let status = UAttributesValidators::Request
            .validator()
            .validate(&attributes);
        assert!(status.is_ok() == expected_result);
        if status.is_ok() {
            assert!(UAttributesValidators::Publish
                .validator()
                .validate(&attributes)
                .is_err());
            assert!(UAttributesValidators::Notification
                .validator()
                .validate(&attributes)
                .is_err());
            assert!(UAttributesValidators::Response
                .validator()
                .validate(&attributes)
                .is_err());
        }
    }

    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), None, None, Some(UPriority::UPRIORITY_CS4), true; "succeeds for mandatory attributes")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), Some(EnumOrUnknown::from(UCode::CANCELLED)), Some(100), Some(UPriority::UPRIORITY_CS4), true; "succeeds for valid attributes")]
    #[test_case(None, Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), Some(EnumOrUnknown::from(UCode::CANCELLED)), Some(100), Some(UPriority::UPRIORITY_CS4), false; "fails for missing message ID")]
    #[test_case(
        Some(UUID {
            // invalid UUID version (not 0b1000 but 0b1010)
            msb: 0x000000000001C000u64,
            lsb: 0x8000000000000000u64,
            ..Default::default()
        }),
        Some(reply_to_address()),
        Some(method_to_invoke()),
        Some(UUID::build()),
        None,
        None,
        Some(UPriority::UPRIORITY_CS4),
        false;
        "fails for invalid message id")]
    #[test_case(Some(UUID::build()), None, Some(method_to_invoke()), Some(UUID::build()), None, None, Some(UPriority::UPRIORITY_CS4), false; "fails for missing reply-to-address")]
    #[test_case(Some(UUID::build()), Some(UUri { resource_id: 0x0001, ..Default::default()}), Some(method_to_invoke()), Some(UUID::build()), None, None, Some(UPriority::UPRIORITY_CS4), false; "fails for invalid reply-to-address")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), None, Some(UUID::build()), None, None, Some(UPriority::UPRIORITY_CS4), false; "fails for missing invoked-method")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(UUri::default()), Some(UUID::build()), None, None, Some(UPriority::UPRIORITY_CS4), false; "fails for invalid invoked-method")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), Some(EnumOrUnknown::from(UCode::CANCELLED)), None, Some(UPriority::UPRIORITY_CS4), true; "succeeds for valid commstatus")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), Some(EnumOrUnknown::from_i32(-42)), None, Some(UPriority::UPRIORITY_CS4), false; "fails for invalid commstatus")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), None, Some(100), Some(UPriority::UPRIORITY_CS4), true; "succeeds for ttl > 0)")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), None, Some(0), Some(UPriority::UPRIORITY_CS4), true; "succeeds for ttl = 0")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), Some(EnumOrUnknown::from(UCode::CANCELLED)), Some(100), None, false; "fails for missing priority")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), Some(UUID::build()), Some(EnumOrUnknown::from(UCode::CANCELLED)), Some(100), Some(UPriority::UPRIORITY_CS3), false; "fails for invalid priority")]
    #[test_case(Some(UUID::build()), Some(reply_to_address()), Some(method_to_invoke()), None, None, None, Some(UPriority::UPRIORITY_CS4), false; "fails for missing request id")]
    #[test_case(
        Some(UUID::build()),
        Some(reply_to_address()),
        Some(method_to_invoke()),
        Some(UUID {
            // invalid UUID version (not 0b1000 but 0b1010)
            msb: 0x000000000001C000u64,
            lsb: 0x8000000000000000u64,
            ..Default::default()
        }),
        None,
        None,
        Some(UPriority::UPRIORITY_CS4),
        false;
        "fails for invalid request id")]
    #[allow(clippy::too_many_arguments)]
    fn test_validate_attributes_for_rpc_response_message(
        id: Option<UUID>,
        reply_to_address: Option<UUri>,
        invoked_method: Option<UUri>,
        reqid: Option<UUID>,
        commstatus: Option<EnumOrUnknown<UCode>>,
        ttl: Option<u32>,
        priority: Option<UPriority>,
        expected_result: bool,
    ) {
        let attributes = UAttributes {
            type_: UMessageType::UMESSAGE_TYPE_RESPONSE.into(),
            id: id.into(),
            priority: priority.unwrap_or(UPriority::UPRIORITY_UNSPECIFIED).into(),
            reqid: reqid.into(),
            source: invoked_method.into(),
            sink: reply_to_address.into(),
            commstatus,
            ttl,
            ..Default::default()
        };
        let status = UAttributesValidators::Response
            .validator()
            .validate(&attributes);
        assert!(status.is_ok() == expected_result);
        if status.is_ok() {
            assert!(UAttributesValidators::Publish
                .validator()
                .validate(&attributes)
                .is_err());
            assert!(UAttributesValidators::Notification
                .validator()
                .validate(&attributes)
                .is_err());
            assert!(UAttributesValidators::Request
                .validator()
                .validate(&attributes)
                .is_err());
        }
    }

    fn publish_topic() -> UUri {
        UUri {
            authority_name: String::from("vcu.someVin"),
            ue_id: 0x0000_5410,
            ue_version_major: 0x01,
            resource_id: 0xa010,
            ..Default::default()
        }
    }

    fn origin() -> UUri {
        UUri {
            authority_name: String::from("vcu.someVin"),
            ue_id: 0x0000_3c00,
            ue_version_major: 0x02,
            resource_id: 0x9a00,
            ..Default::default()
        }
    }

    fn destination() -> UUri {
        UUri {
            authority_name: String::from("vcu.someVin"),
            ue_id: 0x0000_3d07,
            ue_version_major: 0x01,
            resource_id: 0x0000,
            ..Default::default()
        }
    }

    fn reply_to_address() -> UUri {
        UUri {
            authority_name: String::from("vcu.someVin"),
            ue_id: 0x0000_010b,
            ue_version_major: 0x01,
            resource_id: 0x0000,
            ..Default::default()
        }
    }

    fn method_to_invoke() -> UUri {
        UUri {
            authority_name: String::from("vcu.someVin"),
            ue_id: 0x0000_03ae,
            ue_version_major: 0x01,
            resource_id: 0x00e2,
            ..Default::default()
        }
    }
}