|
| 1 | +using System; |
| 2 | +using System.Net; |
| 3 | +using System.Reflection; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using ManagedCode.Communication.Helpers; |
| 6 | +using ManagedCode.Communication.Results; |
| 7 | +using Orleans; |
| 8 | + |
| 9 | +namespace ManagedCode.Communication.Filters; |
| 10 | + |
| 11 | +internal static class CommunicationGrainCallResultFactory |
| 12 | +{ |
| 13 | + private static readonly MethodInfo CreateFailureGenericMethod = |
| 14 | + typeof(CommunicationGrainCallResultFactory).GetMethod( |
| 15 | + nameof(CreateFailureGeneric), |
| 16 | + BindingFlags.NonPublic | BindingFlags.Static) |
| 17 | + ?? throw new MissingMethodException(nameof(CommunicationGrainCallResultFactory), nameof(CreateFailureGeneric)); |
| 18 | + |
| 19 | + public static bool TrySetFailure(IGrainCallContext context, Exception exception) |
| 20 | + { |
| 21 | + var resultType = GetCommunicationResultType(context.InterfaceMethod.ReturnType); |
| 22 | + if (resultType is null) |
| 23 | + { |
| 24 | + return false; |
| 25 | + } |
| 26 | + |
| 27 | + var statusCode = OrleansHttpStatusCodeHelper.GetStatusCodeForException(exception); |
| 28 | + context.Result = CreateFailure(resultType, exception, statusCode); |
| 29 | + return true; |
| 30 | + } |
| 31 | + |
| 32 | + private static Type? GetCommunicationResultType(Type returnType) |
| 33 | + { |
| 34 | + if (!returnType.IsGenericType) |
| 35 | + { |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + var genericDefinition = returnType.GetGenericTypeDefinition(); |
| 40 | + if (genericDefinition != typeof(Task<>) && genericDefinition != typeof(ValueTask<>)) |
| 41 | + { |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + var resultType = returnType.GenericTypeArguments[0]; |
| 46 | + if (!typeof(IResult).IsAssignableFrom(resultType)) |
| 47 | + { |
| 48 | + return null; |
| 49 | + } |
| 50 | + |
| 51 | + var resultFactoryType = typeof(IResultFactory<>).MakeGenericType(resultType); |
| 52 | + return resultFactoryType.IsAssignableFrom(resultType) ? resultType : null; |
| 53 | + } |
| 54 | + |
| 55 | + private static object CreateFailure(Type resultType, Exception exception, HttpStatusCode statusCode) |
| 56 | + { |
| 57 | + var genericMethod = CreateFailureGenericMethod.MakeGenericMethod(resultType); |
| 58 | + return genericMethod.Invoke(obj: null, [exception, statusCode]) |
| 59 | + ?? throw new InvalidOperationException(resultType.FullName); |
| 60 | + } |
| 61 | + |
| 62 | + private static TSelf CreateFailureGeneric<TSelf>(Exception exception, HttpStatusCode statusCode) |
| 63 | + where TSelf : struct, IResultFactory<TSelf> |
| 64 | + { |
| 65 | + return TSelf.Fail(exception, statusCode); |
| 66 | + } |
| 67 | +} |
0 commit comments