reactive_graph_client/client/
mod.rs

1use std::fmt::Display;
2use std::fmt::Formatter;
3use std::sync::Arc;
4
5use crate::client::instances::Instances;
6use crate::client::json_schema::JsonSchema;
7use crate::client::plugin::api::Plugins;
8use crate::client::runtime::Runtime;
9use crate::client::types::Types;
10use cynic::GraphQlError;
11use cynic::Operation;
12use cynic::QueryBuilder;
13use cynic::http::CynicReqwestError;
14use cynic::http::ReqwestExt;
15use cynic_introspection::IntrospectionQuery;
16use cynic_introspection::Schema;
17use cynic_introspection::SchemaError;
18use reactive_graph_graph::InvalidComponentError;
19use reactive_graph_graph::InvalidEntityInstanceError;
20use reactive_graph_graph::InvalidEntityTypeError;
21use reactive_graph_graph::InvalidFlowInstanceError;
22use reactive_graph_graph::InvalidFlowTypeError;
23use reactive_graph_graph::InvalidRelationInstanceError;
24use reactive_graph_graph::InvalidRelationTypeError;
25use reactive_graph_remotes_model::InstanceAddress;
26use reqwest::Client;
27use reqwest::Error;
28use reqwest::header::InvalidHeaderValue;
29use thiserror::Error;
30
31pub mod instances;
32pub mod json_schema;
33pub mod plugin;
34pub mod runtime;
35pub mod types;
36
37#[derive(Debug)]
38pub enum ReactiveGraphClientError {
39    InvalidBearer(InvalidHeaderValue),
40    ClientCreationError(Error),
41}
42
43impl Display for ReactiveGraphClientError {
44    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
45        match self {
46            ReactiveGraphClientError::InvalidBearer(e) => {
47                writeln!(f, "{e}")
48            }
49            ReactiveGraphClientError::ClientCreationError(e) => {
50                writeln!(f, "{e}")
51            }
52        }
53    }
54}
55
56impl std::error::Error for ReactiveGraphClientError {}
57
58#[derive(Debug, Error)]
59pub enum ReactiveGraphClientExecutionError {
60    #[error("Failed to send request: {0}")]
61    FailedToSendRequest(CynicReqwestError),
62    #[error("Failed to parse response: {0}")]
63    FailedToParseResponse(Error),
64    #[error("Failed to run graphql query: {0}")]
65    GraphQlError(#[from] GraphQlErrors),
66    #[error("Failed to run introspection query")]
67    IntrospectionQueryError,
68    #[error("Schema error on introspection query: {0}")]
69    IntrospectionQuerySchemaError(#[from] SchemaError),
70    // #[error("Failed to parse a namespace type: {0}")]
71    // NamespacedTypeError(#[from] NamespacedTypeError),
72    #[error("Invalid component: {0}")]
73    InvalidComponent(#[from] InvalidComponentError),
74    #[error("Invalid entity type: {0}")]
75    InvalidEntityType(#[from] InvalidEntityTypeError),
76    #[error("Invalid relation type: {0}")]
77    InvalidRelationType(#[from] InvalidRelationTypeError),
78    #[error("Invalid flow type: {0}")]
79    InvalidFlowType(#[from] InvalidFlowTypeError),
80    #[error("Invalid entity instance: {0}")]
81    InvalidEntityInstance(#[from] InvalidEntityInstanceError),
82    #[error("Invalid relation instance: {0}")]
83    InvalidRelationInstance(#[from] InvalidRelationInstanceError),
84    #[error("Invalid flow instance: {0}")]
85    InvalidFlowInstance(#[from] InvalidFlowInstanceError),
86}
87
88impl From<CynicReqwestError> for ReactiveGraphClientExecutionError {
89    fn from(e: CynicReqwestError) -> Self {
90        ReactiveGraphClientExecutionError::FailedToSendRequest(e)
91    }
92}
93
94#[derive(Debug, Error)]
95pub struct GraphQlErrors(Vec<GraphQlError>);
96
97impl Display for GraphQlErrors {
98    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
99        let graphql_errors: Vec<String> = self.0.iter().map(|graphql_error| format!("{graphql_error}")).collect();
100        writeln!(f, "The response returned errors:\n{}", graphql_errors.join("\n"))
101    }
102}
103
104pub struct ReactiveGraphClient {
105    remote: InstanceAddress,
106    pub client: Client,
107}
108
109impl ReactiveGraphClient {
110    pub fn new_default() -> Result<Arc<Self>, ReactiveGraphClientError> {
111        ReactiveGraphClient::new(InstanceAddress::default())
112    }
113
114    pub fn new<A: Into<InstanceAddress>>(remote: A) -> Result<Arc<Self>, ReactiveGraphClientError> {
115        let remote = remote.into();
116        let mut client_builder = Client::builder()
117            .user_agent(remote.user_agent.clone())
118            .danger_accept_invalid_certs(remote.danger_accept_invalid_certs.unwrap_or_default())
119            .danger_accept_invalid_hostnames(remote.danger_accept_invalid_hostnames.unwrap_or_default());
120        if let Some(bearer) = remote.bearer.clone() {
121            let header_value = reqwest::header::HeaderValue::from_str(&format!("Bearer {bearer}")).map_err(ReactiveGraphClientError::InvalidBearer)?;
122            client_builder = client_builder.default_headers(std::iter::once((reqwest::header::AUTHORIZATION, header_value)).collect());
123        }
124        let client = client_builder.build().map_err(ReactiveGraphClientError::ClientCreationError)?;
125        Ok(Arc::new(Self { remote, client }))
126    }
127
128    #[cfg(all(test, feature = "integration-tests"))]
129    pub fn new_from_runtime(runtime: Arc<dyn reactive_graph_runtime_api::Runtime>) -> Result<Arc<Self>, ReactiveGraphClientError> {
130        let config = runtime.get_config_manager().get_graphql_server_config();
131        let address = InstanceAddress::new(config.hostname(), config.port(), config.is_secure());
132        ReactiveGraphClient::new(address)
133    }
134
135    /// Returns the instance address.
136    pub fn remote(&self) -> InstanceAddress {
137        self.remote.clone()
138    }
139
140    /// Returns the URL of the graphql endpoint of the remote.
141    pub fn url_reactive_graph(&self) -> String {
142        self.remote.url_reactive_graph()
143    }
144
145    /// Returns the URL of the dynamic graph endpoint of the remote.
146    pub fn url_dynamic_graph(&self) -> String {
147        self.remote.url_dynamic_graph()
148    }
149
150    /// Returns the URL of the runtime endpoint of the remote.
151    pub fn url_reactive_graph_runtime(&self) -> String {
152        self.remote.url_reactive_graph_runtime()
153    }
154
155    /// Returns the URL of the plugins endpoint of the remote.
156    pub fn url_reactive_graph_plugins(&self) -> String {
157        self.remote.url_reactive_graph_plugins()
158    }
159
160    pub async fn introspection_query(&self, url: String) -> Result<Schema, ReactiveGraphClientExecutionError> {
161        self.client
162            .post(url)
163            .run_graphql(IntrospectionQuery::build(()))
164            .await
165            .map_err(ReactiveGraphClientExecutionError::FailedToSendRequest)?
166            .data
167            .ok_or(ReactiveGraphClientExecutionError::IntrospectionQueryError)
168            .and_then(|data| data.into_schema().map_err(ReactiveGraphClientExecutionError::IntrospectionQuerySchemaError))
169    }
170
171    pub async fn introspection_query_reactive_graph(&self) -> Result<Schema, ReactiveGraphClientExecutionError> {
172        self.introspection_query(self.url_reactive_graph()).await
173    }
174
175    pub async fn introspection_query_dynamic_graph(&self) -> Result<Schema, ReactiveGraphClientExecutionError> {
176        self.introspection_query(self.url_dynamic_graph()).await
177    }
178
179    pub async fn introspection_query_reactive_graph_runtime(&self) -> Result<Schema, ReactiveGraphClientExecutionError> {
180        self.introspection_query(self.url_reactive_graph_runtime()).await
181    }
182
183    pub async fn introspection_query_reactive_graph_plugins(&self) -> Result<Schema, ReactiveGraphClientExecutionError> {
184        self.introspection_query(self.url_reactive_graph_plugins()).await
185    }
186
187    pub fn types(self: &Arc<Self>) -> Types {
188        Types::new(self.clone())
189    }
190
191    pub fn instances(self: &Arc<Self>) -> Instances {
192        Instances::new(self.clone())
193    }
194
195    pub fn json_schema(self: &Arc<Self>) -> JsonSchema {
196        JsonSchema::new(self.clone())
197    }
198
199    pub fn runtime(self: &Arc<Self>) -> Runtime {
200        Runtime::new(self.clone())
201    }
202
203    pub fn plugins(self: &Arc<Self>) -> Plugins {
204        Plugins::new(self.clone())
205    }
206
207    /// Runs a typed graphql query and extracts the response data.
208    pub async fn execute_graphql<ResponseData, Vars, ResponseType>(
209        &self,
210        operation: Operation<ResponseData, Vars>,
211        extractor: impl FnOnce(ResponseData) -> ResponseType,
212    ) -> Result<ResponseType, ReactiveGraphClientExecutionError>
213    where
214        Vars: serde::Serialize,
215        ResponseData: serde::de::DeserializeOwned + 'static,
216    {
217        self.execute(self.url_reactive_graph(), operation, extractor).await
218    }
219
220    /// Runs a typed graphql query and extracts the response data.
221    pub async fn execute_dynamic_graph<ResponseData, Vars, ResponseType>(
222        &self,
223        operation: Operation<ResponseData, Vars>,
224        extractor: impl FnOnce(ResponseData) -> ResponseType,
225    ) -> Result<ResponseType, ReactiveGraphClientExecutionError>
226    where
227        Vars: serde::Serialize,
228        ResponseData: serde::de::DeserializeOwned + 'static,
229    {
230        self.execute(self.url_dynamic_graph(), operation, extractor).await
231    }
232
233    /// Runs a typed graphql query and extracts the response data.
234    pub async fn execute_runtime<ResponseData, Vars, ResponseType>(
235        &self,
236        operation: Operation<ResponseData, Vars>,
237        extractor: impl FnOnce(ResponseData) -> ResponseType,
238    ) -> Result<ResponseType, ReactiveGraphClientExecutionError>
239    where
240        Vars: serde::Serialize,
241        ResponseData: serde::de::DeserializeOwned + 'static,
242    {
243        self.execute(self.url_reactive_graph_runtime(), operation, extractor).await
244    }
245
246    /// Runs a typed graphql query and extracts the response data.
247    pub async fn execute_plugins<ResponseData, Vars, ResponseType>(
248        &self,
249        operation: Operation<ResponseData, Vars>,
250        extractor: impl FnOnce(ResponseData) -> ResponseType,
251    ) -> Result<ResponseType, ReactiveGraphClientExecutionError>
252    where
253        Vars: serde::Serialize,
254        ResponseData: serde::de::DeserializeOwned + 'static,
255    {
256        self.execute(self.url_reactive_graph_plugins(), operation, extractor).await
257    }
258
259    /// Runs a typed graphql query and extracts the response data.
260    pub async fn execute<ResponseData, Vars, ResponseType>(
261        &self,
262        endpoint: String,
263        operation: Operation<ResponseData, Vars>,
264        extractor: impl FnOnce(ResponseData) -> ResponseType,
265    ) -> Result<ResponseType, ReactiveGraphClientExecutionError>
266    where
267        Vars: serde::Serialize,
268        ResponseData: serde::de::DeserializeOwned + 'static,
269    {
270        let response = self
271            // Cynic Client
272            .client
273            .post(endpoint)
274            .run_graphql(operation)
275            .await?;
276        if let Some(data) = response.data.map(extractor) {
277            return Ok(data);
278        }
279        Err(ReactiveGraphClientExecutionError::GraphQlError(GraphQlErrors(response.errors.unwrap_or(vec![]))))
280    }
281}