cx_sdk/client/
datasets.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        SdkError,
23    },
24    metadata::CallProperties,
25    util::make_request_with_metadata,
26};
27
28pub use crate::com::coralogixapis::actions::v2::Action;
29
30use cx_api::proto::com::coralogix::enrichment::v1::{
31    CreateCustomEnrichmentRequest,
32    CreateCustomEnrichmentResponse,
33    DeleteCustomEnrichmentRequest,
34    DeleteCustomEnrichmentResponse,
35    File,
36    GetCustomEnrichmentRequest,
37    GetCustomEnrichmentResponse,
38    GetCustomEnrichmentsRequest,
39    GetCustomEnrichmentsResponse,
40    UpdateCustomEnrichmentRequest,
41    UpdateCustomEnrichmentResponse,
42    custom_enrichment_service_client::CustomEnrichmentServiceClient,
43    file::Content,
44};
45use tokio::sync::Mutex;
46use tonic::{
47    metadata::MetadataMap,
48    transport::{
49        Channel,
50        ClientTlsConfig,
51        Endpoint,
52    },
53};
54
55use crate::CoralogixRegion;
56
57pub use crate::com::coralogix::enrichment::v1::CustomEnrichment;
58
59const DATASETS_FEATURE_GROUP_ID: &str = "logs";
60
61/// The Custom Enrichments API client.
62/// Read more at <https://coralogix.com/docs/custom-enrichment-api/>
63pub struct DatasetClient {
64    metadata_map: MetadataMap,
65    service_client: Mutex<CustomEnrichmentServiceClient<Channel>>,
66}
67
68impl DatasetClient {
69    /// Creates a new client for the Custom Enrichments API.
70    ///
71    /// # Arguments
72    /// * `auth_context` - The [`AuthContext`] to use for authentication.
73    /// * `region` - The [`CoralogixRegion`] to connect to.
74    pub fn new(auth_context: AuthContext, region: CoralogixRegion) -> Result<Self> {
75        let channel: Channel = Endpoint::from_str(region.grpc_endpoint().as_str())?
76            .tls_config(ClientTlsConfig::new().with_native_roots())?
77            .connect_lazy();
78        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
79        Ok(Self {
80            metadata_map: request_metadata.to_metadata_map(),
81            service_client: Mutex::new(CustomEnrichmentServiceClient::new(channel)),
82        })
83    }
84
85    /// Creates a new dataset.
86    ///
87    /// # Arguments
88    /// * `name` - The name of the Custom Enrichment.
89    /// * `description` - The description of the Custom Enrichment.
90    /// * `data` - The data of the Custom Enrichment.
91    pub async fn create(
92        &self,
93        name: String,
94        description: Option<String>,
95        data: Vec<u8>,
96    ) -> Result<CreateCustomEnrichmentResponse> {
97        let file = File {
98            name: Some(name.clone()),
99            size: Some(data.len() as u32),
100            content: Some(Content::Binary(data)),
101            extension: Some("csv".into()),
102        };
103        let request = make_request_with_metadata(
104            CreateCustomEnrichmentRequest {
105                file: Some(file),
106                name: Some(name.clone()),
107                description,
108            },
109            &self.metadata_map,
110        );
111        {
112            Ok(self
113                .service_client
114                .lock()
115                .await
116                .create_custom_enrichment(request)
117                .await
118                .map_err(
119                    |status| SdkError::ApiError(SdkApiError {
120                        status,
121                        endpoint: "/com.coralogixapis.enrichment.v1.CustomEnrichmentService/CreateCustomEnrichment".into(),
122                        feature_group: DATASETS_FEATURE_GROUP_ID.into(),
123                    }),
124                )?
125                .into_inner())
126        }
127    }
128
129    /// Replaces the existing dataset identified by its id.
130    ///
131    /// # Arguments
132    /// * `id` - The id of the Custom Enrichment.
133    /// * `name` - The name of the Custom Enrichment.
134    /// * `description` - The description of the Custom Enrichment.
135    /// * `data` - The data of the Custom Enrichment.
136    ///
137    /// Note that the existing dataset will be replaced with a new version of the data.
138    pub async fn replace(
139        &self,
140        id: u32,
141        name: String,
142        description: Option<String>,
143        data: Vec<u8>,
144    ) -> Result<UpdateCustomEnrichmentResponse> {
145        let file = File {
146            name: Some(name.clone()),
147            size: Some(data.len() as u32),
148            content: Some(Content::Binary(data)),
149            extension: Some("csv".into()),
150        };
151        let request = make_request_with_metadata(
152            UpdateCustomEnrichmentRequest {
153                custom_enrichment_id: Some(id),
154                file: Some(file),
155                name: Some(name.clone()),
156                description,
157            },
158            &self.metadata_map,
159        );
160        {
161            Ok(self
162                .service_client
163                .lock()
164                .await
165                .update_custom_enrichment(request)
166                .await
167                .map_err(
168                    |status| SdkError::ApiError(SdkApiError {
169                        status,
170                        endpoint: "/com.coralogixapis.enrichment.v1.CustomEnrichmentService/UpdateCustomEnrichment".into(),
171                        feature_group: DATASETS_FEATURE_GROUP_ID.into(),
172                    }),
173                )?
174                .into_inner())
175        }
176    }
177
178    /// Deletes the dataset identified by its id.
179    ///
180    /// # Arguments
181    /// * `custom_enrichment_id` - The id of the Custom Enrichment.
182    pub async fn delete(
183        &self,
184        custom_enrichment_id: u32,
185    ) -> Result<DeleteCustomEnrichmentResponse> {
186        Ok(self
187            .service_client
188            .lock()
189            .await
190            .delete_custom_enrichment(make_request_with_metadata(
191                DeleteCustomEnrichmentRequest {
192                    custom_enrichment_id: Some(custom_enrichment_id),
193                },
194                &self.metadata_map,
195            ))
196            .await
197            .map_err(
198                |status| SdkError::ApiError(SdkApiError {
199                    status,
200                    endpoint: "/com.coralogixapis.enrichment.v1.CustomEnrichmentService/DeleteCustomEnrichment".into(),
201                    feature_group: DATASETS_FEATURE_GROUP_ID.into(),
202                }),
203            )?
204            .into_inner())
205    }
206
207    /// Retrieves the dataset by id.
208    ///
209    /// # Arguments
210    /// * `id` - The id of the Custom Enrichment.
211    pub async fn get(&self, id: u32) -> Result<GetCustomEnrichmentResponse> {
212        Ok(self
213            .service_client
214            .lock()
215            .await
216            .get_custom_enrichment(make_request_with_metadata(
217                GetCustomEnrichmentRequest { id: Some(id) },
218                &self.metadata_map,
219            ))
220            .await
221            .map_err(
222                |status| SdkError::ApiError(SdkApiError {
223                    status,
224                    endpoint: "/com.coralogixapis.enrichment.v1.CustomEnrichmentService/GetCustomEnrichment".into(),
225                    feature_group: DATASETS_FEATURE_GROUP_ID.into(),
226                }),
227            )?
228            .into_inner())
229    }
230
231    /// Retrieves all datasets.
232    ///
233    /// # Returns
234    /// A list of all Custom Enrichments.
235    pub async fn list(&self) -> Result<GetCustomEnrichmentsResponse> {
236        Ok(self
237            .service_client
238            .lock()
239            .await
240            .get_custom_enrichments(make_request_with_metadata(
241                GetCustomEnrichmentsRequest {},
242                &self.metadata_map,
243            ))
244            .await
245            .map_err(
246                |status| SdkError::ApiError(SdkApiError {
247                    status,
248                    endpoint: "/com.coralogixapis.enrichment.v1.CustomEnrichmentService/GetCustomEnrichments".into(),
249                    feature_group: DATASETS_FEATURE_GROUP_ID.into(),
250                }),
251            )?
252            .into_inner())
253    }
254}