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        Ok(self
102            .service_client
103            .lock()
104            .await
105            .create_action(request)
106            .await
107            .map_err(|status| SdkApiError {
108                status,
109                endpoint: "/com.coralogixapis.actions.v2.ActionsService/CreateAction".into(),
110                feature_group: ACTIONS_FEATURE_GROUP_ID.into(),
111            })?
112            .into_inner())
113    }
114
115    /// Replaces the existing [`Action`] identified by its id.
116    ///
117    /// # Arguments
118    /// * `action` - The action to replace.
119    pub async fn replace(&self, action: Action) -> Result<ReplaceActionResponse> {
120        let request = make_request_with_metadata(
121            ReplaceActionRequest {
122                action: Some(action),
123            },
124            &self.teams_level_metadata_map,
125        );
126        Ok(self
127            .service_client
128            .lock()
129            .await
130            .replace_action(request)
131            .await
132            .map_err(|status| SdkApiError {
133                status,
134                endpoint: "/com.coralogixapis.actions.v2.ActionsService/ReplaceAction".to_string(),
135                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
136            })?
137            .into_inner())
138    }
139
140    /// Deletes the [`Action`] identified by its id.
141    ///
142    /// # Arguments
143    /// * `action_id` - The id of the action to delete.
144    pub async fn delete(&self, action_id: String) -> Result<DeleteActionResponse> {
145        let request = make_request_with_metadata(
146            DeleteActionRequest {
147                id: Some(action_id),
148            },
149            &self.teams_level_metadata_map,
150        );
151        Ok(self
152            .service_client
153            .lock()
154            .await
155            .delete_action(request)
156            .await
157            .map_err(|status| SdkApiError {
158                status,
159                endpoint: "/com.coralogixapis.actions.v2.ActionsService/DeleteAction".to_string(),
160                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
161            })?
162            .into_inner())
163    }
164
165    /// Retrieves the [`Action`] by id.
166    ///
167    /// # Arguments
168    /// * `action_id` - The id of the action to retrieve.
169    pub async fn get(&self, action_id: String) -> Result<Option<Action>> {
170        let request = make_request_with_metadata(
171            GetActionRequest {
172                id: Some(action_id),
173            },
174            &self.teams_level_metadata_map,
175        );
176
177        Ok(self
178            .service_client
179            .lock()
180            .await
181            .get_action(request)
182            .await
183            .map_err(|status| SdkApiError {
184                status,
185                endpoint: "/com.coralogixapis.actions.v2.ActionsService/GetAction".to_string(),
186                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
187            })?
188            .into_inner()
189            .action)
190    }
191
192    /// Retrieves a list of all [`Action`]s.
193    ///     
194    /// # Returns
195    /// A list of all actions.
196    pub async fn list(&self) -> Result<Vec<Action>> {
197        let request =
198            make_request_with_metadata(ListActionsRequest {}, &self.teams_level_metadata_map);
199
200        Ok(self
201            .service_client
202            .lock()
203            .await
204            .list_actions(request)
205            .await
206            .map_err(|status| SdkApiError {
207                status,
208                endpoint: "/com.coralogixapis.actions.v2.ActionsService/ListActions".to_string(),
209                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
210            })?
211            .into_inner()
212            .actions)
213    }
214
215    /// Orders the actions.
216    ///
217    /// # Arguments
218    /// * `private_actions_order` - The order of the private actions.
219    /// * `shared_actions_order` - The order of the shared actions.
220    ///
221    pub async fn order_actions(
222        &self,
223        private_actions_order: HashMap<String, u32>,
224        shared_actions_order: HashMap<String, u32>,
225    ) -> Result<()> {
226        let request = make_request_with_metadata(
227            OrderActionsRequest {
228                private_actions_order,
229                shared_actions_order,
230            },
231            &self.teams_level_metadata_map,
232        );
233
234        self.service_client
235            .lock()
236            .await
237            .order_actions(request)
238            .await
239            .map_err(|status| SdkApiError {
240                status,
241                endpoint: "/com.coralogixapis.actions.v2.ActionsService/OrderActions".to_string(),
242                feature_group: ACTIONS_FEATURE_GROUP_ID.to_string(),
243            })?;
244        Ok(())
245    }
246}