1use std::fmt;
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer, de, ser::SerializeMap};
6use thiserror::Error;
7
8pub use mobench_runtime::MAX_BENCHMARK_COUNT as MAX_REPORT_COUNT;
9
10pub const REPORT_SCHEMA_V2: &str = "mobench.run/v2";
12
13pub const MAX_REPORT_IDENTIFIER_BYTES: usize = 255;
15
16pub const MAX_REPORT_SAMPLES: usize = MAX_REPORT_COUNT as usize;
18
19pub const MAX_REPORT_FAILURE_MESSAGE_BYTES: usize = 4 * 1024;
21
22#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub struct ReportIdentifier(String);
25
26impl ReportIdentifier {
27 pub fn parse(value: impl Into<String>) -> Result<Self, ReportIdentifierError> {
29 let value = value.into();
30 if value.is_empty() {
31 return Err(ReportIdentifierError::Empty);
32 }
33 if value.len() > MAX_REPORT_IDENTIFIER_BYTES {
34 return Err(ReportIdentifierError::TooLong {
35 length: value.len(),
36 limit: MAX_REPORT_IDENTIFIER_BYTES,
37 });
38 }
39 if value == "." || value == ".." {
40 return Err(ReportIdentifierError::DotComponent);
41 }
42 if value.contains('/') || value.contains('\\') {
43 return Err(ReportIdentifierError::PathSeparator);
44 }
45 if value.chars().any(char::is_control) {
46 return Err(ReportIdentifierError::ControlCharacter);
47 }
48 if value.trim() != value {
49 return Err(ReportIdentifierError::SurroundingWhitespace);
50 }
51
52 Ok(Self(value))
53 }
54
55 pub fn as_str(&self) -> &str {
57 &self.0
58 }
59}
60
61impl fmt::Display for ReportIdentifier {
62 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63 self.0.fmt(formatter)
64 }
65}
66
67impl Serialize for ReportIdentifier {
68 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
69 where
70 S: Serializer,
71 {
72 serializer.serialize_str(&self.0)
73 }
74}
75
76impl<'de> Deserialize<'de> for ReportIdentifier {
77 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
78 where
79 D: Deserializer<'de>,
80 {
81 let value = String::deserialize(deserializer)?;
82 Self::parse(value).map_err(de::Error::custom)
83 }
84}
85
86#[derive(Clone, Debug, Error, PartialEq, Eq)]
88pub enum ReportIdentifierError {
89 #[error("report identifier is empty")]
90 Empty,
91 #[error("report identifier is {length} bytes; maximum is {limit}")]
92 TooLong { length: usize, limit: usize },
93 #[error("report identifier must not be '.' or '..'")]
94 DotComponent,
95 #[error("report identifier must not contain path separators")]
96 PathSeparator,
97 #[error("report identifier must not contain control characters")]
98 ControlCharacter,
99 #[error("report identifier must not have surrounding whitespace")]
100 SurroundingWhitespace,
101}
102
103#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
105#[serde(transparent)]
106pub struct ReportCount(u32);
107
108impl ReportCount {
109 pub fn new(value: u32) -> Result<Self, ReportConstructionError> {
111 if value > MAX_REPORT_COUNT {
112 return Err(ReportConstructionError::CountTooLarge {
113 value,
114 limit: MAX_REPORT_COUNT,
115 });
116 }
117 Ok(Self(value))
118 }
119
120 pub const fn get(self) -> u32 {
122 self.0
123 }
124}
125
126impl<'de> Deserialize<'de> for ReportCount {
127 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
128 where
129 D: Deserializer<'de>,
130 {
131 let value = u32::deserialize(deserializer)?;
132 Self::new(value).map_err(de::Error::custom)
133 }
134}
135
136#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
138pub struct ReportCounts {
139 iterations: ReportCount,
140 warmup: ReportCount,
141}
142
143impl ReportCounts {
144 pub fn new(iterations: u32, warmup: u32) -> Result<Self, ReportConstructionError> {
146 if iterations == 0 {
147 return Err(ReportConstructionError::ZeroIterations);
148 }
149 Ok(Self {
150 iterations: ReportCount::new(iterations)?,
151 warmup: ReportCount::new(warmup)?,
152 })
153 }
154
155 pub fn observed(iterations: u32, warmup: u32) -> Result<Self, ReportConstructionError> {
160 Ok(Self {
161 iterations: ReportCount::new(iterations)?,
162 warmup: ReportCount::new(warmup)?,
163 })
164 }
165
166 pub const fn iterations(self) -> u32 {
168 self.iterations.get()
169 }
170
171 pub const fn warmup(self) -> u32 {
173 self.warmup.get()
174 }
175
176 fn validate_requested(self) -> Result<(), ReportValidationError> {
177 if self.iterations() == 0 {
178 return Err(ReportValidationError::ZeroIterations);
179 }
180 Ok(())
181 }
182}
183
184#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
186pub struct ReportIdentity {
187 run_id: ReportIdentifier,
188 nonce: ReportIdentifier,
189 logical_session_id: ReportIdentifier,
190 function_id: ReportIdentifier,
191 producer: ReportIdentifier,
192}
193
194impl ReportIdentity {
195 pub fn new(
197 run_id: ReportIdentifier,
198 nonce: ReportIdentifier,
199 logical_session_id: ReportIdentifier,
200 function_id: ReportIdentifier,
201 producer: ReportIdentifier,
202 ) -> Self {
203 Self {
204 run_id,
205 nonce,
206 logical_session_id,
207 function_id,
208 producer,
209 }
210 }
211
212 pub fn run_id(&self) -> &ReportIdentifier {
214 &self.run_id
215 }
216
217 pub fn nonce(&self) -> &ReportIdentifier {
219 &self.nonce
220 }
221
222 pub fn logical_session_id(&self) -> &ReportIdentifier {
227 &self.logical_session_id
228 }
229
230 pub fn function_id(&self) -> &ReportIdentifier {
232 &self.function_id
233 }
234
235 pub fn producer(&self) -> &ReportIdentifier {
237 &self.producer
238 }
239}
240
241#[derive(Clone, Debug, PartialEq, Eq)]
247pub enum ReportOutcome {
248 Success,
250 Failure { error: ReportFailure },
252 Unknown { status: String },
254}
255
256impl Serialize for ReportOutcome {
257 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
258 where
259 S: Serializer,
260 {
261 let mut map = serializer.serialize_map(None)?;
262 match self {
263 Self::Success => map.serialize_entry("status", "success")?,
264 Self::Failure { error } => {
265 map.serialize_entry("status", "failure")?;
266 map.serialize_entry("error", error)?;
267 }
268 Self::Unknown { status } => map.serialize_entry("status", status)?,
269 }
270 map.end()
271 }
272}
273
274impl<'de> Deserialize<'de> for ReportOutcome {
275 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
276 where
277 D: Deserializer<'de>,
278 {
279 #[derive(Deserialize)]
280 struct OutcomeWire {
281 status: String,
282 #[serde(default)]
283 error: Option<ReportFailure>,
284 }
285
286 let wire = OutcomeWire::deserialize(deserializer)?;
287 match wire.status.as_str() {
288 "success" => Ok(Self::Success),
289 "failure" => wire
290 .error
291 .map(|error| Self::Failure { error })
292 .ok_or_else(|| de::Error::missing_field("error")),
293 _ => Ok(Self::Unknown {
294 status: wire.status,
295 }),
296 }
297 }
298}
299
300#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
302pub struct ReportFailure {
303 code: ReportIdentifier,
304 message: String,
305}
306
307impl ReportFailure {
308 pub fn new(
310 code: ReportIdentifier,
311 message: impl Into<String>,
312 ) -> Result<Self, ReportConstructionError> {
313 let message = message.into();
314 validate_failure_message(&message).map_err(|error| match error {
315 ReportValidationError::EmptyFailureMessage => {
316 ReportConstructionError::EmptyFailureMessage
317 }
318 ReportValidationError::FailureMessageTooLong { length, limit } => {
319 ReportConstructionError::FailureMessageTooLong { length, limit }
320 }
321 _ => unreachable!("failure message validation returned an unrelated error"),
322 })?;
323 Ok(Self { code, message })
324 }
325
326 pub fn code(&self) -> &ReportIdentifier {
328 &self.code
329 }
330
331 pub fn message(&self) -> &str {
333 &self.message
334 }
335}
336
337#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
339pub struct ReportEnvelopeV2 {
340 schema_version: String,
341 #[serde(flatten)]
342 identity: ReportIdentity,
343 requested: ReportCounts,
344 observed: ReportCounts,
345 samples_ns: BoundedSamples,
346 outcome: ReportOutcome,
347}
348
349#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
355pub struct ProviderReportBinding {
356 provider_id: ReportIdentifier,
357 provider_run_id: ReportIdentifier,
358 transport_session_id: ReportIdentifier,
359 requested_device_id: ReportIdentifier,
360 observed_device_id: ReportIdentifier,
361}
362
363impl ProviderReportBinding {
364 pub fn new(
366 provider_id: ReportIdentifier,
367 provider_run_id: ReportIdentifier,
368 transport_session_id: ReportIdentifier,
369 requested_device_id: ReportIdentifier,
370 observed_device_id: ReportIdentifier,
371 ) -> Self {
372 Self {
373 provider_id,
374 provider_run_id,
375 transport_session_id,
376 requested_device_id,
377 observed_device_id,
378 }
379 }
380
381 pub fn provider_id(&self) -> &ReportIdentifier {
383 &self.provider_id
384 }
385
386 pub fn provider_run_id(&self) -> &ReportIdentifier {
388 &self.provider_run_id
389 }
390
391 pub fn transport_session_id(&self) -> &ReportIdentifier {
393 &self.transport_session_id
394 }
395
396 pub fn requested_device_id(&self) -> &ReportIdentifier {
398 &self.requested_device_id
399 }
400
401 pub fn observed_device_id(&self) -> &ReportIdentifier {
403 &self.observed_device_id
404 }
405}
406
407#[derive(Clone, Debug, PartialEq, Eq)]
409pub struct ExpectedProviderBinding {
410 provider_id: ReportIdentifier,
411 provider_run_id: ReportIdentifier,
412 transport_session_id: ReportIdentifier,
413 requested_device_id: ReportIdentifier,
414 observed_device_id: ReportIdentifier,
415}
416
417impl ExpectedProviderBinding {
418 pub fn new(
420 provider_id: ReportIdentifier,
421 provider_run_id: ReportIdentifier,
422 transport_session_id: ReportIdentifier,
423 requested_device_id: ReportIdentifier,
424 observed_device_id: ReportIdentifier,
425 ) -> Self {
426 Self {
427 provider_id,
428 provider_run_id,
429 transport_session_id,
430 requested_device_id,
431 observed_device_id,
432 }
433 }
434
435 pub fn validate(&self, binding: &ProviderReportBinding) -> Result<(), ReportBindingError> {
437 validate_binding_field("provider_id", &self.provider_id, &binding.provider_id)?;
438 validate_binding_field(
439 "provider_run_id",
440 &self.provider_run_id,
441 &binding.provider_run_id,
442 )?;
443 validate_binding_field(
444 "transport_session_id",
445 &self.transport_session_id,
446 &binding.transport_session_id,
447 )?;
448 validate_binding_field(
449 "requested_device_id",
450 &self.requested_device_id,
451 &binding.requested_device_id,
452 )?;
453 if binding.observed_device_id != self.observed_device_id {
454 return Err(ReportBindingError::ObservedDeviceMismatch {
455 expected: self.observed_device_id.clone(),
456 observed: binding.observed_device_id.clone(),
457 });
458 }
459 Ok(())
460 }
461}
462
463#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
466pub struct BoundRunReportV2 {
467 envelope: ReportEnvelopeV2,
468 binding: ProviderReportBinding,
469}
470
471impl BoundRunReportV2 {
472 pub fn envelope(&self) -> &ReportEnvelopeV2 {
474 &self.envelope
475 }
476
477 pub fn binding(&self) -> &ProviderReportBinding {
479 &self.binding
480 }
481}
482
483impl ReportEnvelopeV2 {
484 pub fn new(
486 identity: ReportIdentity,
487 requested: ReportCounts,
488 observed: ReportCounts,
489 samples_ns: Vec<u64>,
490 outcome: ReportOutcome,
491 ) -> Result<Self, ReportConstructionError> {
492 let samples_ns = BoundedSamples::new(samples_ns)?;
493 let report = Self {
494 schema_version: REPORT_SCHEMA_V2.to_owned(),
495 identity,
496 requested,
497 observed,
498 samples_ns,
499 outcome,
500 };
501 report
502 .validate_structure()
503 .map_err(ReportConstructionError::from_validation)?;
504 Ok(report)
505 }
506
507 pub fn schema_version(&self) -> &str {
509 &self.schema_version
510 }
511
512 pub fn identity(&self) -> &ReportIdentity {
514 &self.identity
515 }
516
517 pub const fn requested(&self) -> ReportCounts {
519 self.requested
520 }
521
522 pub const fn observed(&self) -> ReportCounts {
524 self.observed
525 }
526
527 pub fn samples_ns(&self) -> &[u64] {
529 &self.samples_ns.0
530 }
531
532 pub fn outcome(&self) -> &ReportOutcome {
534 &self.outcome
535 }
536
537 fn validate_structure(&self) -> Result<(), ReportValidationError> {
538 if self.schema_version != REPORT_SCHEMA_V2 {
539 return Err(ReportValidationError::WrongSchema {
540 expected: REPORT_SCHEMA_V2,
541 observed: self.schema_version.clone(),
542 });
543 }
544 self.requested.validate_requested()?;
545 if self.samples_ns.0.len() > MAX_REPORT_SAMPLES {
546 return Err(ReportValidationError::TooManySamples {
547 count: self.samples_ns.0.len(),
548 limit: MAX_REPORT_SAMPLES,
549 });
550 }
551 match &self.outcome {
552 ReportOutcome::Success => {
553 self.observed.validate_requested()?;
554 if self.observed != self.requested {
555 return Err(ReportValidationError::ObservedCountsMismatch {
556 requested: self.requested,
557 observed: self.observed,
558 });
559 }
560 if self.samples_ns.0.is_empty() {
561 return Err(ReportValidationError::EmptySuccessSamples);
562 }
563 if self.samples_ns.0.len() != self.observed.iterations() as usize {
564 return Err(ReportValidationError::SampleCountMismatch {
565 expected: self.observed.iterations(),
566 observed: self.samples_ns.0.len(),
567 });
568 }
569 }
570 ReportOutcome::Failure { error } => {
571 if self.observed.iterations() > self.requested.iterations()
572 || self.observed.warmup() > self.requested.warmup()
573 {
574 return Err(ReportValidationError::ObservedCountsExceedRequested {
575 requested: self.requested,
576 observed: self.observed,
577 });
578 }
579 validate_failure_message(&error.message)?;
580 }
581 ReportOutcome::Unknown { status } => {
582 return Err(ReportValidationError::UnknownOutcome {
583 status: status.clone(),
584 });
585 }
586 }
587 Ok(())
588 }
589}
590
591#[derive(Clone, Debug, PartialEq, Eq)]
593pub struct ExpectedReportIdentity {
594 identity: ReportIdentity,
595 requested: ReportCounts,
596}
597
598impl ExpectedReportIdentity {
599 pub fn new(identity: ReportIdentity, requested: ReportCounts) -> Self {
601 Self {
602 identity,
603 requested,
604 }
605 }
606
607 pub fn validate(&self, report: &ReportEnvelopeV2) -> Result<(), ReportValidationError> {
609 report.validate_structure()?;
610 validate_identity_field("run_id", self.identity.run_id(), report.identity.run_id())?;
611 validate_identity_field("nonce", self.identity.nonce(), report.identity.nonce())?;
612 validate_identity_field(
613 "logical_session_id",
614 self.identity.logical_session_id(),
615 report.identity.logical_session_id(),
616 )?;
617 validate_identity_field(
618 "function_id",
619 self.identity.function_id(),
620 report.identity.function_id(),
621 )?;
622 validate_identity_field(
623 "producer",
624 self.identity.producer(),
625 report.identity.producer(),
626 )?;
627 if report.requested != self.requested {
628 return Err(ReportValidationError::RequestedCountsMismatch {
629 expected: self.requested,
630 observed: report.requested,
631 });
632 }
633 Ok(())
634 }
635
636 pub fn validate_json(&self, json: &[u8]) -> Result<ReportEnvelopeV2, ReportValidationError> {
641 let report = serde_json::from_slice(json).map_err(|error| {
642 ReportValidationError::InvalidEnvelope {
643 message: error.to_string(),
644 }
645 })?;
646 self.validate(&report)?;
647 Ok(report)
648 }
649
650 pub fn bind(
653 &self,
654 report: ReportEnvelopeV2,
655 binding: ProviderReportBinding,
656 expected_binding: &ExpectedProviderBinding,
657 ) -> Result<BoundRunReportV2, ReportBindingError> {
658 self.validate(&report)?;
659 expected_binding.validate(&binding)?;
660 Ok(BoundRunReportV2 {
661 envelope: report,
662 binding,
663 })
664 }
665}
666
667fn validate_binding_field(
668 field: &'static str,
669 expected: &ReportIdentifier,
670 observed: &ReportIdentifier,
671) -> Result<(), ReportBindingError> {
672 if observed != expected {
673 return Err(ReportBindingError::ProviderFieldMismatch {
674 field,
675 expected: expected.clone(),
676 observed: observed.clone(),
677 });
678 }
679 Ok(())
680}
681
682fn validate_identity_field(
683 field: &'static str,
684 expected: &ReportIdentifier,
685 observed: &ReportIdentifier,
686) -> Result<(), ReportValidationError> {
687 if observed != expected {
688 return Err(ReportValidationError::IdentityMismatch {
689 field,
690 expected: expected.clone(),
691 observed: observed.clone(),
692 });
693 }
694 Ok(())
695}
696
697fn validate_failure_message(message: &str) -> Result<(), ReportValidationError> {
698 if message.trim().is_empty() {
699 return Err(ReportValidationError::EmptyFailureMessage);
700 }
701 if message.len() > MAX_REPORT_FAILURE_MESSAGE_BYTES {
702 return Err(ReportValidationError::FailureMessageTooLong {
703 length: message.len(),
704 limit: MAX_REPORT_FAILURE_MESSAGE_BYTES,
705 });
706 }
707 Ok(())
708}
709
710#[derive(Clone, Debug, PartialEq, Eq)]
711struct BoundedSamples(Vec<u64>);
712
713impl BoundedSamples {
714 fn new(samples: Vec<u64>) -> Result<Self, ReportConstructionError> {
715 if samples.len() > MAX_REPORT_SAMPLES {
716 return Err(ReportConstructionError::TooManySamples {
717 count: samples.len(),
718 limit: MAX_REPORT_SAMPLES,
719 });
720 }
721 Ok(Self(samples))
722 }
723}
724
725impl Serialize for BoundedSamples {
726 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
727 where
728 S: Serializer,
729 {
730 self.0.serialize(serializer)
731 }
732}
733
734impl<'de> Deserialize<'de> for BoundedSamples {
735 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
736 where
737 D: Deserializer<'de>,
738 {
739 struct SamplesVisitor;
740
741 impl<'de> de::Visitor<'de> for SamplesVisitor {
742 type Value = BoundedSamples;
743
744 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
745 write!(formatter, "at most {MAX_REPORT_SAMPLES} nanosecond samples")
746 }
747
748 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
749 where
750 A: de::SeqAccess<'de>,
751 {
752 let mut samples =
753 Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(MAX_REPORT_SAMPLES));
754 while let Some(sample) = sequence.next_element()? {
755 if samples.len() == MAX_REPORT_SAMPLES {
756 return Err(de::Error::custom(format_args!(
757 "report has more than {MAX_REPORT_SAMPLES} samples"
758 )));
759 }
760 samples.push(sample);
761 }
762 Ok(BoundedSamples(samples))
763 }
764 }
765
766 deserializer.deserialize_seq(SamplesVisitor)
767 }
768}
769
770#[derive(Clone, Debug, Error, PartialEq, Eq)]
772pub enum ReportValidationError {
773 #[error("invalid v2 report envelope: {message}")]
774 InvalidEnvelope { message: String },
775 #[error("wrong report schema: expected {expected}, observed {observed}")]
776 WrongSchema {
777 expected: &'static str,
778 observed: String,
779 },
780 #[error("report identity field {field} mismatched: expected {expected}, observed {observed}")]
781 IdentityMismatch {
782 field: &'static str,
783 expected: ReportIdentifier,
784 observed: ReportIdentifier,
785 },
786 #[error("requested report counts mismatched: expected {expected:?}, observed {observed:?}")]
787 RequestedCountsMismatch {
788 expected: ReportCounts,
789 observed: ReportCounts,
790 },
791 #[error("observed report counts do not match requested counts")]
792 ObservedCountsMismatch {
793 requested: ReportCounts,
794 observed: ReportCounts,
795 },
796 #[error("observed report counts exceed requested counts")]
797 ObservedCountsExceedRequested {
798 requested: ReportCounts,
799 observed: ReportCounts,
800 },
801 #[error("unknown report outcome status {status}")]
802 UnknownOutcome { status: String },
803 #[error("a report must request at least one measured iteration")]
804 ZeroIterations,
805 #[error("successful report has no samples")]
806 EmptySuccessSamples,
807 #[error("successful report expected {expected} samples, observed {observed}")]
808 SampleCountMismatch { expected: u32, observed: usize },
809 #[error("report has {count} samples; maximum is {limit}")]
810 TooManySamples { count: usize, limit: usize },
811 #[error("failure report message is empty")]
812 EmptyFailureMessage,
813 #[error("failure report message is {length} bytes; maximum is {limit}")]
814 FailureMessageTooLong { length: usize, limit: usize },
815}
816
817#[derive(Clone, Debug, Error, PartialEq, Eq)]
819pub enum ReportBindingError {
820 #[error(transparent)]
822 Report(#[from] ReportValidationError),
823 #[error("provider binding field {field} mismatched: expected {expected}, observed {observed}")]
825 ProviderFieldMismatch {
826 field: &'static str,
827 expected: ReportIdentifier,
828 observed: ReportIdentifier,
829 },
830 #[error("provider observed device {observed}, expected authenticated device {expected}")]
832 ObservedDeviceMismatch {
833 expected: ReportIdentifier,
834 observed: ReportIdentifier,
835 },
836}
837
838#[derive(Clone, Debug, Error, PartialEq, Eq)]
840pub enum ReportConstructionError {
841 #[error("report count {value} exceeds maximum {limit}")]
842 CountTooLarge { value: u32, limit: u32 },
843 #[error("a report must request at least one measured iteration")]
844 ZeroIterations,
845 #[error("report has {count} samples; maximum is {limit}")]
846 TooManySamples { count: usize, limit: usize },
847 #[error("successful report has no samples")]
848 EmptySuccessSamples,
849 #[error("successful report expected {expected} samples, observed {observed}")]
850 SampleCountMismatch { expected: u32, observed: usize },
851 #[error("observed report counts do not match requested counts")]
852 ObservedCountsMismatch {
853 requested: ReportCounts,
854 observed: ReportCounts,
855 },
856 #[error("observed report counts exceed requested counts")]
857 ObservedCountsExceedRequested {
858 requested: ReportCounts,
859 observed: ReportCounts,
860 },
861 #[error("unknown report outcome status {status}")]
862 UnknownOutcome { status: String },
863 #[error("failure report message is empty")]
864 EmptyFailureMessage,
865 #[error("failure report message is {length} bytes; maximum is {limit}")]
866 FailureMessageTooLong { length: usize, limit: usize },
867}
868
869impl ReportConstructionError {
870 fn from_validation(error: ReportValidationError) -> Self {
871 match error {
872 ReportValidationError::ZeroIterations => Self::ZeroIterations,
873 ReportValidationError::EmptySuccessSamples => Self::EmptySuccessSamples,
874 ReportValidationError::SampleCountMismatch { expected, observed } => {
875 Self::SampleCountMismatch { expected, observed }
876 }
877 ReportValidationError::TooManySamples { count, limit } => {
878 Self::TooManySamples { count, limit }
879 }
880 ReportValidationError::ObservedCountsMismatch {
881 requested,
882 observed,
883 } => Self::ObservedCountsMismatch {
884 requested,
885 observed,
886 },
887 ReportValidationError::ObservedCountsExceedRequested {
888 requested,
889 observed,
890 } => Self::ObservedCountsExceedRequested {
891 requested,
892 observed,
893 },
894 ReportValidationError::UnknownOutcome { status } => Self::UnknownOutcome { status },
895 ReportValidationError::EmptyFailureMessage => Self::EmptyFailureMessage,
896 ReportValidationError::FailureMessageTooLong { length, limit } => {
897 Self::FailureMessageTooLong { length, limit }
898 }
899 ReportValidationError::InvalidEnvelope { .. }
900 | ReportValidationError::WrongSchema { .. }
901 | ReportValidationError::IdentityMismatch { .. }
902 | ReportValidationError::RequestedCountsMismatch { .. } => {
903 unreachable!("local v2 construction sets schema and has no expected identity")
904 }
905 }
906 }
907}
908
909#[derive(Clone, Debug, PartialEq, Eq)]
914pub struct ReducedProvenanceReport {
915 function_id: ReportIdentifier,
916 samples_ns: Vec<u64>,
917 reported_iterations: Option<ReportCount>,
918 reported_warmup: Option<ReportCount>,
919}
920
921impl ReducedProvenanceReport {
922 pub fn function_id(&self) -> &ReportIdentifier {
924 &self.function_id
925 }
926
927 pub fn samples_ns(&self) -> &[u64] {
929 &self.samples_ns
930 }
931
932 pub fn reported_iterations(&self) -> Option<u32> {
934 self.reported_iterations.map(ReportCount::get)
935 }
936
937 pub fn reported_warmup(&self) -> Option<u32> {
939 self.reported_warmup.map(ReportCount::get)
940 }
941}
942
943#[derive(Deserialize)]
944struct LegacyV1WireReport {
945 function: ReportIdentifier,
946 samples_ns: BoundedSamples,
947 iterations: Option<ReportCount>,
948 warmup: Option<ReportCount>,
949}
950
951#[derive(Deserialize)]
952struct VersionProbe {
953 #[serde(default)]
954 schema_version: Option<String>,
955}
956
957pub fn adapt_legacy_v1_json(json: &[u8]) -> Result<ReducedProvenanceReport, LegacyV1AdapterError> {
959 let version: VersionProbe = serde_json::from_slice(json)
960 .map_err(|error| LegacyV1AdapterError::InvalidLegacyReport(error.to_string()))?;
961 if let Some(schema_version) = version.schema_version {
962 return Err(LegacyV1AdapterError::VersionedEnvelope { schema_version });
963 }
964 let legacy: LegacyV1WireReport = serde_json::from_slice(json)
965 .map_err(|error| LegacyV1AdapterError::InvalidLegacyReport(error.to_string()))?;
966 Ok(ReducedProvenanceReport {
967 function_id: legacy.function,
968 samples_ns: legacy.samples_ns.0,
969 reported_iterations: legacy.iterations,
970 reported_warmup: legacy.warmup,
971 })
972}
973
974#[derive(Clone, Debug, Error, PartialEq, Eq)]
976pub enum LegacyV1AdapterError {
977 #[error("invalid legacy v1 report: {0}")]
978 InvalidLegacyReport(String),
979 #[error("legacy v1 adapter refuses versioned envelope {schema_version}")]
980 VersionedEnvelope { schema_version: String },
981}
982
983#[cfg(test)]
984mod tests {
985 use super::*;
986
987 #[test]
988 fn identifiers_reject_unsafe_components() {
989 for value in ["", ".", "..", "a/b", "a\\b", " a", "a\n"] {
990 assert!(
991 ReportIdentifier::parse(value).is_err(),
992 "accepted {value:?}"
993 );
994 }
995 assert!(ReportIdentifier::parse("sample_fns::checksum").is_ok());
996 assert!(ReportIdentifier::parse("Pixel 9-16.0").is_ok());
997 }
998
999 #[test]
1000 fn counts_are_bounded() {
1001 assert_eq!(
1002 ReportCount::new(MAX_REPORT_COUNT).unwrap().get(),
1003 MAX_REPORT_COUNT
1004 );
1005 assert_eq!(
1006 ReportCount::new(MAX_REPORT_COUNT + 1),
1007 Err(ReportConstructionError::CountTooLarge {
1008 value: MAX_REPORT_COUNT + 1,
1009 limit: MAX_REPORT_COUNT,
1010 })
1011 );
1012 assert_eq!(
1013 ReportCounts::observed(0, 0)
1014 .expect("failed run may observe no iterations")
1015 .iterations(),
1016 0
1017 );
1018 }
1019}