cx_sdk/client/
archive_metrics.rs

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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// Copyright 2024 Coralogix Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use cx_api::proto::com::coralogix::metrics::metrics_configurator::{
    ConfigureTenantRequest,
    GetTenantConfigRequest,
    GetTenantConfigResponse,
    GetTenantConfigResponseV2,
    InternalUpdateRequest,
    ListHotStoreConfigsRequest,
    ListHotStoreConfigsResponse,
    ListTenantConfigsRequest,
    ListTenantConfigsResponse,
    MigrateTenantRequest,
    UpdateRequest,
    ValidateBucketRequest,
    metrics_configurator_public_service_client::MetricsConfiguratorPublicServiceClient,
    metrics_configurator_service_client::MetricsConfiguratorServiceClient,
};
use std::str::FromStr;
use tokio::sync::Mutex;
use tonic::{
    metadata::MetadataMap,
    transport::{
        Channel,
        ClientTlsConfig,
        Endpoint,
    },
};

use crate::{
    CoralogixRegion,
    auth::AuthContext,
    error::{
        Result,
        SdkApiError,
        SdkError,
    },
    metadata::CallProperties,
    util::make_request_with_metadata,
};

pub use cx_api::proto::com::coralogix::metrics::metrics_configurator::{
    RetentionPolicyRequest,
    S3Config,
    configure_tenant_request::StorageConfig,
    internal_update_request::StorageConfig as InternalStorageConfigUpdate,
    tenant_config::StorageConfig as InternalStorageConfig,
    tenant_config_v2::StorageConfig as StorageConfigView,
    update_request::StorageConfig as StorageConfigUpdate,
    validate_bucket_request::StorageConfig as StorageConfigValidation,
};

const ARCHIVE_METRICS_FEATURE_GROUP_ID: &str = "metrics";

/// The metrics archive API client.
/// Read more at [https://coralogix.com/docs/archive-s3-bucket-forever/]()
pub struct MetricsArchiveClient {
    metadata_map: MetadataMap,
    service_client: Mutex<MetricsConfiguratorPublicServiceClient<Channel>>,
}

impl MetricsArchiveClient {
    /// Creates a new client for the Metrics Archive API.
    ///
    /// # Arguments
    /// * `auth_context` - The  to use for authentication.
    /// * `region` - The region to connect to.
    pub fn new(region: CoralogixRegion, auth_context: AuthContext) -> Result<Self> {
        let channel: Channel = Endpoint::from_str(&region.grpc_endpoint())?
            .tls_config(ClientTlsConfig::new().with_native_roots())?
            .connect_lazy();
        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
        Ok(Self {
            metadata_map: request_metadata.to_metadata_map(),
            service_client: Mutex::new(MetricsConfiguratorPublicServiceClient::new(channel)),
        })
    }

