1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use crate::context::{Data, ResolveId};
use crate::error::ParseRequestError;
use crate::mutation_resolver::do_mutation_resolve;
use crate::parser::ast::{
    Definition, Document, OperationDefinition, SelectionSet, VariableDefinition,
};
use crate::parser::parse_query;
use crate::registry::CacheControl;
use crate::validation::{check_rules, CheckResult};
use crate::{
    do_resolve, ContextBase, Error, ObjectType, Pos, Positioned, QueryError, Result, Schema,
    Variables,
};
use itertools::Itertools;
use std::any::Any;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicUsize;
use tempdir::TempDir;

/// IntoQueryBuilder options
#[derive(Default, Clone)]
pub struct IntoQueryBuilderOpts {
    /// A temporary path to store the contents of all files.
    ///
    /// If None, the system temporary path is used.
    pub temp_dir: Option<PathBuf>,

    /// Maximum file size.
    pub max_file_size: Option<usize>,

    /// Maximum number of files.
    pub max_num_files: Option<usize>,
}

#[allow(missing_docs)]
#[async_trait::async_trait]
pub trait IntoQueryBuilder: Sized {
    async fn into_query_builder(self) -> std::result::Result<QueryBuilder, ParseRequestError> {
        self.into_query_builder_opts(&Default::default()).await
    }

    async fn into_query_builder_opts(
        self,
        opts: &IntoQueryBuilderOpts,
    ) -> std::result::Result<QueryBuilder, ParseRequestError>;
}

/// Query response
#[derive(Debug)]
pub struct QueryResponse {
    /// Data of query result
    pub data: serde_json::Value,

    /// Extensions result
    pub extensions: Option<serde_json::Map<String, serde_json::Value>>,

    /// Cache control value
    pub cache_control: CacheControl,
}

/// Query builder
pub struct QueryBuilder {
    pub(crate) query_source: String,
    pub(crate) operation_name: Option<String>,
    pub(crate) variables: Variables,
    pub(crate) ctx_data: Option<Data>,
    pub(crate) files_holder: Option<TempDir>,
}

impl QueryBuilder {
    /// Create query builder with query source.
    pub fn new<T: Into<String>>(query_source: T) -> QueryBuilder {
        QueryBuilder {
            query_source: query_source.into(),
            operation_name: None,
            variables: Default::default(),
            ctx_data: None,
            files_holder: None,
        }
    }

    /// Specify the operation name.
    pub fn operator_name<T: Into<String>>(self, name: T) -> Self {
        QueryBuilder {
            operation_name: Some(name.into()),
            ..self
        }
    }

    /// Specify the variables.
    pub fn variables(self, variables: Variables) -> Self {
        QueryBuilder { variables, ..self }
    }

    /// Add a context data that can be accessed in the `Context`, you access it with `Context::data`.
    ///
    /// **This data is only valid for this query**
    pub fn data<D: Any + Send + Sync>(mut self, data: D) -> Self {
        if let Some(ctx_data) = &mut self.ctx_data {
            ctx_data.insert(data);
        } else {
            let mut ctx_data = Data::default();
            ctx_data.insert(data);
            self.ctx_data = Some(ctx_data);
        }
        self
    }

    /// Set file holder
    pub fn set_files_holder(&mut self, files_holder: TempDir) {
        self.files_holder = Some(files_holder);
    }

    /// Set uploaded file path
    pub fn set_upload(
        &mut self,
        var_path: &str,
        filename: &str,
        content_type: Option<&str>,
        path: &Path,
    ) {
        self.variables
            .set_upload(var_path, filename, content_type, path);
    }

