cx_sdk/client/
recording_rule_group_sets.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.
14use std::str::FromStr;
15
16pub use cx_api::proto::com::coralogixapis::metrics_rule_manager::v1::{
17    CreateRuleGroupSet,
18    CreateRuleGroupSetResult,
19    DeleteRuleGroupSet,
20    FetchRuleGroupResult,
21    FetchRuleGroupSet,
22    InRule,
23    InRuleGroup,
24    OutRuleGroupSet,
25    RuleGroupSetListing,
26    UpdateRuleGroupSet,
27};
28use tokio::sync::Mutex;
29use tonic::{
30    metadata::MetadataMap,
31    transport::{
32        Channel,
33        ClientTlsConfig,
34        Endpoint,
35    },
36};
37
38use crate::{
39    CoralogixRegion,
40    auth::AuthContext,
41    error::{
42        Result,
43        SdkApiError,
44        SdkError,
45    },
46    metadata::CallProperties,
47    util::make_request_with_metadata,
48};
49
50const RECORDING_RULES_FEATURE_GROUP_ID: &str = "recording-rules";
51
52use cx_api::proto::com::coralogixapis::metrics_rule_manager::v1::rule_group_sets_client::RuleGroupSetsClient;
53
54/// A client for the recording rule group sets service.
55pub struct RecordingRuleGroupSetsClient {
56    service_client: Mutex<RuleGroupSetsClient<Channel>>,
57    metadata_map: MetadataMap,
58}
59
60impl RecordingRuleGroupSetsClient {
61    /// Creates a new GroupsClient.
62    ///
63    /// # Arguments
64    /// * `auth_context` - The [`AuthContext`] to use for authentication.
65    /// * `region` - The [`CoralogixRegion`] to connect to.
66    pub fn new(auth_context: AuthContext, region: CoralogixRegion) -> Result<Self> {
67        let channel: Channel = Endpoint::from_str(region.grpc_endpoint().as_str())?
68            .tls_config(ClientTlsConfig::new().with_native_roots())?
69            .connect_lazy();
70        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
71        Ok(Self {
72            metadata_map: request_metadata.to_metadata_map(),
73            service_client: Mutex::new(RuleGroupSetsClient::new(channel)),
74        })
75    }
76
77    #[allow(clippy::too_many_arguments)]
78    /// Creates a new group.
79    ///
80    /// # Arguments
81    /// * `name` - The name of the group.
82    /// * `groups` - The [`InRuleGroup`]s to create.
83    pub async fn create(
84        &self,
85        name: String,
86        groups: Vec<InRuleGroup>,
87    ) -> Result<CreateRuleGroupSetResult> {
88        let request = make_request_with_metadata(
89            CreateRuleGroupSet {
90                name: Some(name),
91                groups,
92            },
93            &self.metadata_map,
94        );
95        Ok(self
96            .service_client
97            .lock()
98            .await
99            .create(request)
100            .await
101            .map_err(|status| {
102                SdkError::ApiError(SdkApiError {
103                    status,
104                    endpoint: "/com.coralogixapis.metrics_rule_manager.v1.RuleGroupSets/Create"
105                        .to_string(),
106                    feature_group: RECORDING_RULES_FEATURE_GROUP_ID.to_string(),
107                })
108            })?
109            .into_inner())
110    }
111
112    /// Fetches a recording rule group set by id.
113    ///
114    /// # Arguments
115    /// * `group_id` - The id of the recording rule group set to fetch.
116    pub async fn get(&self, id: String) -> Result<OutRuleGroupSet> {
117        let request = make_request_with_metadata(FetchRuleGroupSet { id }, &self.metadata_map);
118        Ok(self
119            .service_client
120            .lock()
121            .await
122            .fetch(request)
123            .await
124            .map_err(|status| {
125                SdkError::ApiError(SdkApiError {
126                    status,
127                    endpoint: "/com.coralogixapis.metrics_rule_manager.v1.RuleGroupSets/Fetch"
128                        .to_string(),
129                    feature_group: RECORDING_RULES_FEATURE_GROUP_ID.to_string(),
130                })
131            })?
132            .into_inner())
133    }
134
135    /// Fetches all recording rule group sets.
136    pub async fn list(&self) -> Result<RuleGroupSetListing> {
137        let request = make_request_with_metadata((), &self.metadata_map);
138        Ok(self
139            .service_client
140            .lock()
141            .await
142            .list(request)
143            .await
144            .map_err(|status| {
145                SdkError::ApiError(SdkApiError {
146                    status,
147                    endpoint: "/com.coralogixapis.metrics_rule_manager.v1.RuleGroupSets/List"
148                        .to_string(),
149                    feature_group: RECORDING_RULES_FEATURE_GROUP_ID.to_string(),
150                })
151            })?
152            .into_inner())
153    }
154
155    /// Updates a group.
156    /// * `id` - The id of the rule group set to update.
157    /// * `groups` - The [`InRuleGroup`]s to update.
158    /// * `name` - The optional name for the rule groups.
159    pub async fn update(
160        &self,
161        id: String,
162        groups: Vec<InRuleGroup>,
163        name: Option<String>,
164    ) -> Result<()> {
165        let request =
166            make_request_with_metadata(UpdateRuleGroupSet { id, groups, name }, &self.metadata_map);
167        self.service_client
168            .lock()
169            .await
170            .update(request)
171            .await
172            .map_err(|status| {
173                SdkError::ApiError(SdkApiError {
174                    status,
175                    endpoint: "/com.coralogixapis.metrics_rule_manager.v1.RuleGroupSets/Update"
176                        .to_string(),
177                    feature_group: RECORDING_RULES_FEATURE_GROUP_ID.to_string(),
178                })
179            })?;
180        Ok(())
181    }
182
183    /// Deletes a group.
184    ///
185    /// # Arguments
186    /// * `id` - The id of the recording rule group set to delete.
187    pub async fn delete(&self, id: String) -> Result<()> {
188        let request = make_request_with_metadata(DeleteRuleGroupSet { id }, &self.metadata_map);
189        self.service_client
190            .lock()
191            .await
192            .delete(request)
193            .await
194            .map_err(|status| {
195                SdkError::ApiError(SdkApiError {
196                    status,
197                    endpoint: "/com.coralogixapis.metrics_rule_manager.v1.RuleGroupSets/Delete"
198                        .to_string(),
199                    feature_group: RECORDING_RULES_FEATURE_GROUP_ID.to_string(),
200                })
201            })?;
202        Ok(())
203    }
204}