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
//! A [serde][] implementation for Prometheus' text-based exposition format.
//!
//! Currently this library only supports serialisation to Prometheus' format
//! for exporting metrics but this might be extended to deserialisation
//! later on down the line.
//!
//! serde_prometheus will work with most metric libraries' structs out of the
//! box, however some work may be required to get them into a format expected
//! by Prometheus.
//!
//! Metric names exposed in the format are derived from the value's name in the
//! struct or map that contains it.
//!
//! ## Basic Usage
//!
//! ```rust
//! # use std::collections::HashMap;
//! # use serde::Serialize;
//! # fn main() -> Result<(), serde_prometheus::Error> {
//! #[derive(Serialize)]
//! struct HitCount(u64);
//!
//! #[derive(Serialize)]
//! struct MetricRegistry {
//!     my_struct: MyStructMetrics
//! }
//!
//! #[derive(Serialize)]
//! struct MyStructMetrics {
//!     hit_count: HitCount
//! }
//!
//! let metrics = MetricRegistry {
//!     my_struct: MyStructMetrics {
//!         hit_count: HitCount(30)
//!     }
//! };
//!
//! assert_eq!(
//!    serde_prometheus::to_string(&metrics, None, HashMap::new())?,
//!    "hit_count{path = \"my_struct\"} 30\n"
//! );
//! # Ok(())
//! # }
//! ```
//!
//! ## Global Labels
//!
//! Global labels can be added to all metrics exported by serde_prometheus using
//! the `HashMap` passed into `serde_prometheus::to_string` for example:
//!
//! ```rust
//! # use std::collections::HashMap;
//! # use serde::Serialize;
//! # fn main() -> Result<(), serde_prometheus::Error> {
//! # #[derive(Serialize)]
//! # struct HitCount(u64);
//! #
//! # #[derive(Serialize)]   
//! # struct MetricRegistry {
//! #     my_struct: MyStructMetrics
//! # }
//! #
//! # #[derive(Serialize)]    
//! # struct MyStructMetrics {
//! #     hit_count: HitCount 
//! # }
//! # 
//! # let metrics = MetricRegistry {  
//! #     my_struct: MyStructMetrics {
//! #         hit_count: HitCount(30) 
//! #     }
//! # };
//! let mut labels = HashMap::new();
//! labels.insert("my_key", "my_value");
//!
//! let serialised = serde_prometheus::to_string(&metrics, None, labels)?;
//! # // deal with HashMap reordering vals
//! # if serialised.contains("{path") {
//! #     assert_eq!(serialised, "hit_count{path = \"my_struct\", my_key = \"my_value\"} 30\n");
//! # } else {
//! assert_eq!(serialised, "hit_count{my_key = \"my_value\", path = \"my_struct\"} 30\n");
//! # }
//! # Ok(())
//! # }
//! ```
//!
//! ## Global Prefix
//!
//! And a global prefix can be added to all metrics:
//!
//! ```rust
//! # use std::collections::HashMap;
//! # use serde::Serialize;
//! # fn main() -> Result<(), serde_prometheus::Error> {
//! # #[derive(Serialize)]
//! # struct HitCount(u64);
//! #
//! # #[derive(Serialize)]   
//! # struct MetricRegistry {
//! #     my_struct: MyStructMetrics
//! # }
//! #  
//! # #[derive(Serialize)]    
//! # struct MyStructMetrics {
//! #     hit_count: HitCount 
//! # }
//! #  
//! # let metrics = MetricRegistry {  
//! #     my_struct: MyStructMetrics {
//! #         hit_count: HitCount(30) 
//! #     }
//! # };
//! assert_eq!(
//!    serde_prometheus::to_string(&metrics, Some("my_prefix"), HashMap::new())?,
//!    "my_prefix_hit_count{path = \"my_struct\"} 30\n"
//! );
//! # Ok(())
//! # }
//! ```
//!
//! ## Metadata/key manipulation
//!
//! Serde's newtype implementation is (ab)used by serde_prometheus to add metadata
//! to serialised fields without breaking backwards compatibility with serde_json
//! and such.
//!
//! For example, [serde_prometheus support has been added to metered-rs][mrsimpl]'s
//! histograms whilst still keeping the same JSON schema, it does this by using
//! a call to `serialize_newtype_struct` in a struct's Serialize trait impl, the
//! format for the type names is as follows:
//!
//! ```txt
//! modifiers|key=value,key2=value2
//! ```
//!
//! The modifiers that can be used are:
//!
//! | Modifier     | Description |
//! | ------------ | ----------- |
//! | <            | Pops a value off of the `path` stack and prepends it to the name |
//! | !            | Pops the last value off of the `path` stack and drops it |
//!
//! These can be combined and are read from left to right, for example:
//!
//! ```rust
//! # use std::collections::HashMap;
//! # use serde::{Serializer, Serialize};
//! # fn main() -> Result<(), serde_prometheus::Error> {
//! # #[derive(Serialize)]
//! # struct MetricRegistry {
//! #     my_struct: MyStructMetrics
//! # }
//! #
//! # #[derive(Serialize)]    
//! # struct MyStructMetrics {
//! #     my_method: MyMethodMetrics 
//! # }
//! #
//! # #[derive(Serialize)]
//! # struct MyMethodMetrics {
//! #     hit_count: HitCount
//! # }
//! #
//! struct HitCount(u64);
//! impl Serialize for HitCount {
//!     fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
//!         // ignore the current key, and include the one before
//!         serializer.serialize_newtype_struct("!<|my_key=my_value", &self.0)
//!     }
//! } 
//!
//! let metrics = MetricRegistry {
//!     my_struct: MyStructMetrics {
//!         my_method: MyMethodMetrics {
//!             hit_count: HitCount(30)
//!         }
//!     }
//! };
//!
//! let serialised = serde_prometheus::to_string(&metrics, None, HashMap::new())?;
//! # // deal with HashMap reordering vals
//! # if serialised.contains("{path=") {
//! #     assert_eq!(serialised, "my_struct_my_method{path = \"\", my_key = \"my_value\"}");
//! # } else {
//! // would be `hit_count{my_key = "my_value", path = "my_struct/my_method"}` without the Serialize impl
//! assert_eq!(
//!    serde_prometheus::to_string(&metrics, None, HashMap::new())?,
//!    "my_struct_my_method{my_key = \"my_value\", path = \"\"} 30\n"
//! );
//! # }
//! # Ok(())
//! # }
//! ```
//!
//! [serde]: https://github.com/serde-rs/serde/
//! [mrsimpl]: https://github.com/magnet/metered-rs/commit/b6b61979a2727e3be58737015ba11eb63309ed6b