    /// Execute the query.
    pub async fn execute<Query, Mutation, Subscription>(
        self,
        schema: &Schema<Query, Mutation, Subscription>,
    ) -> Result<QueryResponse>
    where
        Query: ObjectType + Send + Sync,
        Mutation: ObjectType + Send + Sync,
    {
        // create extension instances
        let extensions = schema
            .0
            .extensions
            .iter()
            .map(|factory| factory())
            .collect_vec();

        // parse query source
        extensions
            .iter()
            .for_each(|e| e.parse_start(&self.query_source));
        let document = parse_query(&self.query_source).map_err(Into::<Error>::into)?;
        extensions.iter().for_each(|e| e.parse_end());

        // check rules
        extensions.iter().for_each(|e| e.validation_start());
        let CheckResult {
            cache_control,
            complexity,
            depth,
        } = check_rules(&schema.0.registry, &document, schema.0.validation_mode)?;
        extensions.iter().for_each(|e| e.validation_end());

        // check limit
        if let Some(limit_complexity) = schema.0.complexity {
            if complexity > limit_complexity {
                return Err(QueryError::TooComplex.into_error(Pos::default()));
            }
        }

        if let Some(limit_depth) = schema.0.depth {
            if depth > limit_depth {
                return Err(QueryError::TooDeep.into_error(Pos::default()));
            }
        }

        // execute
        let inc_resolve_id = AtomicUsize::default();
        let mut fragments = HashMap::new();
        let (selection_set, variable_definitions, is_query) =
            current_operation(&document, self.operation_name.as_deref()).ok_or_else(|| {
                Error::Query {
                    pos: Pos::default(),
                    path: None,
                    err: QueryError::MissingOperation,
                }
            })?;

        for definition in &document.definitions {
            if let Definition::Fragment(fragment) = &definition.node {
                fragments.insert(fragment.name.clone_inner(), fragment.clone_inner());
            }
        }

        let ctx = ContextBase {
            path_node: None,
            resolve_id: ResolveId::root(),
            inc_resolve_id: &inc_resolve_id,
            extensions: &extensions,
            item: selection_set,
            variables: &self.variables,
            variable_definitions,
            registry: &schema.0.registry,
            data: &schema.0.data,
            ctx_data: self.ctx_data.as_ref(),
            fragments: &fragments,
        };

        extensions.iter().for_each(|e| e.execution_start());
        let data = if is_query {
            do_resolve(&ctx, &schema.0.query).await?
        } else {
            do_mutation_resolve(&ctx, &schema.0.mutation).await?
        };
        extensions.iter().for_each(|e| e.execution_end());

        let res = QueryResponse {
            data,
            extensions: if !extensions.is_empty() {
                Some(
                    extensions
                        .iter()
                        .filter_map(|e| {
                            if let Some(name) = e.name() {
                                e.result().map(|res| (name.to_string(), res))
                            } else {
                                None
                            }
                        })
                        .collect::<serde_json::Map<_, _>>(),
                )
            } else {
                None
            },
            cache_control,
        };
        Ok(res)
    }
}

#[allow(clippy::type_complexity)]
fn current_operation<'a>(
    document: &'a Document,
    operation_name: Option<&str>,
) -> Option<(
    &'a Positioned<SelectionSet>,
    &'a [Positioned<VariableDefinition>],
    bool,
)> {
    for definition in &document.definitions {
        match &definition.node {
            Definition::Operation(operation_definition) => match &operation_definition.node {
                OperationDefinition::SelectionSet(s) => {
                    return Some((s, &[], true));
                }
                OperationDefinition::Query(query)
                    if query.name.is_none()
                        || operation_name.is_none()
                        || query.name.as_ref().map(|name| name.as_str())
                            == operation_name.as_deref() =>
                {
                    return Some((&query.selection_set, &query.variable_definitions, true));
                }
                OperationDefinition::Mutation(mutation)
                    if mutation.name.is_none()
                        || operation_name.is_none()
                        || mutation.name.as_ref().map(|name| name.as_str())
                            == operation_name.as_deref() =>
                {
                    return Some((
                        &mutation.selection_set,
                        &mutation.variable_definitions,
                        false,
                    ));
                }
                OperationDefinition::Subscription(subscription)
                    if subscription.name.is_none()
                        || operation_name.is_none()
                        || subscription.name.as_ref().map(|name| name.as_str())
                            == operation_name.as_deref() =>
                {
                    return None;
                }
                _ => {}
            },
            Definition::Fragment(_) => {}
        }
    }
    None
}