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
//! Types related to query API calls

use serde::{Deserialize, Serialize};

use super::{enums::object_type::IcingaObjectType, metadata::IcingaMetadata};

/// wrapper for Json results
#[derive(Debug, Clone, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct ResultsWrapper<T> {
    /// the internal field in the Icinga2 object containing all an array of the actual results
    pub results: Vec<T>,
}

/// the result of an icinga query to a type with joins
#[derive(Debug, Clone, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct QueryResultObjectWithJoins<Obj, ObjJoins> {
    /// dependency attributes
    pub attrs: Obj,
    /// joins
    pub joins: ObjJoins,
    /// metadata, only contains data if the parameter meta contains one or more values
    pub meta: IcingaMetadata,
    /// object name
    pub name: String,
    /// type of icinga object, should always be the one matching Obj
    #[serde(rename = "type")]
    pub object_type: IcingaObjectType,
}

/// the result of an icinga query to a type without joins
#[derive(Debug, Clone, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct QueryResultObject<Obj> {
    /// dependency attributes
    pub attrs: Obj,
    /// metadata, only contains data if the parameter meta contains one or more values
    pub meta: IcingaMetadata,
    /// object name
    pub name: String,
    /// type of icinga object, should always be the one matching Obj
    #[serde(rename = "type")]
    pub object_type: IcingaObjectType,
}

/// represents a type of icinga object which can returned by a query
pub trait QueryableObject {
    /// the type of the endpoint for listing all objects of this type
    type ListEndpoint;

    /// returns the endpoint constructed by calling the builder's build method
    /// without calling any of the builder methods first
    ///
    /// # Errors
    ///
    /// this returns any errors the builder's builder() call produces
    fn default_query_endpoint() -> Result<Self::ListEndpoint, crate::error::Error>;
}

/// implement a query REST API Endpoint for the given Icinga type with join support
macro_rules! query_with_joins {
    ($name:ident, $builder_name:ident, $object_category:path, $path_component:path, $return_type:ty, $join_types:ty, $join_return_type:ty, $object_type:expr, $url_fragment:expr) => {
        use std::collections::BTreeMap;

#[rustfmt::skip]
        use crate::types::{
            enums::object_type::IcingaObjectType,
            filter::IcingaFilter,
            join_types::{
                add_joins_to_url,
                $path_component::{$join_return_type, $join_types},
                IcingaJoins,
            },
            metadata::{add_meta_to_url, IcingaMetadataType},
            query::{QueryableObject, QueryResultObject, QueryResultObjectWithJoins, ResultsWrapper},
            rest::{RestApiEndpoint, RestApiResponse},
            $object_category::{
                $path_component::{
                    $return_type,
                }
            }
        };

        /// query for Icinga objects of this type
        #[allow(clippy::missing_errors_doc)]
        #[derive(Debug, Clone, derive_builder::Builder)]
        #[builder(
            build_fn(error = "crate::error::Error", validate = "Self::validate"),
            derive(Debug)
        )]
        pub struct $name<'a> {
            /// the joins (related objects) to return along with each result
            #[builder(default, setter(strip_option, into))]
            joins: Option<IcingaJoins<'a, $join_types>>,
            /// the metadata to return along with each result
            #[builder(default, setter(strip_option, into))]
            meta: Option<Vec<IcingaMetadataType>>,
            /// filter the results
            #[builder(default, setter(strip_option, into))]
            filter: Option<IcingaFilter>,
        }

        impl<'a> $name<'a> {
            /// create a new builder for this endpoint
            ///
            /// this is usually the first step to calling this REST API endpoint
            #[must_use]
            pub fn builder() -> $builder_name<'a> {
                $builder_name::default()
            }
        }

        impl QueryableObject for $return_type {
            type ListEndpoint = $name<'static>;

            fn default_query_endpoint() -> Result<Self::ListEndpoint, crate::error::Error> {
                $name::builder().build()
            }
        }

        impl<'a> $builder_name<'a> {
            /// makes sure the filter object type is the correct one for the type of return values this endpoint returns
            ///
            /// # Errors
            ///
            /// this returns an error if the filter field object type does not match the return type of the API call
            pub fn validate(&self) -> Result<(), crate::error::Error> {
                let expected = $object_type;
                if let Some(Some(filter)) = &self.filter {
                    if filter.object_type != expected {
                        Err(crate::error::Error::FilterObjectTypeMismatch(
                            vec![expected],
                            filter.object_type.to_owned(),
                        ))
                    } else {
                        Ok(())
                    }
                } else {
                    Ok(())
                }
            }
        }

        impl<'a> RestApiEndpoint for $name<'a> {
            type RequestBody = IcingaFilter;

            fn method(&self) -> Result<reqwest::Method, crate::error::Error> {
                Ok(reqwest::Method::GET)
            }

            fn url(&self, base_url: &url::Url) -> Result<url::Url, crate::error::Error> {
                let mut url = base_url
                    .join($url_fragment)
                    .map_err(crate::error::Error::CouldNotParseUrlFragment)?;
                if let Some(joins) = &self.joins {
                    add_joins_to_url(&mut url, &joins)?;
                }
                if let Some(meta) = &self.meta {
                    add_meta_to_url(&mut url, &meta)?;
                }
                Ok(url)
            }

            fn request_body(
                &self,
            ) -> Result<Option<std::borrow::Cow<Self::RequestBody>>, crate::error::Error>
            where
                Self::RequestBody: Clone + serde::Serialize + std::fmt::Debug,
            {
                Ok(self.filter.as_ref().map(|f| std::borrow::Cow::Borrowed(f)))
            }
        }

        impl<'a> RestApiResponse<$name<'a>> for ResultsWrapper<QueryResultObject<$return_type>> {}

        impl<'a> RestApiResponse<$name<'a>>
            for ResultsWrapper<QueryResultObject<BTreeMap<String, serde_json::Value>>>
        {
        }

        impl<'a> RestApiResponse<$name<'a>>
            for ResultsWrapper<QueryResultObjectWithJoins<$return_type, $join_return_type>>
        {
        }

        impl<'a> RestApiResponse<$name<'a>>
            for ResultsWrapper<
                QueryResultObjectWithJoins<BTreeMap<String, serde_json::Value>, $join_return_type>,
            >
        {
        }

        impl<'a> RestApiResponse<$name<'a>>
            for ResultsWrapper<
                QueryResultObjectWithJoins<$return_type, BTreeMap<String, serde_json::Value>>,
            >
        {
        }

        impl<'a> RestApiResponse<$name<'a>>
            for ResultsWrapper<
                QueryResultObjectWithJoins<
                    BTreeMap<String, serde_json::Value>,
                    BTreeMap<String, serde_json::Value>,
                >,
            >
        {
        }
    };
}
pub(crate) use query_with_joins;