#![deny(clippy::all)]
#![deny(clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]

mod error;
mod key;
mod label;
mod value;

pub use crate::error::Error;
use crate::key::{Serializer as KeySerializer};
use crate::label::{Serializer as LabelSerializer};
use crate::value::{Serializer as ValueSerializer};

use std::collections::HashMap;
use std::convert::TryFrom;
use std::str::FromStr;
use std::fmt::Display;
use std::borrow::Cow;

use serde::{Serialize, ser::{Impossible, SerializeMap, SerializeStruct, SerializeSeq}};
use snafu::ResultExt;

pub enum TypeHint {
    Counter = 1337,
    Guage = 1338,
    Histogram = 1339,
    Summary = 1340,
}
impl TryFrom<u32> for TypeHint {
    type Error = Error;

    fn try_from(x: u32) -> Result<Self, Self::Error> {
        match x {
            x if x == TypeHint::Counter as u32 => Ok(TypeHint::Counter),
            x if x == TypeHint::Guage as u32 => Ok(TypeHint::Guage),
            x if x == TypeHint::Histogram as u32 => Ok(TypeHint::Histogram),
            x if x == TypeHint::Summary as u32 => Ok(TypeHint::Summary),
            _ => Err(Error::UnsupportedValue { kind: "TypeHint".to_string() }),
        }
    }
}
impl FromStr for TypeHint {
    type Err = Error;

    fn from_str(v: &str) -> std::result::Result<Self, Self::Err> {
        match v {
            "counter" => Ok(TypeHint::Counter),
            "guage" => Ok(TypeHint::Guage),
            "histogram" => Ok(TypeHint::Histogram),
            "summary" => Ok(TypeHint::Summary),
            _ => Err(Error::UnknownHint),
        }
    }
}
impl Display for TypeHint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            TypeHint::Counter => "counter",
            TypeHint::Guage => "guage",
            TypeHint::Histogram => "histogram",
            TypeHint::Summary => "summary",
        })
    }
}

struct Serializer<'a, T: std::io::Write, S: std::hash::BuildHasher> {
    namespace: Option<&'a str>,
    path: Vec<String>,
    global_labels: HashMap<&'a str, &'a str, S>,
    output: T,
}

