chroma_types/
types.rs

1use chroma_error::{ChromaError, ErrorCodes};
2use thiserror::Error;
3use tonic::Status;
4
5/// Macro to define UUID newtype wrappers with standard implementations.
6/// Reduces boilerplate for UUID wrapper types.
7///
8/// Generates:
9/// - Struct with standard derives (Copy, Clone, Debug, etc.)
10/// - new() method with configurable UUID generation (v4 for random, v7 for time-ordered)
11/// - FromStr implementation for parsing from strings
12/// - Display implementation for formatting
13///
14/// # Examples
15///
16/// ```ignore
17/// define_uuid_newtype!(
18///     /// My custom UUID type.
19///     MyUuid,
20///     new_v4
21/// );
22/// ```
23macro_rules! define_uuid_newtype {
24    ($(#[$meta:meta])* $name:ident, $uuid_fn:ident) => {
25        $(#[$meta])*
26        #[derive(
27            Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize,
28        )]
29        pub struct $name(pub uuid::Uuid);
30
31        impl $name {
32            pub fn new() -> Self {
33                $name(uuid::Uuid::$uuid_fn())
34            }
35        }
36
37        impl std::str::FromStr for $name {
38            type Err = uuid::Error;
39            fn from_str(s: &str) -> Result<Self, Self::Err> {
40                uuid::Uuid::parse_str(s).map($name)
41            }
42        }
43
44        impl std::fmt::Display for $name {
45            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46                write!(f, "{}", self.0)
47            }
48        }
49    };
50}
51
52/// A macro for easily implementing match arms for a base error type with common errors.
53/// Other types can wrap it and still implement the ChromaError trait
54/// without boilerplate.
55macro_rules! impl_base_convert_error {
56    ($err:ty, { $($variant:pat => $action:expr),* $(,)? }) => {
57        impl ChromaError for $err {
58            fn code(&self) -> ErrorCodes {
59                match self {
60                    Self::DecodeError(inner) => inner.code(),
61                    // Handle custom variants
62                    $( $variant => $action, )*
63                }
64            }
65        }
66    };
67}
68
69#[derive(Error, Debug)]
70pub enum ConversionError {
71    #[error("Error decoding protobuf message")]
72    DecodeError,
73}
74
75impl ChromaError for ConversionError {
76    fn code(&self) -> ErrorCodes {
77        ErrorCodes::InvalidArgument
78    }
79}
80
81impl From<ConversionError> for Status {
82    fn from(value: ConversionError) -> Self {
83        Status::invalid_argument(value.to_string())
84    }
85}
86
87#[derive(thiserror::Error, Debug)]
88#[error(transparent)]
89pub enum WrappedSerdeJsonError {
90    #[error(transparent)]
91    SerdeJsonError(#[from] serde_json::Error),
92}
93
94impl ChromaError for WrappedSerdeJsonError {
95    fn code(&self) -> ErrorCodes {
96        ErrorCodes::InvalidArgument
97    }
98}