cx_sdk/client/
scopes.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 cx_api::proto::com::coralogixapis::scopes::v1::{
29    EntityType,
30    Filter,
31};
32
33use cx_api::proto::com::coralogixapis::scopes::v1::{
34    CreateScopeRequest,
35    CreateScopeResponse,
36    DeleteScopeRequest,
37    DeleteScopeResponse,
38    GetScopesResponse,
39    GetTeamScopesByIdsRequest,
40    GetTeamScopesRequest,
41    UpdateScopeRequest,
42    UpdateScopeResponse,
43    scopes_service_client::ScopesServiceClient,
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
57const SCOPES_FEATURE_GROUP_ID: &str = "aaa";
58
59/// The Scopes Service client.
60/// Read more at <https://coralogix.com/docs/scopes/>
61pub struct ScopesClient {
62    metadata_map: MetadataMap,
63    service_client: Mutex<ScopesServiceClient<Channel>>,
64}
65
66impl ScopesClient {
67    /// Creates a new client for the SLO.
68    ///
69    /// # Arguments
70    /// * `auth_context` - The [`AuthContext`] to use for authentication.
71    /// * `region` - The [`CoralogixRegion`] to connect to.
72    pub fn new(auth_context: AuthContext, region: CoralogixRegion) -> Result<Self> {
73        let channel: Channel = Endpoint::from_str(region.grpc_endpoint().as_str())?
74            .tls_config(ClientTlsConfig::new().with_native_roots())?
75            .connect_lazy();
76        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
77        Ok(Self {
78            metadata_map: request_metadata.to_metadata_map(),
79            service_client: Mutex::new(ScopesServiceClient::new(channel)),
80        })
81    }
82
83    /// Create a new Scope.
84    ///
85    /// # Arguments
86    /// * `display_name` - The display name of the Scope.
87    /// * `description` - The description of the Scope.
88    /// * `filters` - The filters of the Scope.
89    /// * `default_expression` - The default expression of the Scope.
90    pub async fn create(
91        &self,
92        display_name: String,
93        description: Option<String>,
94        filters: Vec<Filter>,
95        default_expression: String,
96    ) -> Result<CreateScopeResponse> {
97        Ok(self
98            .service_client
99            .lock()
100            .await
101            .create_scope(make_request_with_metadata(
102                CreateScopeRequest {
103                    display_name,
104                    description,
105                    filters,
106                    default_expression,
107                },
108                &self.metadata_map,
109            ))
110            .await
111            .map_err(|status| {
112                SdkError::ApiError(SdkApiError {
113                    status,
114                    endpoint: "/com.coralogixapis.scopes.v1.ScopesService/CreateScope".to_string(),
115                    feature_group: SCOPES_FEATURE_GROUP_ID.into(),
116                })
117            })?
118            .into_inner())
119    }
120
121    /// Update a Scope.
122    ///
123    /// # Arguments
124    /// * `id` - The ID of the Scope to update.
125    /// * `display_name` - The display name of the Scope.
126    /// * `description` - The description of the Scope.
127    /// * `filters` - The filters of the Scope.
128    /// * `default_expression` - The default expression of the Scope.
129    pub async fn update(
130        &self,
131        id: String,
132        display_name: String,
133        description: Option<String>,
134        filters: Vec<Filter>,
135        default_expression: String,
136    ) -> Result<UpdateScopeResponse> {
137        Ok(self
138            .service_client
139            .lock()
140            .await
141            .update_scope(make_request_with_metadata(
142                UpdateScopeRequest {
143                    id,
144                    display_name,
145                    description,
146                    filters,
147                    default_expression,
148                },
149                &self.metadata_map,
150            ))
151            .await
152            .map_err(|status| {
153                SdkError::ApiError(SdkApiError {
154                    status,
155                    endpoint: "/com.coralogixapis.scopes.v1.ScopesService/UpdateScope".to_string(),
156                    feature_group: SCOPES_FEATURE_GROUP_ID.into(),
157                })
158            })?
159            .into_inner())
160    }
161
162    /// Delete a Scope by its ID.
163    ///
164    /// # Arguments
165    /// * `id` - The ID of the Scope to delete.
166    pub async fn delete(&self, id: String) -> Result<DeleteScopeResponse> {
167        Ok(self
168            .service_client
169            .lock()
170            .await
171            .delete_scope(make_request_with_metadata(
172                DeleteScopeRequest { id },
173                &self.metadata_map,
174            ))
175            .await
176            .map_err(|status| {
177                SdkError::ApiError(SdkApiError {
178                    status,
179                    endpoint: "/com.coralogixapis.scopes.v1.ScopesService/DeleteScope".to_string(),
180                    feature_group: SCOPES_FEATURE_GROUP_ID.into(),
181                })
182            })?
183            .into_inner())
184    }
185
186    /// Get a list of Scopes for your team by their IDs.
187    ///
188    /// # Arguments
189    /// * `ids` - The IDs of the Scopes to get.
190    pub async fn get(&self, ids: Vec<String>) -> Result<GetScopesResponse> {
191        Ok(self
192            .service_client
193            .lock()
194            .await
195            .get_team_scopes_by_ids(make_request_with_metadata(
196                GetTeamScopesByIdsRequest { ids },
197                &self.metadata_map,
198            ))
199            .await
200            .map_err(|status| {
201                SdkError::ApiError(SdkApiError {
202                    status,
203                    endpoint: "/com.coralogixapis.scopes.v1.ScopesService/GetTeamScopesByIds"
204                        .to_string(),
205                    feature_group: SCOPES_FEATURE_GROUP_ID.into(),
206                })
207            })?
208            .into_inner())
209    }
210
211    /// Get a list of all Scopes for your team.
212    pub async fn list(&self) -> Result<GetScopesResponse> {
213        Ok(self
214            .service_client
215            .lock()
216            .await
217            .get_team_scopes(make_request_with_metadata(
218                GetTeamScopesRequest {},
219                &self.metadata_map,
220            ))
221            .await
222            .map_err(|status| {
223                SdkError::ApiError(SdkApiError {
224                    status,
225                    endpoint: "/com.coralogixapis.scopes.v1.ScopesService/GetTeamScopes"
226                        .to_string(),
227                    feature_group: SCOPES_FEATURE_GROUP_ID.into(),
228                })
229            })?
230            .into_inner())
231    }
232}