/// Outputs a `metered::MetricRegistry` in Prometheus' simple text-based exposition
/// format.
pub fn to_string<T, S>(
    value: &T,
    namespace: Option<&str>,
    global_labels: HashMap<&str, &str, S>,
) -> Result<String, Error>
where
    T: ?Sized + Serialize,
    S: std::hash::BuildHasher,
{
    let mut serializer = Serializer {
        namespace,
        path: vec![],
        global_labels,
        // sizeof(value) * 4 to get the size of the utf8-repr of the values then multiply by 12 to
        // get a decent estimate of the size of this output including keys.
        output: Vec::with_capacity(std::mem::size_of_val(value) * 4 * 12),
    };
    value.serialize(&mut serializer)?;
    Ok(String::from_utf8(serializer.output).unwrap())
}

impl<T: std::io::Write, S: std::hash::BuildHasher> Serializer<'_, T, S> {
    fn write_key<'a>(&mut self, hint: Option<TypeHint>, key: Option<Cow<'a, str>>) -> Result<(), Error> {
        let path = self.path.last();

        let key = match (path, key) {
            (Some(path), Some(key)) => format!("{}_{}", path, key.as_ref()),
            (_,          Some(key)) => key.into_owned(),
            (Some(path), _) => path.to_string(),
            (_,          _) => return Err(error::Error::NoMetricName),
        };
        let key = match self.namespace {
            Some(namespace) => format!("{}_{}", namespace, key),
            None => key,
        };

        if let Some(typ) = hint {
            writeln!(self.output, "# TYPE {} {}", key, typ)?;
        }

        key.serialize(&mut KeySerializer {
            output: &mut self.output,
        })?;

        Ok(())
    }

    fn write_labels(&mut self, extras: Option<HashMap<&str, &str>>) -> Result<(), Error> {
        let mut map = extras.unwrap_or_default();

        let path = if self.path.is_empty() {
            None
        } else {
            Some(self.path[..self.path.len() - 1].join("/"))
        };
        if let Some(path) = path.as_ref() {
            map.insert("path", path);
        }

        for (key, value) in &self.global_labels {
            map.insert(key, value);
        }

        if !map.is_empty() {
            map.serialize(&mut LabelSerializer {
                output: &mut self.output,
                remaining: 0,
            })?;
        }

        Ok(())
    }

    fn write_value<V: Serialize>(&mut self, value: V) -> Result<(), Error> {
        self.output.write_all(b" ")?;
        value.serialize(&mut ValueSerializer {
            output: &mut self.output,
        })?;
        self.output.write_all(b"\n")?;

        Ok(())
    }
}

