samples.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from typing import Dict, NamedTuple, Optional, Sequence, Union
  2. class Timestamp:
  3. """A nanosecond-resolution timestamp."""
  4. def __init__(self, sec: float, nsec: float) -> None:
  5. if nsec < 0 or nsec >= 1e9:
  6. raise ValueError(f"Invalid value for nanoseconds in Timestamp: {nsec}")
  7. if sec < 0:
  8. nsec = -nsec
  9. self.sec: int = int(sec)
  10. self.nsec: int = int(nsec)
  11. def __str__(self) -> str:
  12. return f"{self.sec}.{self.nsec:09d}"
  13. def __repr__(self) -> str:
  14. return f"Timestamp({self.sec}, {self.nsec})"
  15. def __float__(self) -> float:
  16. return float(self.sec) + float(self.nsec) / 1e9
  17. def __eq__(self, other: object) -> bool:
  18. return isinstance(other, Timestamp) and self.sec == other.sec and self.nsec == other.nsec
  19. def __ne__(self, other: object) -> bool:
  20. return not self == other
  21. def __gt__(self, other: "Timestamp") -> bool:
  22. return self.nsec > other.nsec if self.sec == other.sec else self.sec > other.sec
  23. def __lt__(self, other: "Timestamp") -> bool:
  24. return self.nsec < other.nsec if self.sec == other.sec else self.sec < other.sec
  25. # BucketSpan is experimental and subject to change at any time.
  26. class BucketSpan(NamedTuple):
  27. offset: int
  28. length: int
  29. # Timestamp and exemplar are optional.
  30. # Value can be an int or a float.
  31. # Timestamp can be a float containing a unixtime in seconds,
  32. # a Timestamp object, or None.
  33. # Exemplar can be an Exemplar object, or None.
  34. class Exemplar(NamedTuple):
  35. labels: Dict[str, str]
  36. value: float
  37. timestamp: Optional[Union[float, Timestamp]] = None
  38. # NativeHistogram is experimental and subject to change at any time.
  39. class NativeHistogram(NamedTuple):
  40. count_value: float
  41. sum_value: float
  42. schema: int
  43. zero_threshold: float
  44. zero_count: float
  45. pos_spans: Optional[Sequence[BucketSpan]] = None
  46. neg_spans: Optional[Sequence[BucketSpan]] = None
  47. pos_deltas: Optional[Sequence[int]] = None
  48. neg_deltas: Optional[Sequence[int]] = None
  49. nh_exemplars: Optional[Sequence[Exemplar]] = None
  50. class Sample(NamedTuple):
  51. name: str
  52. labels: Dict[str, str]
  53. value: float
  54. timestamp: Optional[Union[float, Timestamp]] = None
  55. exemplar: Optional[Exemplar] = None
  56. native_histogram: Optional[NativeHistogram] = None