/// implement a query REST API Endpoint for the given Icinga type without join support
macro_rules! query {
    ($name:ident, $builder_name:ident, $object_category:path, $path_component:path, $return_type:ty, $object_type:expr, $url_fragment:expr) => {
        use std::collections::BTreeMap;

#[rustfmt::skip]
        use crate::types::{
            enums::object_type::IcingaObjectType,
            filter::IcingaFilter,
            metadata::{add_meta_to_url, IcingaMetadataType},
            query::{QueryableObject, QueryResultObject, ResultsWrapper},
            rest::{RestApiEndpoint, RestApiResponse},
            $object_category::{
                $path_component::{
                    $return_type,
                },
            },
        };

        /// query for Icinga objects of this type
        #[allow(clippy::missing_errors_doc)]
        #[derive(Debug, Clone, derive_builder::Builder)]
        #[builder(
            build_fn(error = "crate::error::Error", validate = "Self::validate"),
            derive(Debug)
        )]
        pub struct $name {
            /// the metadata to return along with each result
            #[builder(default, setter(strip_option, into))]
            meta: Option<Vec<IcingaMetadataType>>,
            /// filter the results
            #[builder(default, setter(strip_option, into))]
            filter: Option<IcingaFilter>,
        }

        impl $name {
            /// create a new builder for this endpoint
            ///
            /// this is usually the first step to calling this REST API endpoint
            #[must_use]
            pub fn builder() -> $builder_name {
                $builder_name::default()
            }
        }

        impl QueryableObject for $return_type {
            type ListEndpoint = $name;

            fn default_query_endpoint() -> Result<Self::ListEndpoint, crate::error::Error> {
                $name::builder().build()
            }
        }

        impl $builder_name {
            /// makes sure the filter object type is the correct one for the type of return values this endpoint returns
            ///
            /// # Errors
            ///
            /// this returns an error if the filter field object type does not match the return type of the API call
            pub fn validate(&self) -> Result<(), crate::error::Error> {
                let expected = $object_type;
                if let Some(Some(filter)) = &self.filter {
                    if filter.object_type != expected {
                        Err(crate::error::Error::FilterObjectTypeMismatch(
                            vec![expected],
                            filter.object_type.to_owned(),
                        ))
                    } else {
                        Ok(())
                    }
                } else {
                    Ok(())
                }
            }
        }

        impl RestApiEndpoint for $name {
            type RequestBody = IcingaFilter;

            fn method(&self) -> Result<reqwest::Method, crate::error::Error> {
                Ok(reqwest::Method::GET)
            }

            fn url(&self, base_url: &url::Url) -> Result<url::Url, crate::error::Error> {
                let mut url = base_url
                    .join($url_fragment)
                    .map_err(crate::error::Error::CouldNotParseUrlFragment)?;
                if let Some(meta) = &self.meta {
                    add_meta_to_url(&mut url, &meta)?;
                }
                Ok(url)
            }

            fn request_body(
                &self,
            ) -> Result<Option<std::borrow::Cow<Self::RequestBody>>, crate::error::Error>
            where
                Self::RequestBody: Clone + serde::Serialize + std::fmt::Debug,
            {
                Ok(self.filter.as_ref().map(|f| std::borrow::Cow::Borrowed(f)))
            }
        }

        impl RestApiResponse<$name> for ResultsWrapper<QueryResultObject<$return_type>> {}

        impl RestApiResponse<$name>
            for ResultsWrapper<QueryResultObject<BTreeMap<String, serde_json::Value>>>
        {
        }
    };
}
pub(crate) use query;