Skip to content

Added support for reference resolvers on an entity interface. #8425

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,19 @@ public override void OnAfterInitialize(
objectType,
objectTypeCfg,
discoveryContext);
return;
}

if (discoveryContext.Type is InterfaceType interfaceType
&& configuration is InterfaceTypeConfiguration interfaceTypeCfg)
{
ApplyMethodLevelReferenceResolvers(
interfaceType,
interfaceTypeCfg);

AggregatePropertyLevelKeyDirectives(
interfaceTypeCfg,
discoveryContext);
}
}

Expand Down Expand Up @@ -345,12 +358,23 @@ public override void OnAfterMakeExecutable(
{
CompleteExternalFieldSetters(type, typeCfg);
CompleteReferenceResolver(typeCfg);
return;
}

if (completionContext.Type is InterfaceType interfaceType
&& configuration is InterfaceTypeConfiguration interfaceTypeCfg)
{
CompleteExternalFieldSetters(interfaceType, interfaceTypeCfg);
CompleteReferenceResolver(interfaceTypeCfg);
}
}

private void CompleteExternalFieldSetters(ObjectType type, ObjectTypeConfiguration typeCfg)
=> ExternalSetterExpressionHelper.TryAddExternalSetter(type, typeCfg);

private void CompleteExternalFieldSetters(InterfaceType type, InterfaceTypeConfiguration typeCfg)
=> ExternalSetterExpressionHelper.TryAddExternalSetter(type, typeCfg);

private void CompleteReferenceResolver(ObjectTypeConfiguration typeCfg)
{
var resolvers = typeCfg.Features.Get<List<ReferenceResolverConfiguration>>();
Expand Down Expand Up @@ -398,6 +422,53 @@ private void CompleteReferenceResolver(ObjectTypeConfiguration typeCfg)
}
}

private void CompleteReferenceResolver(InterfaceTypeConfiguration typeCfg)
{
var resolvers = typeCfg.Features.Get<List<ReferenceResolverConfiguration>>();

if (resolvers is null)
{
return;
}

if (resolvers.Count == 1)
{
typeCfg.Features.Set(new ReferenceResolver(resolvers[0].Resolver));
}
else
{
var expressions = new Stack<(Expression Condition, Expression Execute)>();
var context = Expression.Parameter(typeof(IResolverContext));

foreach (var resolverDef in resolvers)
{
Expression required = Expression.Constant(resolverDef.Required);
Expression resolver = Expression.Constant(resolverDef.Resolver);
Expression condition = Expression.Call(s_matches, context, required);
Expression execute = Expression.Call(s_execute, context, resolver);
expressions.Push((condition, execute));
}

Expression current = Expression.Call(s_invalid, context);
var variable = Expression.Variable(typeof(ValueTask<object?>));

while (expressions.Count > 0)
{
var expression = expressions.Pop();
current = Expression.IfThenElse(
expression.Condition,
Expression.Assign(variable, expression.Execute),
current);
}

current = Expression.Block([variable], current, variable);

typeCfg.Features.Set(
new ReferenceResolver(
Expression.Lambda<FieldResolverDelegate>(current, context).Compile()));
}
}

private void AddServiceTypeToQueryType(
ITypeCompletionContext completionContext,
TypeSystemConfiguration? definition)
Expand Down Expand Up @@ -452,6 +523,43 @@ private void ApplyMethodLevelReferenceResolvers(
descriptor.CreateConfiguration();
}

private void ApplyMethodLevelReferenceResolvers(
InterfaceType interfaceType,
InterfaceTypeConfiguration interfaceTypeCfg)
{
if (interfaceType.RuntimeType == typeof(object))
{
return;
}

var descriptor = InterfaceTypeDescriptor.From(_context, interfaceTypeCfg);

// Static methods won't end up in the schema as fields.
// The default initialization system only considers instance methods,
// so we have to handle the attributes for those manually.
var potentiallyUnregisteredReferenceResolvers = interfaceType.RuntimeType
.GetMethods(BindingFlags.Static | BindingFlags.Public);

foreach (var possibleReferenceResolver in potentiallyUnregisteredReferenceResolvers)
{
if (!possibleReferenceResolver.IsDefined(typeof(ReferenceResolverAttribute)))
{
continue;
}

foreach (var attribute in possibleReferenceResolver.GetCustomAttributes(true))
{
if (attribute is ReferenceResolverAttribute casted)
{
casted.TryConfigure(_context, descriptor, possibleReferenceResolver);
}
}
}

// This seems to re-detect the entity resolver and save it into the context data.
descriptor.CreateConfiguration();
}

private void AddToUnionIfHasTypeLevelKeyDirective(
ObjectType objectType,
ObjectTypeConfiguration objectTypeCfg)
Expand Down Expand Up @@ -532,6 +640,61 @@ private void AggregatePropertyLevelKeyDirectives(
}
}