    /// Configures the tenant.
    ///
    /// # Arguments
    /// * `retention_policy` - The retention policy to set.
    /// * `storage_config` - The storage configuration to set.
    pub async fn configure_tenant(
        &self,
        retention_policy: Option<RetentionPolicyRequest>,
        storage_config: StorageConfig,
    ) -> Result<()> {
        let request = make_request_with_metadata(
            ConfigureTenantRequest {
                retention_policy,
                storage_config: Some(storage_config),
            },
            &self.metadata_map,
        );
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .configure_tenant(request)
                .await
                .map(|_| ())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/ConfigureTenant".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }

    /// Updates the tenant configuration.
    ///
    /// # Arguments
    /// * `retention_days` - The retention days to set.
    /// * `storage_config` - The storage configuration to set.
    pub async fn update_tenant(
        &self,
        retention_days: u32,
        storage_config: StorageConfigUpdate,
    ) -> Result<()> {
        let request = make_request_with_metadata(
            UpdateRequest {
                retention_days: Some(retention_days),
                storage_config: Some(storage_config),
            },
            &self.metadata_map,
        );
        {
            let mut client = self.service_client.lock().await.clone();

            client.update(request).await.map(|_| ()).map_err(
                |status| SdkError::ApiError(SdkApiError {
                    status,
                    endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/Update".into(),
                    feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                },
            ))
        }
    }

    /// Validates a bucket configuration.
    ///
    /// # Arguments
    /// * `storage_config` - The storage configuration to validate.
    /// * `bucket_name` - The name of the bucket to validate.
    pub async fn validate_bucket(&self, storage_config: StorageConfigValidation) -> Result<()> {
        let request = make_request_with_metadata(
            ValidateBucketRequest {
                storage_config: Some(storage_config),
            },
            &self.metadata_map,
        );
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .validate_bucket(request)
                .await
                .map(|_| ())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/ValidateBucket".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }

    /// Gets the tenant configuration.
    pub async fn get_tenant_config(&self) -> Result<GetTenantConfigResponseV2> {
        let request = make_request_with_metadata((), &self.metadata_map);
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .get_tenant_config(request)
                .await
                .map(|response| response.into_inner())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/GetTenantConfig".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }

    /// Enables the archive.
    pub async fn enable_archive(&self) -> Result<()> {
        let request = make_request_with_metadata((), &self.metadata_map);
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .enable_archive(request)
                .await
                .map(|_| ())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/EnableArchive".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }

    /// Disables the archive.
    pub async fn disable_archive(&self) -> Result<()> {
        let request = make_request_with_metadata((), &self.metadata_map);
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .disable_archive(request)
                .await
                .map(|_| ())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorPublicService/DisableArchive".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }
}

/// A service client for the internal metrics archive API. It's only for Coralogix internal use.
pub struct MetricsArchiveInternalClient {
    metadata_map: MetadataMap,
    service_client: Mutex<MetricsConfiguratorServiceClient<Channel>>,
}

impl MetricsArchiveInternalClient {
    /// Creates a new client for the internal Metrics Archive API.
    ///
    /// # Arguments
    /// * `auth_context` - The  to use for authentication.
    /// * `region` - The region to connect to.
    pub fn new(region: CoralogixRegion, auth_context: AuthContext) -> Result<Self> {
        let channel: Channel = Endpoint::from_str(&region.grpc_endpoint())?
            .tls_config(ClientTlsConfig::new().with_native_roots())?
            .connect_lazy();
        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
        Ok(Self {
            metadata_map: request_metadata.to_metadata_map(),
            service_client: Mutex::new(MetricsConfiguratorServiceClient::new(channel)),
        })
    }

    /// Gets the tenant configuration.
    ///
    /// # Arguments
    /// * `tenant_id` - The ID of the tenant to get the configuration for.
    pub async fn get_tenant_config(&self, tenant_id: u32) -> Result<GetTenantConfigResponse> {
        let request =
            make_request_with_metadata(GetTenantConfigRequest { tenant_id }, &self.metadata_map);
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .get_tenant_config(request)
                .await
                .map(|response| response.into_inner())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/GetTenantConfig".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }

    /// Lists the tenant configurations.
    pub async fn list_tenant_configs(&self) -> Result<ListTenantConfigsResponse> {
        let request = make_request_with_metadata(ListTenantConfigsRequest {}, &self.metadata_map);
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .list_tenant_configs(request)
                .await
                .map(|response| response.into_inner())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/ListTenantConfigs".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }

    /// Lists the hot store configurations.
    pub async fn list_hot_store_configs(&self) -> Result<ListHotStoreConfigsResponse> {
        let request = make_request_with_metadata(ListHotStoreConfigsRequest {}, &self.metadata_map);
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .list_host_store_configs(request)
                .await
                .map(|r| r.into_inner())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/ListHotStoreConfigs".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }

    /// Migrates a tenant.
    ///
    /// # Arguments
    /// * `tenant_id` - The ID of the tenant to migrate.
    pub async fn migrate_tenant(&self, tenant_id: u32) -> Result<()> {
        let request =
            make_request_with_metadata(MigrateTenantRequest { tenant_id }, &self.metadata_map);
        {
            let mut client = self.service_client.lock().await.clone();

            client
                .migrate_tenant(request)
                .await
                .map(|_| ())
                .map_err(
                    |status| SdkError::ApiError(SdkApiError {
                        status,
                        endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/MigrateTenant".into(),
                        feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                    },
                ))
        }
    }

    /// Updates the tenant configuration.
    ///
    /// # Arguments
    /// * `tenant_id` - The ID of the tenant to update.
    pub async fn update(
        &self,
        tenant_id: u32,
        retention_days: u32,
        storage_config: InternalStorageConfigUpdate,
    ) -> Result<()> {
        let request = make_request_with_metadata(
            InternalUpdateRequest {
                retention_days: Some(retention_days),
                storage_config: Some(storage_config),
                tenant_id,
            },
            &self.metadata_map,
        );
        {
            let mut client = self.service_client.lock().await.clone();

            client.update(request).await.map(|_| ()).map_err(
                |status| SdkError::ApiError(SdkApiError {
                    status,
                    endpoint: "/com.coralogixapis.metrics.metrics_configurator.MetricsConfiguratorService/Update".into(),
                    feature_group: ARCHIVE_METRICS_FEATURE_GROUP_ID.into(),
                },
            ))
        }
    }
}