cx_sdk/client/
events.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 tokio::sync::Mutex;
18use tonic::transport::{
19    Channel,
20    ClientTlsConfig,
21    Endpoint,
22};
23
24use cx_api::proto::com::coralogixapis::events::v3::{
25    BatchGetEventRequest,
26    BatchGetEventResponse,
27    GetEventRequest,
28    GetEventResponse,
29    GetEventsStatisticsRequest,
30    GetEventsStatisticsResponse,
31    ListEventsCountRequest,
32    ListEventsCountResponse,
33    ListEventsRequest,
34    ListEventsResponse,
35    events_service_client::EventsServiceClient,
36};
37
38pub use cx_api::proto::com::coralogixapis::events::v3::{
39    EventsFilter,
40    EventsQueryFilter,
41    FilterOperator,
42    Filters,
43    OrderBy,
44    OrderByDirection,
45    OrderByFields,
46    PaginationRequest,
47    TimestampRange,
48};
49
50use crate::{
51    CoralogixRegion,
52    auth::AuthContext,
53    error::{
54        Result,
55        SdkApiError,
56    },
57    metadata::CallProperties,
58    util::make_request_with_metadata,
59};
60
61const EVENTS_FEATURE_GROUP_ID: &str = "events";
62
63/// The Events API client.
64pub struct EventsClient {
65    metadata_map: tonic::metadata::MetadataMap,
66    service_client: Mutex<EventsServiceClient<Channel>>,
67}
68
69impl EventsClient {
70    /// Creates a new client for the Events API.
71    ///
72    /// # Arguments
73    /// * `region` - The region to connect to.
74    /// * `auth_context` - The authentication context to use.
75    pub fn new(region: CoralogixRegion, auth_context: AuthContext) -> Result<Self> {
76        let channel = Endpoint::from_str(&region.grpc_endpoint())?
77            .tls_config(ClientTlsConfig::new().with_native_roots())?
78            .connect_lazy();
79
80        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
81        Ok(Self {
82            metadata_map: request_metadata.to_metadata_map(),
83            service_client: Mutex::new(EventsServiceClient::new(channel)),
84        })
85    }
86
87    /// Gets a single event by ID.
88    ///
89    /// # Arguments
90    /// * `id` - The ID of the event to get.
91    /// * `order_bys` - The order by fields to use.
92    /// * `pagination` - The pagination request to use.
93    pub async fn get(
94        &self,
95        id: Option<String>,
96        order_bys: Vec<OrderBy>,
97        pagination: Option<PaginationRequest>,
98    ) -> Result<GetEventResponse> {
99        let request = make_request_with_metadata(
100            GetEventRequest {
101                id,
102                order_bys,
103                pagination,
104            },
105            &self.metadata_map,
106        );
107
108        Ok(self
109            .service_client
110            .lock()
111            .await
112            .get_event(request)
113            .await
114            .map_err(|status| SdkApiError {
115                status,
116                endpoint: "/com.coralogixapis.events.v3.EventsService/GetEvent".into(),
117                feature_group: EVENTS_FEATURE_GROUP_ID.into(),
118            })?
119            .into_inner())
120    }
121
122    /// Gets multiple events by their IDs.
123    ///
124    /// # Arguments
125    /// * `ids` - The IDs of the events to get.
126    /// * `order_bys` - The order by fields to use.
127    /// * `pagination` - The pagination request to use.
128    /// * `filter` - The filter to use.
129    pub async fn batch_get(
130        &self,
131        ids: Vec<String>,
132        order_bys: Vec<OrderBy>,
133        pagination: Option<PaginationRequest>,
134        filter: Option<EventsQueryFilter>,
135    ) -> Result<BatchGetEventResponse> {
136        let request = make_request_with_metadata(
137            BatchGetEventRequest {
138                ids,
139                order_bys,
140                pagination,
141                filter,
142            },
143            &self.metadata_map,
144        );
145
146        Ok(self
147            .service_client
148            .lock()
149            .await
150            .batch_get_event(request)
151            .await
152            .map_err(|status| SdkApiError {
153                status,
154                endpoint: "/com.coralogixapis.events.v3.EventsService/BatchGetEvent".into(),
155                feature_group: EVENTS_FEATURE_GROUP_ID.into(),
156            })?
157            .into_inner())
158    }
159
160    /// Lists events based on the provided filter criteria.
161    ///
162    /// # Arguments
163    /// * `filter` - The filter to use.
164    /// * `order_bys` - The order by fields to use.
165    /// * `pagination` - The pagination request to use.
166    pub async fn list(
167        &self,
168        filter: Option<EventsFilter>,
169        order_bys: Vec<OrderBy>,
170        pagination: Option<PaginationRequest>,
171    ) -> Result<ListEventsResponse> {
172        let request = make_request_with_metadata(
173            ListEventsRequest {
174                filter,
175                order_bys,
176                pagination,
177            },
178            &self.metadata_map,
179        );
180
181        Ok(self
182            .service_client
183            .lock()
184            .await
185            .list_events(request)
186            .await
187            .map_err(|status| SdkApiError {
188                status,
189                endpoint: "/com.coralogixapis.events.v3.EventsService/ListEvents".into(),
190                feature_group: EVENTS_FEATURE_GROUP_ID.into(),
191            })?
192            .into_inner())
193    }
194
195    /// Gets the count of events matching the filter criteria.
196    ///
197    /// # Arguments
198    /// * `filter` - The filter to use.
199    pub async fn list_count(
200        &self,
201        filter: Option<EventsFilter>,
202    ) -> Result<ListEventsCountResponse> {
203        let request =
204            make_request_with_metadata(ListEventsCountRequest { filter }, &self.metadata_map);
205
206        Ok(self
207            .service_client
208            .lock()
209            .await
210            .list_events_count(request)
211            .await
212            .map_err(|status| SdkApiError {
213                status,
214                endpoint: "/com.coralogixapis.events.v3.EventsService/ListEventsCount".into(),
215                feature_group: EVENTS_FEATURE_GROUP_ID.into(),
216            })?
217            .into_inner())
218    }
219
220    /// Gets statistics about events matching the filter criteria.
221    ///
222    /// # Arguments
223    /// * `filter` - The filter to use.
224    pub async fn get_statistics(
225        &self,
226        filter: Option<EventsFilter>,
227    ) -> Result<GetEventsStatisticsResponse> {
228        let request =
229            make_request_with_metadata(GetEventsStatisticsRequest { filter }, &self.metadata_map);
230
231        Ok(self
232            .service_client
233            .lock()
234            .await
235            .get_events_statistics(request)
236            .await
237            .map_err(|status| SdkApiError {
238                status,
239                endpoint: "/com.coralogixapis.events.v3.EventsService/GetEventsStatistics".into(),
240                feature_group: EVENTS_FEATURE_GROUP_ID.into(),
241            })?
242            .into_inner())
243    }
244}