impl<W: std::io::Write, S: std::hash::BuildHasher> serde::Serializer for &mut Serializer<'_, W, S> {
    type Ok = ();
    type Error = Error;
    type SerializeSeq = Self;
    type SerializeTuple = Impossible<Self::Ok, Self::Error>;
    type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
    type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>;
    type SerializeMap = Self;
    type SerializeStruct = Self;
    type SerializeStructVariant = Impossible<Self::Ok, Self::Error>;

    ///////////////////////////////////////////////////////////
    // whole key/value serialisation
    ///////////////////////////////////////////////////////////

    // Unit struct means a named value containing no data.
    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, Some(Cow::Borrowed(name)))?;
        self.write_labels(None)?;
        self.write_value(0)
    }

    fn serialize_newtype_struct<T: ?Sized>(
        self,
        type_name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        let (modifiers, labels) = if type_name.contains('|') {
            let mut split = type_name.splitn(2, '|');
            (split.next().filter(|v| !v.is_empty()), split.next().filter(|v| !v.is_empty()))
        } else {
            (None, Some(type_name).filter(|v| !v.is_empty() && v.contains('=')))
        };

        let original = self.path.clone();
        let mut key = Vec::new(); // VecDeque for push_front?

        if let Some(modifiers) = modifiers {
            for modifier in modifiers.chars() {
                match modifier {
                    // include the last appended path, ignoring excluded ones, in the key instead
                    // of the 'path' label
                    '<' => key.insert(0, self.path.pop().expect("no path to pop!!")),
                    // exclude a path from both the name and the 'path' label
                    '!' => { self.path.pop(); },
                    _ => return Err(Error::InvalidModifier)
                }
            }
        }

        let key = if key.is_empty() {
            None
        } else {
            Some(Cow::Owned(key.join("_")))
        };

        self.write_key(None, key)?;
        self.write_labels(if let Some(label) = labels {
            let mut labels = HashMap::new();
            let pairs = label
                .split(',')
                .map(|pair| pair.splitn(2, '='))
                .map(|mut v| (v.next(), v.next()));

            for (key, value) in pairs {
                labels.insert(
                    key.ok_or(Error::InvalidLabel)?,
                    value.ok_or(Error::InvalidLabel)?,
                );
            }
            Some(labels)
        } else {
            None
        })?;

        self.write_value(value)?;

        self.path = original;

        Ok(())
    }

    fn serialize_newtype_variant<T: ?Sized>(
        self,
        name: &'static str,
        variant_index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        let name = match name {
            "" => None,
            x => Some(Cow::Borrowed(x)),
        };

        let hint = match variant_index {
            0 => None,
            x => Some(TypeHint::try_from(x)?),
        };

        self.write_key(hint, name)?;

        self.write_labels(if variant.contains('=') {
            let mut labels = HashMap::new();
            let pairs = variant
                .split(',')
                .map(|pair| pair.splitn(2, '='))
                .map(|mut v| (v.next(), v.next()));

            for (key, value) in pairs {
                labels.insert(
                    key.ok_or(Error::InvalidLabel)?,
                    value.ok_or(Error::InvalidLabel)?,
                );
            }
            Some(labels)
        } else {
            None
        })?;

        self.write_value(value)?;

        Ok(())
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        Ok(self)
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        Ok(self)
    }

    fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_f32(self, value: f32) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_f64(self, value: f64) -> Result<Self::Ok, Self::Error> {
        self.write_key(None, None)?;
        self.write_labels(None)?;
        self.write_value(value)?;
        Ok(())
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        // noop
        Ok(())
    }

    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        value.serialize(&mut *self)?;
        Ok(())
    }

    ///////////////////////////////////////////////////////////
    // Unsupported key/value serialisers
    ///////////////////////////////////////////////////////////

    fn serialize_unit_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        Err(Error::UnsupportedValue { kind: format!("Unit Variant ({}::{})", name, variant) })
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        Ok(self)
    }

    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        Err(Error::UnsupportedValue { kind: "Tuple".to_string() })
    }

    fn serialize_tuple_struct(
        self,
        name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        Err(Error::UnsupportedValue { kind: format!("Tuple Struct ({})", name) })
    }

    fn serialize_tuple_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        Err(Error::UnsupportedValue { kind: format!("Tuple Variant ({}::{})", name, variant) })
    }

    fn serialize_struct_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        Err(Error::UnsupportedValue { kind: format!("Struct Variant ({}::{})", name, variant) })
    }

    fn collect_str<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Display,
    {
        Err(Error::UnsupportedValue { kind: "collect_str".to_string() })
    }

    fn serialize_str(self, _v: &str) -> Result<Self::Ok, Self::Error> {
        Err(Error::UnsupportedValue { kind: "str".to_string() })
    }

    fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
        Err(Error::UnsupportedValue { kind: "char".to_string() })
    }

    fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
        Err(Error::UnsupportedValue { kind: "bytes".to_string() })
    }

    fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
        Err(Error::UnsupportedValue { kind: "bool".to_string() })
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Err(Error::UnsupportedValue { kind: "()".to_string() })
    }
}

/// Maps are most of the time histograms so we handle them a little bit differently,
/// instead of using the key directly from the map, we modify them a little bit to
/// make them a little bit more Prometheus-like using the `MapKeySerializer`.
impl<W: std::io::Write, S: std::hash::BuildHasher> SerializeMap for &mut Serializer<'_, W, S> {
    type Ok = ();
    type Error = Error;

    fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error> {
        let key_bytes = key.serialize(MapKeySerializer)?;
        self.path.push(std::str::from_utf8(key_bytes.as_bytes()).context(error::MetricNameMustBeUtf8)?.to_owned());

        Ok(())
    }

    fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
        value.serialize(&mut **self)?;
        self.path.pop();
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<W: std::io::Write, S: std::hash::BuildHasher> SerializeStruct for &mut Serializer<'_, W, S> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: ?Sized + Serialize>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<(), Self::Error> {
        self.path.push(key.to_owned());
        value.serialize(&mut **self)?;
        self.path.pop();
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<W: std::io::Write, S: std::hash::BuildHasher> SerializeSeq for &mut Serializer<'_, W, S> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<T: ?Sized + Serialize>(
        &mut self,
        value: &T
    ) -> Result<(), Self::Error> {
        value.serialize(&mut **self)?;
        Ok(())
    }


    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

