cx_sdk/client/
events2metrics.rs

1// Copyright 2024 Coralogix Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::str::FromStr;
16
17use crate::{
18    auth::AuthContext,
19    error::{
20        Result,
21        SdkApiError,
22    },
23    metadata::CallProperties,
24    util::make_request_with_metadata,
25};
26
27use cx_api::proto::com::coralogixapis::events2metrics::v2::{
28    CreateE2mRequest,
29    CreateE2mResponse,
30    DeleteE2mRequest,
31    DeleteE2mResponse,
32    GetE2mRequest,
33    GetE2mResponse,
34    GetLimitsRequest,
35    GetLimitsResponse,
36    ListE2mRequest,
37    ListE2mResponse,
38    ListLabelsCardinalityRequest,
39    ListLabelsCardinalityResponse,
40    ReplaceE2mRequest,
41    ReplaceE2mResponse,
42    events2_metric_service_client::Events2MetricServiceClient,
43};
44use tokio::sync::Mutex;
45use tonic::{
46    metadata::MetadataMap,
47    transport::{
48        Channel,
49        ClientTlsConfig,
50        Endpoint,
51    },
52};
53
54pub use cx_api::proto::com::coralogixapis::events2metrics::v2::{
55    E2m,
56    E2mCreateParams,
57    MetricField,
58    MetricLabel,
59    list_labels_cardinality_request::Query,
60};
61
62use crate::CoralogixRegion;
63
64const EVENTS2METRICS_FEATURE_GROUP_ID: &str = "events_2_metrics";
65
66/// The Events2Metrics API client.
67/// Read more at <https://coralogix.com/docs/events2metrics/>
68pub struct Events2MetricsClient {
69    metadata_map: MetadataMap,
70    service_client: Mutex<Events2MetricServiceClient<Channel>>,
71}
72
73impl Events2MetricsClient {
74    /// Creates a new client for the Events2Metrics API.
75    ///
76    /// # Arguments
77    /// * `auth_context` - The [`AuthContext`] to use for authentication.
78    /// * `region` - The [`CoralogixRegion`] to connect to.
79    pub fn new(auth_context: AuthContext, region: CoralogixRegion) -> Result<Self> {
80        let channel: Channel = Endpoint::from_str(region.grpc_endpoint().as_str())?
81            .tls_config(ClientTlsConfig::new().with_native_roots())?
82            .connect_lazy();
83        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
84        Ok(Self {
85            metadata_map: request_metadata.to_metadata_map(),
86            service_client: Mutex::new(Events2MetricServiceClient::new(channel)),
87        })
88    }
89
90    /// Creates a new E2M mapping.
91    ///
92    /// # Arguments
93    /// * `params` - The parameters for the E2M mapping.
94    pub async fn create(&self, params: E2mCreateParams) -> Result<CreateE2mResponse> {
95        let request =
96            make_request_with_metadata(CreateE2mRequest { e2m: Some(params) }, &self.metadata_map);
97        Ok(self
98            .service_client
99            .lock()
100            .await
101            .create_e2m(request)
102            .await
103            .map_err(|status| SdkApiError {
104                status,
105                endpoint: "/com.coralogixapis.events2metrics.v2.Events2MetricService/CreateE2M"
106                    .to_string(),
107                feature_group: EVENTS2METRICS_FEATURE_GROUP_ID.to_string(),
108            })?
109            .into_inner())
110    }
111
112    /// Replaces an existing E2M mapping.
113    ///
114    /// # Arguments
115    /// * `e2m` - The E2M mapping to replace.
116    pub async fn replace(&self, e2m: E2m) -> Result<ReplaceE2mResponse> {
117        Ok(self
118            .service_client
119            .lock()
120            .await
121            .replace_e2m(make_request_with_metadata(
122                ReplaceE2mRequest { e2m: Some(e2m) },
123                &self.metadata_map,
124            ))
125            .await
126            .map_err(|status| SdkApiError {
127                status,
128                endpoint: "/com.coralogixapis.events2metrics.v2.Events2MetricService/ReplaceE2M"
129                    .to_string(),
130                feature_group: EVENTS2METRICS_FEATURE_GROUP_ID.to_string(),
131            })?
132            .into_inner())
133    }
134
135    /// Deletes an E2M mapping.
136    ///
137    /// # Arguments
138    /// * `id` - The ID of the E2M mapping to delete.
139    pub async fn delete(&self, id: String) -> Result<DeleteE2mResponse> {
140        Ok(self
141            .service_client
142            .lock()
143            .await
144            .delete_e2m(make_request_with_metadata(
145                DeleteE2mRequest { id: Some(id) },
146                &self.metadata_map,
147            ))
148            .await
149            .map_err(|status| SdkApiError {
150                status,
151                endpoint: "/com.coralogixapis.events2metrics.v2.Events2MetricService/DeleteE2M"
152                    .to_string(),
153                feature_group: EVENTS2METRICS_FEATURE_GROUP_ID.to_string(),
154            })?
155            .into_inner())
156    }
157
158    /// Retrieves an E2M mapping by its ID.
159    ///
160    /// # Arguments
161    /// * `id` - The ID of the E2M mapping to get.
162    pub async fn get(&self, id: String) -> Result<GetE2mResponse> {
163        Ok(self
164            .service_client
165            .lock()
166            .await
167            .get_e2m(make_request_with_metadata(
168                GetE2mRequest { id: Some(id) },
169                &self.metadata_map,
170            ))
171            .await
172            .map_err(|status| SdkApiError {
173                status,
174                endpoint: "/com.coralogixapis.events2metrics.v2.Events2MetricService/GetE2M"
175                    .to_string(),
176                feature_group: EVENTS2METRICS_FEATURE_GROUP_ID.to_string(),
177            })?
178            .into_inner())
179    }
180
181    /// Retrieves the limits associated with this account.
182    ///
183    /// # Returns
184    /// The limits associated with this account.
185    pub async fn get_limits(&self) -> Result<GetLimitsResponse> {
186        Ok(self
187            .service_client
188            .lock()
189            .await
190            .get_limits(make_request_with_metadata(
191                GetLimitsRequest {},
192                &self.metadata_map,
193            ))
194            .await
195            .map_err(|status| SdkApiError {
196                status,
197                endpoint: "/com.coralogixapis.events2metrics.v2.Events2MetricService/GetLimits"
198                    .to_string(),
199                feature_group: EVENTS2METRICS_FEATURE_GROUP_ID.to_string(),
200            })?
201            .into_inner())
202    }
203
204    /// Lists all E2M mappings.
205    ///
206    /// # Returns
207    /// A list of all E2M mappings.
208    pub async fn list(&self) -> Result<ListE2mResponse> {
209        Ok(self
210            .service_client
211            .lock()
212            .await
213            .list_e2m(make_request_with_metadata(
214                ListE2mRequest {},
215                &self.metadata_map,
216            ))
217            .await
218            .map_err(|status| SdkApiError {
219                status,
220                endpoint: "/com.coralogixapis.events2metrics.v2.Events2MetricService/ListE2M"
221                    .to_string(),
222                feature_group: EVENTS2METRICS_FEATURE_GROUP_ID.to_string(),
223            })?
224            .into_inner())
225    }
226
227    /// Lists the cardinality of labels for a given metric.
228    ///
229    /// # Arguments
230    /// * `metric_labels` - The labels of the metric to list cardinality for.
231    /// * `query` - The query to filter the labels by.
232    pub async fn list_labels_cardinality(
233        &self,
234        metric_labels: Vec<MetricLabel>,
235        query: Query,
236    ) -> Result<ListLabelsCardinalityResponse> {
237        Ok(self
238            .service_client
239            .lock()
240            .await
241            .list_labels_cardinality(make_request_with_metadata(
242                ListLabelsCardinalityRequest {
243                    metric_labels,
244                    query: Some(query),
245                },
246                &self.metadata_map,
247            ))
248            .await
249            .map_err(|status| SdkApiError {
250                status,
251                endpoint: "/com.coralogixapis.events2metrics.v2.Events2MetricService/ListLabelsCardinality".to_string(),
252                feature_group: EVENTS2METRICS_FEATURE_GROUP_ID.to_string(),
253            })?
254            .into_inner())
255    }
256
257    // TODO: Expose the AtomicBatchExecuteE2m API where CRUD requests can be batched together.
258}