async-graphql/src/extensions/mod.rs

472 lines
14 KiB
Rust
Raw Normal View History

2020-03-26 03:34:28 +00:00
//! Extensions for schema
2020-12-18 15:58:03 +00:00
mod analyzer;
#[cfg(feature = "apollo_persisted_queries")]
pub mod apollo_persisted_queries;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "apollo_tracing")]
2020-04-28 07:01:19 +00:00
mod apollo_tracing;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "log")]
2020-05-22 03:58:49 +00:00
mod logger;
2021-03-20 11:42:00 +00:00
#[cfg(feature = "opentelemetry")]
mod opentelemetry;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "tracing")]
2020-03-26 03:34:28 +00:00
mod tracing;
2020-12-18 15:58:03 +00:00
pub use self::analyzer::Analyzer;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "apollo_tracing")]
2020-05-22 03:58:49 +00:00
pub use self::apollo_tracing::ApolloTracing;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "log")]
2020-05-22 03:58:49 +00:00
pub use self::logger::Logger;
2021-03-20 11:42:00 +00:00
#[cfg(feature = "opentelemetry")]
2021-04-04 04:05:54 +00:00
pub use self::opentelemetry::OpenTelemetry;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "tracing")]
2021-04-04 04:05:54 +00:00
pub use self::tracing::Tracing;
2020-03-26 03:34:28 +00:00
2021-04-04 04:05:54 +00:00
use std::any::{Any, TypeId};
use std::future::Future;
use std::sync::Arc;
use futures_util::stream::BoxStream;
use futures_util::stream::StreamExt;
use crate::parser::types::ExecutableDocument;
use crate::{
Data, Error, QueryPathNode, Request, Response, Result, SchemaEnv, ServerError, ServerResult,
ValidationResult, Value, Variables,
};
2020-03-26 03:34:28 +00:00
2020-09-29 12:47:37 +00:00
/// Context for extension
pub struct ExtensionContext<'a> {
2020-09-26 07:52:59 +00:00
#[doc(hidden)]
2020-09-29 12:47:37 +00:00
pub schema_data: &'a Data,
2020-09-26 07:52:59 +00:00
#[doc(hidden)]
pub session_data: &'a Data,
#[doc(hidden)]
pub query_data: Option<&'a Data>,
}
2020-09-29 12:47:37 +00:00
impl<'a> ExtensionContext<'a> {
/// Gets the global data defined in the `Context` or `Schema`.
///
/// If both `Schema` and `Query` have the same data type, the data in the `Query` is obtained.
///
/// # Errors
///
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
/// Returns a `Error` if the specified type data does not exist.
pub fn data<D: Any + Send + Sync>(&self) -> Result<&'a D> {
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
self.data_opt::<D>().ok_or_else(|| {
Error::new(format!(
"Data `{}` does not exist.",
std::any::type_name::<D>()
))
})
}
/// Gets the global data defined in the `Context` or `Schema`.
///
/// # Panics
///
/// It will panic if the specified data type does not exist.
pub fn data_unchecked<D: Any + Send + Sync>(&self) -> &'a D {
self.data_opt::<D>()
.unwrap_or_else(|| panic!("Data `{}` does not exist.", std::any::type_name::<D>()))
}
/// Gets the global data defined in the `Context` or `Schema` or `None` if the specified type data does not exist.
pub fn data_opt<D: Any + Send + Sync>(&self) -> Option<&'a D> {
2020-09-29 12:47:37 +00:00
self.query_data
.and_then(|query_data| query_data.get(&TypeId::of::<D>()))
.or_else(|| self.session_data.get(&TypeId::of::<D>()))
2020-09-29 12:47:37 +00:00
.or_else(|| self.schema_data.get(&TypeId::of::<D>()))
.and_then(|d| d.downcast_ref::<D>())
}
2020-03-26 03:34:28 +00:00
}
2020-09-29 12:47:37 +00:00
/// Parameters for `Extension::resolve_field_start`
pub struct ResolveInfo<'a> {
/// Current path node, You can go through the entire path.
pub path_node: &'a QueryPathNode<'a>,
/// Parent type
pub parent_type: &'a str,
/// Current return type, is qualified name.
pub return_type: &'a str,
}
2021-04-04 04:05:54 +00:00
type RequestFut<'a> = &'a mut (dyn Future<Output = Response> + Send + Unpin);
type ParseFut<'a> = &'a mut (dyn Future<Output = ServerResult<ExecutableDocument>> + Send + Unpin);
type ValidationFut<'a> =
&'a mut (dyn Future<Output = Result<ValidationResult, Vec<ServerError>>> + Send + Unpin);
type ExecuteFut<'a> = &'a mut (dyn Future<Output = Response> + Send + Unpin);
type ResolveFut<'a> = &'a mut (dyn Future<Output = ServerResult<Option<Value>>> + Send + Unpin);
/// The remainder of a extension chain.
pub struct NextExtension<'a> {
chain: &'a [Arc<dyn Extension>],
request_fut: Option<RequestFut<'a>>,
parse_query_fut: Option<ParseFut<'a>>,
validation_fut: Option<ValidationFut<'a>>,
execute_fut: Option<ExecuteFut<'a>>,
resolve_fut: Option<ResolveFut<'a>>,
}
impl<'a> NextExtension<'a> {
#[inline]
pub(crate) fn new(chain: &'a [Arc<dyn Extension>]) -> Self {
Self {
chain,
request_fut: None,
parse_query_fut: None,
validation_fut: None,
execute_fut: None,
resolve_fut: None,
}
}
#[inline]
pub(crate) fn with_chain(self, chain: &'a [Arc<dyn Extension>]) -> Self {
Self { chain, ..self }
2020-04-28 07:01:19 +00:00
}
2020-03-26 03:34:28 +00:00
2021-04-04 04:05:54 +00:00
#[inline]
pub(crate) fn with_request(self, fut: RequestFut<'a>) -> Self {
Self {
request_fut: Some(fut),
..self
}
}
2021-04-04 04:05:54 +00:00
#[inline]
pub(crate) fn with_parse_query(self, fut: ParseFut<'a>) -> Self {
Self {
parse_query_fut: Some(fut),
..self
}
}
2021-04-04 04:05:54 +00:00
#[inline]
pub(crate) fn with_validation(self, fut: ValidationFut<'a>) -> Self {
Self {
validation_fut: Some(fut),
..self
}
}
#[inline]
pub(crate) fn with_execute(self, fut: ExecuteFut<'a>) -> Self {
Self {
execute_fut: Some(fut),
..self
}
}
#[inline]
pub(crate) fn with_resolve(self, fut: ResolveFut<'a>) -> Self {
Self {
resolve_fut: Some(fut),
..self
}
}
/// Call the [Extension::request] function of next extension.
pub async fn request(mut self, ctx: &ExtensionContext<'_>) -> Response {
if let Some((first, next)) = self.chain.split_first() {
first.request(ctx, self.with_chain(next)).await
} else {
self.request_fut
.take()
.expect("You definitely called the wrong function.")
.await
}
}
/// Call the [Extension::subscribe] function of next extension.
pub fn subscribe<'s>(
self,
ctx: &ExtensionContext<'_>,
stream: BoxStream<'s, Response>,
) -> BoxStream<'s, Response> {
if let Some((first, next)) = self.chain.split_first() {
first.subscribe(ctx, stream, self.with_chain(next))
} else {
stream
}
}
/// Call the [Extension::prepare_request] function of next extension.
pub async fn prepare_request(
self,
ctx: &ExtensionContext<'_>,
request: Request,
) -> ServerResult<Request> {
2021-04-04 04:05:54 +00:00
if let Some((first, next)) = self.chain.split_first() {
first
.prepare_request(ctx, request, self.with_chain(next))
.await
} else {
Ok(request)
}
}
2021-04-04 04:05:54 +00:00
/// Call the [Extension::parse_query] function of next extension.
pub async fn parse_query(
mut self,
2020-09-29 12:47:37 +00:00
ctx: &ExtensionContext<'_>,
2021-04-04 04:05:54 +00:00
query: &str,
2020-09-29 12:47:37 +00:00
variables: &Variables,
2021-04-04 04:05:54 +00:00
) -> ServerResult<ExecutableDocument> {
if let Some((first, next)) = self.chain.split_first() {
first
.parse_query(ctx, query, variables, self.with_chain(next))
.await
} else {
self.parse_query_fut
.take()
.expect("You definitely called the wrong function.")
.await
}
2020-09-29 12:47:37 +00:00
}
2020-03-26 03:34:28 +00:00
2021-04-04 04:05:54 +00:00
/// Call the [Extension::validation] function of next extension.
pub async fn validation(
mut self,
ctx: &ExtensionContext<'_>,
) -> Result<ValidationResult, Vec<ServerError>> {
if let Some((first, next)) = self.chain.split_first() {
first.validation(ctx, self.with_chain(next)).await
} else {
self.validation_fut
.take()
.expect("You definitely called the wrong function.")
.await
}
}
2020-03-26 03:34:28 +00:00
2021-04-04 04:05:54 +00:00
/// Call the [Extension::execute] function of next extension.
pub async fn execute(mut self, ctx: &ExtensionContext<'_>) -> Response {
if let Some((first, next)) = self.chain.split_first() {
first.execute(ctx, self.with_chain(next)).await
} else {
self.execute_fut
.take()
.expect("You definitely called the wrong function.")
.await
}
}
2020-03-26 03:34:28 +00:00
2021-04-04 04:05:54 +00:00
/// Call the [Extension::resolve] function of next extension.
pub async fn resolve(
mut self,
ctx: &ExtensionContext<'_>,
info: ResolveInfo<'_>,
) -> ServerResult<Option<Value>> {
if let Some((first, next)) = self.chain.split_first() {
first.resolve(ctx, info, self.with_chain(next)).await
} else {
self.resolve_fut
.take()
.expect("You definitely called the wrong function.")
.await
}
}
}
2020-03-26 03:34:28 +00:00
2021-04-04 04:05:54 +00:00
/// Represents a GraphQL extension
#[async_trait::async_trait]
#[allow(unused_variables)]
pub trait Extension: Sync + Send + 'static {
/// Called at start query/mutation request.
async fn request(&self, ctx: &ExtensionContext<'_>, next: NextExtension<'_>) -> Response {
next.request(ctx).await
}
2020-03-26 03:34:28 +00:00
2021-04-04 04:05:54 +00:00
/// Called at subscribe request.
fn subscribe<'s>(
&self,
ctx: &ExtensionContext<'_>,
stream: BoxStream<'s, Response>,
next: NextExtension<'_>,
) -> BoxStream<'s, Response> {
next.subscribe(ctx, stream)
}
2020-05-22 03:58:49 +00:00
2021-04-04 04:05:54 +00:00
/// Called at prepare request.
async fn prepare_request(
&self,
ctx: &ExtensionContext<'_>,
request: Request,
next: NextExtension<'_>,
) -> ServerResult<Request> {
next.prepare_request(ctx, request).await
}
2020-03-26 03:34:28 +00:00
2021-04-04 04:05:54 +00:00
/// Called at parse query.
async fn parse_query(
&self,
ctx: &ExtensionContext<'_>,
query: &str,
variables: &Variables,
next: NextExtension<'_>,
) -> ServerResult<ExecutableDocument> {
next.parse_query(ctx, query, variables).await
2020-04-28 07:01:19 +00:00
}
2020-05-22 03:58:49 +00:00
2021-04-04 04:05:54 +00:00
/// Called at validation query.
async fn validation(
&self,
ctx: &ExtensionContext<'_>,
next: NextExtension<'_>,
) -> Result<ValidationResult, Vec<ServerError>> {
next.validation(ctx).await
}
2021-04-04 04:05:54 +00:00
/// Called at execute query.
async fn execute(&self, ctx: &ExtensionContext<'_>, next: NextExtension<'_>) -> Response {
next.execute(ctx).await
2020-05-22 03:58:49 +00:00
}
2020-10-12 06:49:32 +00:00
2021-04-04 04:05:54 +00:00
/// Called at resolve field.
async fn resolve(
&self,
ctx: &ExtensionContext<'_>,
info: ResolveInfo<'_>,
next: NextExtension<'_>,
) -> ServerResult<Option<Value>> {
next.resolve(ctx, info).await
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
}
}
2020-05-22 03:58:49 +00:00
2020-10-12 06:49:32 +00:00
/// Extension factory
///
/// Used to create an extension instance.
pub trait ExtensionFactory: Send + Sync + 'static {
/// Create an extended instance.
2021-04-04 04:05:54 +00:00
fn create(&self) -> Arc<dyn Extension>;
2020-10-12 06:49:32 +00:00
}
2021-04-04 04:05:54 +00:00
#[derive(Clone)]
2020-10-12 06:49:32 +00:00
#[doc(hidden)]
pub struct Extensions {
2021-04-04 04:05:54 +00:00
extensions: Vec<Arc<dyn Extension>>,
schema_env: SchemaEnv,
session_data: Arc<Data>,
query_data: Option<Arc<Data>>,
}
2020-10-12 06:49:32 +00:00
#[doc(hidden)]
impl Extensions {
2021-04-04 04:05:54 +00:00
pub(crate) fn new(
extensions: impl IntoIterator<Item = Arc<dyn Extension>>,
schema_env: SchemaEnv,
session_data: Arc<Data>,
) -> Self {
Extensions {
2021-04-04 04:05:54 +00:00
extensions: extensions.into_iter().collect(),
schema_env,
session_data,
query_data: None,
}
}
pub fn attach_query_data(&mut self, data: Arc<Data>) {
self.query_data = Some(data);
}
2021-04-04 04:05:54 +00:00
#[inline]
pub(crate) fn is_empty(&self) -> bool {
self.extensions.is_empty()
2020-10-12 06:49:32 +00:00
}
#[inline]
2021-04-04 04:05:54 +00:00
fn create_context(&self) -> ExtensionContext {
ExtensionContext {
schema_data: &self.schema_env.data,
session_data: &self.session_data,
query_data: self.query_data.as_deref(),
}
}
2021-04-04 04:05:54 +00:00
pub async fn request(&self, request_fut: RequestFut<'_>) -> Response {
if !self.extensions.is_empty() {
let next = NextExtension::new(&self.extensions).with_request(request_fut);
next.request(&self.create_context()).await
} else {
request_fut.await
}
}
2021-04-04 04:05:54 +00:00
pub fn subscribe<'s>(&self, stream: BoxStream<'s, Response>) -> BoxStream<'s, Response> {
if !self.extensions.is_empty() {
let next = NextExtension::new(&self.extensions);
next.subscribe(&self.create_context(), stream)
} else {
stream.boxed()
}
}
pub async fn prepare_request(&self, request: Request) -> ServerResult<Request> {
2021-04-04 04:05:54 +00:00
if !self.extensions.is_empty() {
let next = NextExtension::new(&self.extensions);
next.prepare_request(&self.create_context(), request).await
} else {
Ok(request)
2020-10-12 06:49:32 +00:00
}
2020-05-22 03:58:49 +00:00
}
2021-04-04 04:05:54 +00:00
pub async fn parse_query(
&self,
query: &str,
variables: &Variables,
parse_query_fut: ParseFut<'_>,
) -> ServerResult<ExecutableDocument> {
if !self.extensions.is_empty() {
let next = NextExtension::new(&self.extensions).with_parse_query(parse_query_fut);
next.parse_query(&self.create_context(), query, variables)
.await
} else {
parse_query_fut.await
2020-10-12 06:49:32 +00:00
}
2020-05-22 03:58:49 +00:00
}
2021-04-04 04:05:54 +00:00
pub async fn validation(
&self,
validation_fut: ValidationFut<'_>,
) -> Result<ValidationResult, Vec<ServerError>> {
if !self.extensions.is_empty() {
let next = NextExtension::new(&self.extensions).with_validation(validation_fut);
next.validation(&self.create_context()).await
} else {
validation_fut.await
2020-10-12 06:49:32 +00:00
}
2020-05-22 03:58:49 +00:00
}
2021-04-04 04:05:54 +00:00
pub async fn execute(&self, execute_fut: ExecuteFut<'_>) -> Response {
if !self.extensions.is_empty() {
let next = NextExtension::new(&self.extensions).with_execute(execute_fut);
next.execute(&self.create_context()).await
} else {
execute_fut.await
2020-10-12 06:49:32 +00:00
}
2020-05-22 03:58:49 +00:00
}
2021-04-04 04:05:54 +00:00
pub async fn resolve(
&self,
info: ResolveInfo<'_>,
resolve_fut: ResolveFut<'_>,
) -> ServerResult<Option<Value>> {
if !self.extensions.is_empty() {
let next = NextExtension::new(&self.extensions).with_resolve(resolve_fut);
next.resolve(&self.create_context(), info).await
2020-05-22 03:58:49 +00:00
} else {
2021-04-04 04:05:54 +00:00
resolve_fut.await
2020-05-22 03:58:49 +00:00
}
}
}