cx_sdk/client/
archive_metrics.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 cx_api::proto::com::coralogix::metrics::metrics_configurator::{
16    ConfigureTenantRequest,
17    GetTenantConfigRequest,
18    GetTenantConfigResponse,
19    GetTenantConfigResponseV2,
20    InternalUpdateRequest,
21    ListHotStoreConfigsRequest,
22    ListHotStoreConfigsResponse,
23    ListTenantConfigsRequest,
24    ListTenantConfigsResponse,
25    MigrateTenantRequest,
26    UpdateRequest,
27    ValidateBucketRequest,
28    metrics_configurator_public_service_client::MetricsConfiguratorPublicServiceClient,
29    metrics_configurator_service_client::MetricsConfiguratorServiceClient,
30};
31use std::str::FromStr;
32use tokio::sync::Mutex;
33use tonic::{
34    metadata::MetadataMap,
35    transport::{
36        Channel,
37        ClientTlsConfig,
38        Endpoint,
39    },
40};
41
42use crate::{
43    CoralogixRegion,
44    auth::AuthContext,
45    error::{
46        Result,
47        SdkApiError,
48        SdkError,
49    },
50    metadata::CallProperties,
51    util::make_request_with_metadata,
52};
53
54pub use cx_api::proto::com::coralogix::metrics::metrics_configurator::{
55    RetentionPolicyRequest,
56    S3Config,
57    configure_tenant_request::StorageConfig,
58    internal_update_request::StorageConfig as InternalStorageConfigUpdate,
59    tenant_config::StorageConfig as InternalStorageConfig,
60    tenant_config_v2::StorageConfig as StorageConfigView,
61    update_request::StorageConfig as StorageConfigUpdate,
62    validate_bucket_request::StorageConfig as StorageConfigValidation,
63};
64
65const ARCHIVE_METRICS_FEATURE_GROUP_ID: &str = "metrics";
66
67/// The metrics archive API client.
68/// Read more at [https://coralogix.com/docs/archive-s3-bucket-forever/]()
69pub struct MetricsArchiveClient {
70    metadata_map: MetadataMap,
71    service_client: Mutex<MetricsConfiguratorPublicServiceClient<Channel>>,
72}
73
74impl MetricsArchiveClient {
75    /// Creates a new client for the Metrics Archive API.
76    ///
77    /// # Arguments
78    /// * `auth_context` - The  to use for authentication.
79    /// * `region` - The region to connect to.
80    pub fn new(region: CoralogixRegion, auth_context: AuthContext) -> Result<Self> {
81        let channel: Channel = Endpoint::from_str(&region.grpc_endpoint())?
82            .tls_config(ClientTlsConfig::new().with_native_roots())?
83            .connect_lazy();
84        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
85        Ok(Self {
86            metadata_map: request_metadata.to_metadata_map(),
87            service_client: Mutex::new(MetricsConfiguratorPublicServiceClient::new(channel)),
88        })
89    }
90
91    /// Configures the tenant.
92    ///
93    /// # Arguments
94    /// * `retention_policy` - The retention policy to set.
95    /// * `storage_config` - The storage configuration to set.
96    pub async fn configure_tenant(
97        &self,
98        retention_policy: Option<RetentionPolicyRequest>,
99        storage_config: StorageConfig,
100    ) -> Result<()> {
101        let request = make_request_with_metadata(
102            ConfigureTenantRequest {
103                retention_policy,
104                storage_config: Some(storage_config),
105            },
106            &self.metadata_map,
107        );
108        {
109            let mut client = self.service_client.lock().await.clone();
110
111            client
112                .configure_tenant(request)
113                .await
114                .map(|_| ())
115                .map_err(
116                    |status| SdkError::ApiError(SdkApiError {
117                        status,
118                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/ConfigureTenant".into(),
119                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
120                    },
121                ))
122        }
123    }
124
125    /// Updates the tenant configuration.
126    ///
127    /// # Arguments
128    /// * `retention_days` - The retention days to set.
129    /// * `storage_config` - The storage configuration to set.
130    pub async fn update_tenant(
131        &self,
132        retention_days: u32,
133        storage_config: StorageConfigUpdate,
134    ) -> Result<()> {
135        let request = make_request_with_metadata(
136            UpdateRequest {
137                retention_days: Some(retention_days),
138                storage_config: Some(storage_config),
139            },
140            &self.metadata_map,
141        );
142        {
143            let mut client = self.service_client.lock().await.clone();
144
145            client.update(request).await.map(|_| ()).map_err(
146                |status| SdkError::ApiError(SdkApiError {
147                    status,
148                    endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/Update".into(),
149                    feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
150                },
151            ))
152        }
153    }
154
155    /// Validates a bucket configuration.
156    ///
157    /// # Arguments
158    /// * `storage_config` - The storage configuration to validate.
159    /// * `bucket_name` - The name of the bucket to validate.
160    pub async fn validate_bucket(&self, storage_config: StorageConfigValidation) -> Result<()> {
161        let request = make_request_with_metadata(
162            ValidateBucketRequest {
163                storage_config: Some(storage_config),
164            },
165            &self.metadata_map,
166        );
167        {
168            let mut client = self.service_client.lock().await.clone();
169
170            client
171                .validate_bucket(request)
172                .await
173                .map(|_| ())
174                .map_err(
175                    |status| SdkError::ApiError(SdkApiError {
176                        status,
177                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/ValidateBucket".into(),
178                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
179                    },
180                ))
181        }
182    }
183
184    /// Gets the tenant configuration.
185    pub async fn get_tenant_config(&self) -> Result<GetTenantConfigResponseV2> {
186        let request = make_request_with_metadata((), &self.metadata_map);
187        {
188            let mut client = self.service_client.lock().await.clone();
189
190            client
191                .get_tenant_config(request)
192                .await
193                .map(|response| response.into_inner())
194                .map_err(
195                    |status| SdkError::ApiError(SdkApiError {
196                        status,
197                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/GetTenantConfig".into(),
198                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
199                    },
200                ))
201        }
202    }
203
204    /// Enables the archive.
205    pub async fn enable_archive(&self) -> Result<()> {
206        let request = make_request_with_metadata((), &self.metadata_map);
207        {
208            let mut client = self.service_client.lock().await.clone();
209
210            client
211                .enable_archive(request)
212                .await
213                .map(|_| ())
214                .map_err(
215                    |status| SdkError::ApiError(SdkApiError {
216                        status,
217                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/EnableArchive".into(),
218                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
219                    },
220                ))
221        }
222    }
223
224    /// Disables the archive.
225    pub async fn disable_archive(&self) -> Result<()> {
226        let request = make_request_with_metadata((), &self.metadata_map);
227        {
228            let mut client = self.service_client.lock().await.clone();
229
230            client
231                .disable_archive(request)
232                .await
233                .map(|_| ())
234                .map_err(
235                    |status| SdkError::ApiError(SdkApiError {
236                        status,
237                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/DisableArchive".into(),
238                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
239                    },
240                ))
241        }
242    }
243}
244
245/// A service client for the internal metrics archive API. It's only for Coralogix internal use.
246pub struct MetricsArchiveInternalClient {
247    metadata_map: MetadataMap,
248    service_client: Mutex<MetricsConfiguratorServiceClient<Channel>>,
249}
250
251impl MetricsArchiveInternalClient {
252    /// Creates a new client for the internal Metrics Archive API.
253    ///
254    /// # Arguments
255    /// * `auth_context` - The  to use for authentication.
256    /// * `region` - The region to connect to.
257    pub fn new(region: CoralogixRegion, auth_context: AuthContext) -> Result<Self> {
258        let channel: Channel = Endpoint::from_str(&region.grpc_endpoint())?
259            .tls_config(ClientTlsConfig::new().with_native_roots())?
260            .connect_lazy();
261        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
262        Ok(Self {
263            metadata_map: request_metadata.to_metadata_map(),
264            service_client: Mutex::new(MetricsConfiguratorServiceClient::new(channel)),
265        })
266    }
267
268    /// Gets the tenant configuration.
269    ///
270    /// # Arguments
271    /// * `tenant_id` - The ID of the tenant to get the configuration for.
272    pub async fn get_tenant_config(&self, tenant_id: u32) -> Result<GetTenantConfigResponse> {
273        let request =
274            make_request_with_metadata(GetTenantConfigRequest { tenant_id }, &self.metadata_map);
275        {
276            let mut client = self.service_client.lock().await.clone();
277
278            client
279                .get_tenant_config(request)
280                .await
281                .map(|response| response.into_inner())
282                .map_err(
283                    |status| SdkError::ApiError(SdkApiError {
284                        status,
285                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/GetTenantConfig".into(),
286                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
287                    },
288                ))
289        }
290    }
291
292    /// Lists the tenant configurations.
293    pub async fn list_tenant_configs(&self) -> Result<ListTenantConfigsResponse> {
294        let request = make_request_with_metadata(ListTenantConfigsRequest {}, &self.metadata_map);
295        {
296            let mut client = self.service_client.lock().await.clone();
297
298            client
299                .list_tenant_configs(request)
300                .await
301                .map(|response| response.into_inner())
302                .map_err(
303                    |status| SdkError::ApiError(SdkApiError {
304                        status,
305                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/ListTenantConfigs".into(),
306                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
307                    },
308                ))
309        }
310    }
311
312    /// Lists the hot store configurations.
313    pub async fn list_hot_store_configs(&self) -> Result<ListHotStoreConfigsResponse> {
314        let request = make_request_with_metadata(ListHotStoreConfigsRequest {}, &self.metadata_map);
315        {
316            let mut client = self.service_client.lock().await.clone();
317
318            client
319                .list_host_store_configs(request)
320                .await
321                .map(|r| r.into_inner())
322                .map_err(
323                    |status| SdkError::ApiError(SdkApiError {
324                        status,
325                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/ListHotStoreConfigs".into(),
326                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
327                    },
328                ))
329        }
330    }
331
332    /// Migrates a tenant.
333    ///
334    /// # Arguments
335    /// * `tenant_id` - The ID of the tenant to migrate.
336    pub async fn migrate_tenant(&self, tenant_id: u32) -> Result<()> {
337        let request =
338            make_request_with_metadata(MigrateTenantRequest { tenant_id }, &self.metadata_map);
339        {
340            let mut client = self.service_client.lock().await.clone();
341
342            client
343                .migrate_tenant(request)
344                .await
345                .map(|_| ())
346                .map_err(
347                    |status| SdkError::ApiError(SdkApiError {
348                        status,
349                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/MigrateTenant".into(),
350                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
351                    },
352                ))
353        }
354    }
355
356    /// Updates the tenant configuration.
357    ///
358    /// # Arguments
359    /// * `tenant_id` - The ID of the tenant to update.
360    pub async fn update(
361        &self,
362        tenant_id: u32,
363        retention_days: u32,
364        storage_config: InternalStorageConfigUpdate,
365    ) -> Result<()> {
366        let request = make_request_with_metadata(
367            InternalUpdateRequest {
368                retention_days: Some(retention_days),
369                storage_config: Some(storage_config),
370                tenant_id,
371            },
372            &self.metadata_map,
373        );
374        {
375            let mut client = self.service_client.lock().await.clone();
376
377            client.update(request).await.map(|_| ()).map_err(
378                |status| SdkError::ApiError(SdkApiError {
379                    status,
380                    endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/Update".into(),
381                    feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
382                },
383            ))
384        }
385    }
386}