cx_sdk/client/
actions.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::{
16    collections::HashMap,
17    str::FromStr,
18};
19
20use crate::{
21    auth::AuthContext,
22    com::coralogixapis::actions::v2::{
23        CreateActionRequest,
24        CreateActionResponse,
25        DeleteActionRequest,
26        GetActionRequest,
27        ListActionsRequest,
28        OrderActionsRequest,
29        ReplaceActionRequest,
30        ReplaceActionResponse,
31        actions_service_client::ActionsServiceClient,
32    },
33    error::{
34        Result,
35        SdkApiError,
36    },
37    metadata::CallProperties,
38    util::make_request_with_metadata,
39};
40
41pub use crate::com::coralogixapis::actions::v2::{
42    Action,
43    SourceType,
44};
45
46use cx_api::proto::com::coralogixapis::actions::v2::DeleteActionResponse;
47use tokio::sync::Mutex;
48use tonic::{
49    metadata::MetadataMap,
50    transport::{
51        Channel,
52        ClientTlsConfig,
53        Endpoint,
54    },
55};
56
57use crate::CoralogixRegion;
58
59const ACTIONS_FEATURE_GROUP_ID: &str = "actions";
60
61/// The Actions API client.
62/// Read more at <https://coralogix.com/docs/coralogix-action-extension/>
63pub struct ActionsClient {
64    teams_level_metadata_map: MetadataMap,
65    service_client: Mutex<ActionsServiceClient<Channel>>,
66}
67
68impl ActionsClient {
69    /// Creates a new client for the Actions 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            teams_level_metadata_map: request_metadata.to_metadata_map(),
81            service_client: Mutex::new(ActionsServiceClient::new(channel)),
82        })
83    }
84
85    /// Creates a new Action
86    ///
87    /// # Arguments
88    /// * `action` - The [`Action`] to create.
89    pub async fn create(&self, action: Action) -> Result<CreateActionResponse> {
90        let request = make_request_with_metadata(
91            CreateActionRequest {
92                name: action.name,
93                url: action.url,
94                is_private: action.is_private,
95                source_type: action.source_type,
96                application_names: action.application_names,
97                subsystem_names: action.subsystem_names,
98            },
99            &self.teams_level_metadata_map,
100        );
101        //let client = self.service_client.lock().await.descri
102        Ok(self
103            .service_client
104            .lock()
105            .await
106            .create_action(request)
107            .await
108            .map_err(|status| SdkApiError {
109                status,
110                endpoint: "/com.coralogixapis.actions.v2.ActionsService/CreateAction".into(),
111                feature_group: ACTIONS_FEATURE_GROUP_ID.into(),
112            })?
113            .into_inner())
114    }
115
116    /// Replaces the existing [`Action`] identified by its id.
117    ///
118    /// # Arguments
119    /// * `action` - The action to replace.
120    pub async fn replace(&self, action: Action) -> Result<ReplaceActionResponse> {
121        let request = make_request_with_metadata(
122            ReplaceActionRequest {
123                action: Some(action),
124            },
125            &self.teams_level_metadata_map,
126        );
127        Ok(self
128            .service_client
129            .lock()
130            .await
131            .replace_action(request)
132            .await
133            .map_err(|status| SdkApiError {
134                status,
135                endpoint: "/com.coralogixapis.actions.v2.ActionsService/ReplaceAction".to_string(),
136                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
137            })?
138            .into_inner())
139    }
140
141    /// Deletes the [`Action`] identified by its id.
142    ///
143    /// # Arguments
144    /// * `action_id` - The id of the action to delete.
145    pub async fn delete(&self, action_id: String) -> Result<DeleteActionResponse> {
146        let request = make_request_with_metadata(
147            DeleteActionRequest {
148                id: Some(action_id),
149            },
150            &self.teams_level_metadata_map,
151        );
152        Ok(self
153            .service_client
154            .lock()
155            .await
156            .delete_action(request)
157            .await
158            .map_err(|status| SdkApiError {
159                status,
160                endpoint: "/com.coralogixapis.actions.v2.ActionsService/DeleteAction".to_string(),
161                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
162            })?
163            .into_inner())
164    }
165
166    /// Retrieves the [`Action`] by id.
167    ///
168    /// # Arguments
169    /// * `action_id` - The id of the action to retrieve.
170    pub async fn get(&self, action_id: String) -> Result<Option<Action>> {
171        let request = make_request_with_metadata(
172            GetActionRequest {
173                id: Some(action_id),
174            },
175            &self.teams_level_metadata_map,
176        );
177
178        Ok(self
179            .service_client
180            .lock()
181            .await
182            .get_action(request)
183            .await
184            .map_err(|status| SdkApiError {
185                status,
186                endpoint: "/com.coralogixapis.actions.v2.ActionsService/GetAction".to_string(),
187                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
188            })?
189            .into_inner()
190            .action)
191    }
192
193    /// Retrieves a list of all [`Action`]s.
194    ///     
195    /// # Returns
196    /// A list of all actions.
197    pub async fn list(&self) -> Result<Vec<Action>> {
198        let request =
199            make_request_with_metadata(ListActionsRequest {}, &self.teams_level_metadata_map);
200
201        Ok(self
202            .service_client
203            .lock()
204            .await
205            .list_actions(request)
206            .await
207            .map_err(|status| SdkApiError {
208                status,
209                endpoint: "/com.coralogixapis.actions.v2.ActionsService/ListActions".to_string(),
210                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
211            })?
212            .into_inner()
213            .actions)
214    }
215
216    /// Orders the actions.
217    ///
218    /// # Arguments
219    /// * `private_actions_order` - The order of the private actions.
220    /// * `shared_actions_order` - The order of the shared actions.
221    ///
222    pub async fn order_actions(
223        &self,
224        private_actions_order: HashMap<String, u32>,
225        shared_actions_order: HashMap<String, u32>,
226    ) -> Result<()> {
227        let request = make_request_with_metadata(
228            OrderActionsRequest {
229                private_actions_order,
230                shared_actions_order,
231            },
232            &self.teams_level_metadata_map,
233        );
234
235        self.service_client
236            .lock()
237            .await
238            .order_actions(request)
239            .await
240            .map_err(|status| SdkApiError {
241                status,
242                endpoint: "/com.coralogixapis.actions.v2.ActionsService/OrderActions".to_string(),
243                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
244            })?;
245        Ok(())
246    }
247}