use std::{
any::TypeId,
sync::{Arc, OnceLock},
};
use futures::future::BoxFuture;
use gql::{AppliedDirective, ComplexityFn, Field, GraphQLError, Name, TypeRef};
use indexmap::IndexMap;
use crate::{
registry::TypeRegistry,
schema::ObjectRef,
traits::{AbstractType, InputObject, ObjectModel, OutputType},
};
#[derive(Clone, Debug)]
pub(crate) enum FieldCheck {
Abstract {
owner: Name,
field: Name,
original: TypeRef,
abstract_name: Name,
},
TypeOverride {
owner: Name,
field: Name,
original: TypeRef,
replacement: TypeRef,
},
NonNullOnOption {
owner: Name,
field: Name,
rust_type: &'static str,
},
NullableItemsOnNonList {
owner: Name,
field: Name,
ty: TypeRef,
},
NonNullItemsOnNonList {
owner: Name,
field: Name,
ty: TypeRef,
},
InheritedType {
owner: Name,
field: Name,
actual: TypeRef,
expected: TypeRef,
},
DynamicObject {
owner: Name,
field: Name,
original: TypeRef,
model: &'static str,
},
DynamicType {
owner: Name,
field: Name,
rust: TypeRef,
declared: TypeRef,
},
}
pub(crate) enum FieldSink<'a> {
Object(&'a mut IndexMap<Name, Field>),
Fields(&'a mut Vec<Field>),
}
impl FieldSink<'_> {
fn get(&self, name: &str) -> Option<&Field> {
match self {
Self::Object(fields) => fields.get(name),
Self::Fields(fields) => fields.iter().rev().find(|field| &*field.name == name),
}
}
fn get_mut(&mut self, name: &str) -> Option<&mut Field> {
match self {
Self::Object(fields) => fields.get_mut(name),
Self::Fields(fields) => fields.iter_mut().rev().find(|field| &*field.name == name),
}
}
}
enum GuardPredicate<Ctx: 'static> {
Sync(Arc<dyn Fn(&Ctx) -> bool + Send + Sync>),
Async(Arc<dyn for<'r> Fn(&'r Ctx) -> BoxFuture<'r, bool> + Send + Sync>),
}
impl<Ctx: 'static> Clone for GuardPredicate<Ctx> {
fn clone(&self) -> Self {
match self {
Self::Sync(predicate) => Self::Sync(Arc::clone(predicate)),
Self::Async(predicate) => Self::Async(Arc::clone(predicate)),
}
}
}
pub(crate) struct AuthGuard<Ctx: 'static> {
predicate: GuardPredicate<Ctx>,
message: Arc<str>,
}
impl<Ctx: 'static> Clone for AuthGuard<Ctx> {
fn clone(&self) -> Self {
Self {
predicate: self.predicate.clone(),
message: Arc::clone(&self.message),
}
}
}
impl<Ctx: 'static> AuthGuard<Ctx> {
fn new(predicate: GuardPredicate<Ctx>, message: Option<Arc<str>>) -> Self {
Self {
predicate,
message: message.unwrap_or_else(|| Arc::from("Not authorized")),
}
}
pub(crate) fn with_message(&self, message: Option<Arc<str>>) -> Arc<Self> {
Arc::new(Self {
predicate: self.predicate.clone(),
message: message.unwrap_or_else(|| Arc::clone(&self.message)),
})
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(skip_all, level = "trace", name = "gurafi.auth")
)]
fn check<'r>(&self, context: &'r Ctx) -> BoxFuture<'r, Result<(), GraphQLError>> {
let message = Arc::clone(&self.message);
match &self.predicate {
GuardPredicate::Sync(predicate) => {
let allowed = predicate(context);
Box::pin(async move {
if allowed {
Ok(())
} else {
Err(GraphQLError::new(message.to_string()).extend("code", "UNAUTHORIZED"))
}
})
}
GuardPredicate::Async(predicate) => {
let future = predicate(context);
Box::pin(async move {
if future.await {
Ok(())
} else {
Err(GraphQLError::new(message.to_string()).extend("code", "UNAUTHORIZED"))
}
})
}
}
}
}
pub(crate) struct RawFieldArgs;
pub(crate) struct ValidationSlot<Ctx: 'static> {
hook: Arc<OnceLock<ErasedValidator<Ctx>>>,
}
impl<Ctx: 'static> Clone for ValidationSlot<Ctx> {
fn clone(&self) -> Self {
Self {
hook: Arc::clone(&self.hook),
}
}
}
type ErasedValidator<Ctx> =
Arc<dyn Fn(&dyn std::any::Any, &Ctx) -> Result<(), GraphQLError> + Send + Sync>;
impl<Ctx: 'static> Default for ValidationSlot<Ctx> {
fn default() -> Self {
Self::new()
}
}
impl<Ctx: 'static> ValidationSlot<Ctx> {
pub(crate) fn new() -> Self {
Self {
hook: Arc::new(OnceLock::new()),
}
}
pub(crate) fn install<A: 'static>(
&self,
validator: impl Fn(&A, &Ctx) -> Result<(), GraphQLError> + Send + Sync + 'static,
) {
let validator = Arc::new(validator);
let _ = self
.hook
.set(Arc::new(move |args: &dyn std::any::Any, ctx: &Ctx| {
let args = args.downcast_ref::<A>().ok_or_else(|| {
GraphQLError::new(
"Internal error: a field validator received arguments of a different type.",
)
})?;
validator(args, ctx)
}));
}
pub(crate) fn is_installed(&self) -> bool {
self.hook.get().is_some()
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(
skip_all,
level = "trace",
name = "gurafi.validator",
fields(args = std::any::type_name::<A>())
)
)]
pub(crate) fn run<A: 'static>(&self, args: &A, ctx: &Ctx) -> Result<(), GraphQLError> {
match self.hook.get() {
Some(hook) => hook(args, ctx),
None => Ok(()),
}
}
}
enum Complexity {
Fixed(u32),
Custom(ComplexityFn),
}
pub struct FieldConfig<'a, Ctx: 'static> {
registry: &'a mut TypeRegistry,
sink: FieldSink<'a>,
name: Name,
description: Option<Arc<str>>,
deprecation: Option<Arc<str>>,
directives: Vec<AppliedDirective>,
complexity: Option<Complexity>,
auth: Option<GuardPredicate<Ctx>>,
auth_error: Option<Arc<str>>,
field_auth: Option<&'a mut IndexMap<Name, Arc<AuthGuard<Ctx>>>>,
checks: Option<&'a mut Vec<FieldCheck>>,
owner: Name,
original: OnceLock<TypeRef>,
rust_nullable: bool,
rust_type_name: &'static str,
args_type: TypeId,
validation: ValidationSlot<Ctx>,
marker: std::marker::PhantomData<fn() -> Ctx>,
}
fn empty_name() -> Name {
static EMPTY: OnceLock<Name> = OnceLock::new();
Arc::clone(EMPTY.get_or_init(|| Name::from("")))
}
impl<'a, Ctx: 'static> FieldConfig<'a, Ctx> {
pub(crate) fn for_object_checked(
registry: &'a mut TypeRegistry,
fields: &'a mut IndexMap<Name, Field>,
checks: &'a mut Vec<FieldCheck>,
owner: impl Into<Name>,
name: Name,
rust_nullable: bool,
rust_type_name: &'static str,
args_type: TypeId,
validation: ValidationSlot<Ctx>,
) -> Self {
Self::new(
registry,
FieldSink::Object(fields),
name,
Some(checks),
owner.into(),
rust_nullable,
rust_type_name,
args_type,
validation,
)
}
pub(crate) fn for_interface(
registry: &'a mut TypeRegistry,
fields: &'a mut IndexMap<Name, Field>,
field_auth: &'a mut IndexMap<Name, Arc<AuthGuard<Ctx>>>,
name: Name,
rust_nullable: bool,
rust_type_name: &'static str,
) -> Self {
let mut config = Self::new(
registry,
FieldSink::Object(fields),
name,
None,
empty_name(),
rust_nullable,
rust_type_name,
TypeId::of::<()>(),
ValidationSlot::new(),
);
config.field_auth = Some(field_auth);
config
}
pub(crate) fn for_fields_checked(
registry: &'a mut TypeRegistry,
fields: &'a mut Vec<Field>,
checks: &'a mut Vec<FieldCheck>,
owner: impl Into<Name>,
name: Name,
rust_nullable: bool,
rust_type_name: &'static str,
args_type: TypeId,
validation: ValidationSlot<Ctx>,
) -> Self {
Self::new(
registry,
FieldSink::Fields(fields),
name,
Some(checks),
owner.into(),
rust_nullable,
rust_type_name,
args_type,
validation,
)
}
fn new(
registry: &'a mut TypeRegistry,
sink: FieldSink<'a>,
name: Name,
checks: Option<&'a mut Vec<FieldCheck>>,
owner: Name,
rust_nullable: bool,
rust_type_name: &'static str,
args_type: TypeId,
validation: ValidationSlot<Ctx>,
) -> Self {
Self {
registry,
sink,
name,
description: None,
deprecation: None,
directives: Vec::new(),
complexity: None,
auth: None,
auth_error: None,
field_auth: None,
checks,
owner,
original: OnceLock::new(),
rust_nullable,
rust_type_name,
args_type,
validation,
marker: std::marker::PhantomData,
}
}
fn original(&self) -> &TypeRef {
self.original.get_or_init(|| {
self.sink.get(&self.name).map_or_else(
|| TypeRef::Named(Arc::clone(&self.name)),
|field| field.ty.clone(),
)
})
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
pub fn description(&mut self, description: impl Into<Arc<str>>) -> &mut Self {
self.description = Some(description.into());
self
}
pub fn deprecated(&mut self, reason: impl Into<Arc<str>>) -> &mut Self {
self.deprecation = Some(reason.into());
self
}
pub fn directive(&mut self, directive: AppliedDirective) -> &mut Self {
self.directives.push(directive);
self
}
pub fn complexity(&mut self, complexity: u32) -> &mut Self {
self.complexity = Some(Complexity::Fixed(complexity));
self
}
pub fn complexity_with(
&mut self,
estimator: impl Fn(&gql::Object) -> u32 + Send + Sync + 'static,
) -> &mut Self {
self.complexity = Some(Complexity::Custom(Arc::new(estimator)));
self
}
pub fn auth(&mut self, predicate: impl Fn(&Ctx) -> bool + Send + Sync + 'static) -> &mut Self {
self.auth = Some(GuardPredicate::Sync(Arc::new(predicate)));
self
}
pub fn auth_async(
&mut self,
predicate: impl for<'r> Fn(&'r Ctx) -> BoxFuture<'r, bool> + Send + Sync + 'static,
) -> &mut Self {
self.auth = Some(GuardPredicate::Async(Arc::new(predicate)));
self
}
pub fn auth_error(&mut self, message: impl Into<Arc<str>>) -> &mut Self {
self.auth_error = Some(message.into());
self
}
pub fn validate<A: InputObject>(
&mut self,
validator: impl Fn(&A, &Ctx) -> Result<(), GraphQLError> + Send + Sync + 'static,
) -> &mut Self {
if self.args_type == TypeId::of::<RawFieldArgs>() {
self.registry.push_error(GraphQLError::new(format!(
"Field `{}.{}` is declared with `raw_field`, which installs no resolver, so a \
`validate` hook could never run. Declare the field with `raw_field_with::<_, \
Args>(...)` to coerce arguments through a resolver, then call `validate` on that.",
self.owner, self.name,
)));
return self;
}
if TypeId::of::<A>() != self.args_type {
self.registry.push_error(GraphQLError::new(format!(
"Field `{}.{}` calls `validate::<{}>()`, but its resolver's arguments type is \
not `{}`. Use the field's actual arguments type, or change the resolver to take \
`{}`.",
self.owner,
self.name,
std::any::type_name::<A>(),
std::any::type_name::<A>(),
std::any::type_name::<A>(),
)));
return self;
}
if self.validation.is_installed() {
self.registry.push_error(GraphQLError::new(format!(
"Field `{}.{}` installs more than one `validate` hook. Combine the checks into \
one validator.",
self.owner, self.name,
)));
return self;
}
self.validation.install::<A>(validator);
self
}
pub fn as_abstract(&mut self, reference: impl AbstractType) -> &mut Self {
let abstract_name: Name = Arc::from(reference.abstract_name());
let original = self
.sink
.get(&self.name)
.map_or_else(|| self.original().clone(), |field| field.ty.clone());
if let Some(checks) = &mut self.checks {
checks.push(FieldCheck::Abstract {
owner: self.owner.clone(),
field: self.name.clone(),
original,
abstract_name: abstract_name.clone(),
});
}
if let Some(field) = self.sink.get_mut(&self.name) {
field.ty = replace_named_type(&field.ty, abstract_name);
}
self
}
pub fn as_object_ref<M: ObjectModel>(&mut self, reference: &ObjectRef<M>) -> &mut Self {
self.registry.reference_object(reference.name());
if self.checks.is_some() {
let original = self.original().clone();
if let Some(checks) = &mut self.checks {
checks.push(FieldCheck::DynamicObject {
owner: self.owner.clone(),
field: self.name.clone(),
original,
model: M::NAME,
});
}
}
if let Some(field) = self.sink.get_mut(&self.name) {
field.ty = replace_named_type(&field.ty, Arc::from(reference.name()));
}
self
}
pub fn as_dynamic(&mut self, ty: TypeRef) -> &mut Self {
let current = self
.sink
.get(&self.name)
.map_or_else(|| self.original().clone(), |field| field.ty.clone());
if let Some(checks) = &mut self.checks {
checks.push(FieldCheck::DynamicType {
owner: self.owner.clone(),
field: self.name.clone(),
rust: current,
declared: ty.clone(),
});
}
if let Some(field) = self.sink.get_mut(&self.name) {
field.ty = ty;
}
self
}
pub fn as_type<T: OutputType>(&mut self) -> &mut Self {
self.override_type::<T>()
}
pub fn returns<T: OutputType>(&mut self) -> &mut Self {
self.override_type::<T>()
}
fn override_type<T: OutputType>(&mut self) -> &mut Self {
T::register_output(self.registry);
let replacement = T::output_type();
if self.checks.is_some() {
let original = self.original().clone();
if let Some(checks) = &mut self.checks {
checks.push(FieldCheck::TypeOverride {
owner: self.owner.clone(),
field: self.name.clone(),
original,
replacement: replacement.clone(),
});
}
}
if let Some(field) = self.sink.get_mut(&self.name) {
field.ty = replacement;
}
self
}
pub fn nullable(&mut self) -> &mut Self {
if let Some(field) = self.sink.get_mut(&self.name) {
if let TypeRef::NonNull(inner) = &field.ty {
field.ty = (**inner).clone();
}
}
self
}
pub fn non_null(&mut self) -> &mut Self {
if self.rust_nullable {
if let Some(checks) = &mut self.checks {
checks.push(FieldCheck::NonNullOnOption {
owner: self.owner.clone(),
field: self.name.clone(),
rust_type: self.rust_type_name,
});
}
}
if let Some(field) = self.sink.get_mut(&self.name) {
if !matches!(field.ty, TypeRef::NonNull(_)) {
field.ty = TypeRef::NonNull(Box::new(field.ty.clone()));
}
}
self
}
pub fn nullable_items(&mut self) -> &mut Self {
let Some(field) = self.sink.get_mut(&self.name) else {
return self;
};
match nullable_items(&field.ty) {
Some(ty) => field.ty = ty,
None => {
let ty = field.ty.clone();
if let Some(checks) = &mut self.checks {
checks.push(FieldCheck::NullableItemsOnNonList {
owner: self.owner.clone(),
field: self.name.clone(),
ty,
});
}
}
}
self
}
pub fn non_null_items(&mut self) -> &mut Self {
let Some(field) = self.sink.get_mut(&self.name) else {
return self;
};
match non_null_items(&field.ty) {
Some(ty) => field.ty = ty,
None => {
let ty = field.ty.clone();
if let Some(checks) = &mut self.checks {
checks.push(FieldCheck::NonNullItemsOnNonList {
owner: self.owner.clone(),
field: self.name.clone(),
ty,
});
}
}
}
self
}
}
impl<Ctx: 'static> Drop for FieldConfig<'_, Ctx> {
fn drop(&mut self) {
let Some(field) = self.sink.get_mut(&self.name) else {
return;
};
if let Some(description) = self.description.take() {
field.description = Some(description);
}
if let Some(deprecation) = self.deprecation.take() {
field.deprecation_reason = Some(deprecation);
}
if !self.directives.is_empty() {
field.directives.append(&mut self.directives);
}
if let Some(complexity) = self.complexity.take() {
field.complexity = Some(match complexity {
Complexity::Fixed(value) => Arc::new(move |_| value),
Complexity::Custom(function) => function,
});
}
if let Some(predicate) = self.auth.take() {
let guard = Arc::new(AuthGuard::new(predicate, self.auth_error.take()));
if let Some(field_auth) = &mut self.field_auth {
field_auth.insert(self.name.clone(), guard);
} else {
apply_auth_guard(field, guard);
}
}
}
}
pub struct InterfaceFieldConfig<'a, Ctx: 'static> {
inner: FieldConfig<'a, Ctx>,
}
impl<'a, Ctx: 'static> InterfaceFieldConfig<'a, Ctx> {
pub(crate) fn new(inner: FieldConfig<'a, Ctx>) -> Self {
Self { inner }
}
#[must_use]
pub fn name(&self) -> &str {
self.inner.name()
}
pub fn description(&mut self, description: impl Into<Arc<str>>) -> &mut Self {
self.inner.description(description);
self
}
pub fn deprecated(&mut self, reason: impl Into<Arc<str>>) -> &mut Self {
self.inner.deprecated(reason);
self
}
pub fn directive(&mut self, directive: AppliedDirective) -> &mut Self {
self.inner.directive(directive);
self
}
pub fn auth(&mut self, predicate: impl Fn(&Ctx) -> bool + Send + Sync + 'static) -> &mut Self {
self.inner.auth(predicate);
self
}
pub fn auth_async(
&mut self,
predicate: impl for<'r> Fn(&'r Ctx) -> BoxFuture<'r, bool> + Send + Sync + 'static,
) -> &mut Self {
self.inner.auth_async(predicate);
self
}
pub fn auth_error(&mut self, message: impl Into<Arc<str>>) -> &mut Self {
self.inner.auth_error(message);
self
}
}
impl<Ctx> std::fmt::Debug for FieldConfig<'_, Ctx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FieldConfig")
.field("name", &self.name)
.field("description", &self.description)
.field("deprecation", &self.deprecation)
.field("authorized", &self.auth.is_some())
.finish_non_exhaustive()
}
}
pub(crate) fn read_raw_field(
field_name: &str,
parent: &gql::Value,
) -> Result<gql::Value, GraphQLError> {
match parent {
gql::Value::Object(object) => {
Ok(object.get(field_name).cloned().unwrap_or(gql::Value::Null))
}
gql::Value::Null => Ok(gql::Value::Null),
gql::Value::External(_) => Err(GraphQLError::new(format!(
"Field \"{field_name}\" is a raw field with no resolver, but its parent is a model \
value, not a raw object. Resolve the parent with `Raw`, or declare the field with a \
resolver."
))),
other => Err(GraphQLError::new(format!(
"Field \"{field_name}\" is a raw field with no resolver and its parent is a {}, not \
an object.",
other.kind()
))),
}
}
pub(crate) fn install_property_resolver(field: &mut Field) {
if field.resolve.is_some() || field.subscribe.is_some() {
return;
}
field.resolve = Some(property_resolver(field.name.clone()));
}
pub(crate) fn property_resolver(name: Name) -> gql::ResolveFn {
Arc::new(move |context| {
let name = name.clone();
Box::pin(async move { read_raw_field(&name, context.parent) })
})
}
pub(crate) fn apply_auth_guard<Ctx: 'static>(field: &mut Field, guard: Arc<AuthGuard<Ctx>>) {
install_property_resolver(field);
let resolve_guard = Arc::clone(&guard);
if let Some(resolve) = field.resolve.take() {
field.resolve = Some(Arc::new(move |context| {
let resolve = Arc::clone(&resolve);
let guard = Arc::clone(&resolve_guard);
Box::pin(async move {
let ctx = context.context.require_data::<Ctx>()?;
guard.check(ctx).await?;
let _span = crate::telemetry::span_if_enabled!(
tracing::Level::TRACE,
"gurafi",
"gurafi.resolver",
parent_type = context.info.parent_type,
field = context.info.field_name,
);
crate::telemetry::instrument_span!(_span.clone(), resolve(context)).await
})
}));
}
if let Some(subscribe) = field.subscribe.take() {
field.subscribe = Some(Arc::new(move |context| {
let subscribe = Arc::clone(&subscribe);
let guard = Arc::clone(&guard);
Box::pin(async move {
let ctx = context.context.require_data::<Ctx>()?;
guard.check(ctx).await?;
subscribe(context).await
})
}));
}
}
pub(crate) fn sync_guard<Ctx: 'static>(
predicate: impl Fn(&Ctx) -> bool + Send + Sync + 'static,
message: Option<Arc<str>>,
) -> Arc<AuthGuard<Ctx>> {
Arc::new(AuthGuard::new(
GuardPredicate::Sync(Arc::new(predicate)),
message,
))
}
pub(crate) fn async_guard<Ctx: 'static>(
predicate: impl for<'r> Fn(&'r Ctx) -> BoxFuture<'r, bool> + Send + Sync + 'static,
message: Option<Arc<str>>,
) -> Arc<AuthGuard<Ctx>> {
Arc::new(AuthGuard::new(
GuardPredicate::Async(Arc::new(predicate)),
message,
))
}
fn replace_named_type(ty: &TypeRef, name: Name) -> TypeRef {
match ty {
TypeRef::Named(_) => TypeRef::Named(name),
TypeRef::List(inner) => TypeRef::List(Box::new(replace_named_type(inner, name))),
TypeRef::NonNull(inner) => TypeRef::NonNull(Box::new(replace_named_type(inner, name))),
}
}
fn non_null_items(ty: &TypeRef) -> Option<TypeRef> {
match ty {
TypeRef::NonNull(inner) => non_null_items(inner).map(|ty| TypeRef::NonNull(Box::new(ty))),
TypeRef::List(inner) => Some(TypeRef::List(match inner.as_ref() {
TypeRef::NonNull(_) => inner.clone(),
other => Box::new(TypeRef::NonNull(Box::new(other.clone()))),
})),
TypeRef::Named(_) => None,
}
}
fn nullable_items(ty: &TypeRef) -> Option<TypeRef> {
match ty {
TypeRef::NonNull(inner) => nullable_items(inner).map(|ty| TypeRef::NonNull(Box::new(ty))),
TypeRef::List(inner) => Some(TypeRef::List(match inner.as_ref() {
TypeRef::NonNull(item) => item.clone(),
other => Box::new(other.clone()),
})),
TypeRef::Named(_) => None,
}
}