struct MapKeySerializer;
impl serde::Serializer for MapKeySerializer {
    type Ok = String;
    type Error = Error;

    type SerializeSeq = Impossible<String, Error>;
    type SerializeTuple = Impossible<String, Error>;
    type SerializeTupleStruct = Impossible<String, Error>;
    type SerializeTupleVariant = Impossible<String, Error>;
    type SerializeMap = Impossible<String, Error>;
    type SerializeStruct = Impossible<String, Error>;
    type SerializeStructVariant = Impossible<String, Error>;

    fn serialize_bool(self, _value: bool) -> Result<Self::Ok, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_f32(self, _value: f32) -> Result<Self::Ok, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_f64(self, _value: f64) -> Result<Self::Ok, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_char(self, value: char) -> Result<Self::Ok, Self::Error> {
        // A char encoded as UTF-8 takes 4 bytes at most.
        let mut buf = [0; 4];
        self.serialize_str(value.encode_utf8(&mut buf))
    }

    fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
        Ok(value.to_string())
    }

    fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        Ok(variant.to_string())
    }

    #[inline]
    fn serialize_newtype_struct<T>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        Err(Error::MapKeyMustBeString)
    }

    fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Display,
    {
        Ok(value.to_string())
    }
}

#[cfg(test)]
mod tests {
    use metered::{metered, HitCount, ResponseTime, Throughput};
    use std::collections::HashMap;

    #[derive(serde::Serialize)]
    pub struct ServiceMetricRegistry<'a> {
        biz: &'a BizMetrics,
        baz: &'a BazMetrics,
    }

    #[derive(Default)]
    pub struct Biz {
        metrics: BizMetrics,
    }
    #[metered(registry = BizMetrics)]
    impl Biz {
        #[measure([HitCount, Throughput, ResponseTime])]
        pub fn bizle(&self) {}
    }

    #[derive(Default)]
    pub struct Baz {
        metrics: BazMetrics,
    }
    #[metered(registry = BazMetrics)]
    impl Baz {
        #[measure([HitCount, Throughput, ResponseTime])]
        pub fn bazle(&self) {}
    }

    #[test]
    fn normal_registry() {
        let biz = Biz::default();
        let baz = Baz::default();

        let ret = crate::to_string(
            &ServiceMetricRegistry {
                biz: &biz.metrics,
                baz: &baz.metrics,
            },
            None,
            HashMap::new(),
        )
        .unwrap();
        let split: Vec<&str> = ret.split("\n").collect();

        assert_eq!(split[0], "hit_count{path = \"biz/bizle\"} 0");

        if !split.contains(&"throughput{quantile = \"0.95\", path = \"biz/bizle\"} 0")
            && !split.contains(&"throughput{path = \"biz/bizle\", quantile = \"0.95\"} 0")
        {
            assert!(split.contains(&"throughput{quantile = \"0.95\", path = \"biz/bizle\"} 0"));
        }
    }

    #[test]
    fn wrapped_registry() {
        #[derive(serde::Serialize)]
        pub struct MyWrapperRegistry<'a> {
            wrapper: ServiceMetricRegistry<'a>,
        }

        let biz = Biz::default();
        let baz = Baz::default();

        let mut labels = HashMap::new();
        labels.insert("service", "my_cool_service");
        let ret = crate::to_string(
            &MyWrapperRegistry {
                wrapper: ServiceMetricRegistry {
                    biz: &biz.metrics,
                    baz: &baz.metrics,
                },
            },
            Some("global"),
            labels,
        )
        .unwrap();
        let split: Vec<&str> = ret.split("\n").collect();

        if split[0] != "global_hit_count{service = \"my_cool_service\", path = \"wrapper/biz/bizle\"} 0"
            && split[0] != "global_hit_count{path = \"wrapper/biz/bizle\", service = \"my_cool_service\"} 0"
        {
            assert_eq!(split[0], "global_hit_count{service = \"my_cool_service\", path = \"wrapper/biz/bizle\"} 0");
        }
        if !split.contains(&"global_response_time_count{path = \"wrapper/baz/bazle\", service = \"my_cool_service\"} 0")
            && !split.contains(&"global_response_time_count{service = \"my_cool_service\", path = \"wrapper/baz/bazle\"} 0")
        {
            assert!(split.contains(&"global_response_time_count{service = \"my_cool_service\", path = \"wrapper/biz/bizle\"} 0"));
        }
    }
}