private void AggregatePropertyLevelKeyDirectives(
InterfaceTypeConfiguration interfaceTypeCfg,
ITypeDiscoveryContext discoveryContext)
{
// if we find key markers on our fields, we need to construct the key directive
// from the annotated fields.
var foundMarkers = interfaceTypeCfg.Fields.Any(f => f.Features.TryGet(out KeyMarker? _));

if (!foundMarkers)
{
return;
}

IReadOnlyList<InterfaceFieldConfiguration> fields = interfaceTypeCfg.Fields;
var fieldSet = new StringBuilder();
bool? resolvable = null;

foreach (var fieldDefinition in fields)
{
if (fieldDefinition.Features.TryGet(out KeyMarker? key))
{
if (resolvable is null)
{
resolvable = key.Resolvable;
}
else if (resolvable != key.Resolvable)
{
throw Key_FieldSet_ResolvableMustBeConsistent(fieldDefinition.Member!);
}

if (fieldSet.Length > 0)
{
fieldSet.Append(' ');
}

fieldSet.Append(fieldDefinition.Name);
}
}

// add the key directive with the dynamically generated field set.
AddKeyDirective(interfaceTypeCfg, fieldSet.ToString(), resolvable ?? true);

// register dependency to the key directive so that it is completed before
// we complete this type.
foreach (var directiveDefinition in interfaceTypeCfg.Directives)
{
discoveryContext.Dependencies.Add(
new TypeDependency(
directiveDefinition.Type,
TypeDependencyFulfilled.Completed));

discoveryContext.Dependencies.Add(new(directiveDefinition.Type));
}
}

private void AddMemberTypesToTheEntityUnionType(
ITypeCompletionContext completionContext,
TypeSystemConfiguration? definition)
Expand All @@ -556,4 +719,15 @@ private void AddKeyDirective(
new KeyDirective(fieldSet, resolvable),
_keyDirectiveReference));
}

private void AddKeyDirective(
InterfaceTypeConfiguration interfaceTypeCfg,
string fieldSet,
bool resolvable)
{
interfaceTypeCfg.Directives.Add(
new DirectiveConfiguration(
new KeyDirective(fieldSet, resolvable),
_keyDirectiveReference));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,24 @@ internal static class EntitiesResolver
entityContext.SetLocalState(DataField, current.Data);

tasks[i] = entity.Resolver.Invoke(entityContext).AsTask();
continue;
}
else

if (schema.Types.TryGetType<InterfaceType>(current.TypeName, out var interfaceType)
&& interfaceType.Features.TryGet(out ReferenceResolver? entityInterface))
{
throw ThrowHelper.EntityResolver_NoResolverFound();
// We clone the resolver context here so that we can split the work
// into subtasks that can be awaited in parallel and produce separate results.
var entityContext = context.Clone();

entityContext.SetLocalState(TypeField, interfaceType);
entityContext.SetLocalState(DataField, current.Data);

tasks[i] = entityInterface.Resolver.Invoke(entityContext).AsTask();
continue;
}

throw ThrowHelper.EntityResolver_NoResolverFound();
}

for (var i = 0; i < representations.Count; i++)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,30 @@ public static void TryAddExternalSetter(ObjectType type, ObjectTypeConfiguration
}
}

public static void TryAddExternalSetter(InterfaceType type, InterfaceTypeConfiguration typeDef)
{
List<Expression>? block = null;

foreach (var field in type.Fields)
{
if (field.Directives.ContainsDirective<ExternalDirective>()
&& typeDef.Fields.FirstOrDefault(f => f.Name == field.Name) is
{ Member: PropertyInfo { SetMethod: not null } property })
{
var expression = CreateTrySetValue(type.RuntimeType, property, field.Name);
(block ??= []).Add(expression);
}
}

if (block is not null)
{
typeDef.Features.Set(new ExternalSetter(
Lambda<Action<ObjectType, IValueNode, object>>(
Block(block), s_type, s_data, s_entity)
.Compile()));
}
}

private static Expression CreateTrySetValue(
Type runtimeType,
PropertyInfo property,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ internal sealed class ReferenceResolverArgumentExpressionBuilder :
nameof(ArgumentParser.GetValue),
BindingFlags.Static | BindingFlags.Public)!;

private readonly Type _targetType;

public ReferenceResolverArgumentExpressionBuilder(Type targetType)
{
ArgumentNullException.ThrowIfNull(targetType);
_targetType = targetType;
}

public override Expression Build(ParameterExpressionBuilderContext context)
{
var param = context.Parameter;
Expand All @@ -35,7 +43,7 @@ public override Expression Build(ParameterExpressionBuilderContext context)
param,
typeKey,
context.ResolverContext,
typeof(ObjectType));
_targetType);
var getValueMethod = _getValue.MakeGenericMethod(param.ParameterType);
var getValue = Expression.Call(
getValueMethod,
Expand Down
Loading
Loading