|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System.Reflection; |
| 5 | +using Microsoft.AspNetCore.Mvc; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.IO; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Azure.CloudMachine; |
| 10 | +using Microsoft.AspNetCore.Http; |
| 11 | +using Microsoft.AspNetCore.Routing; |
| 12 | +using Microsoft.AspNetCore.Builder; |
| 13 | + |
| 14 | +namespace System.ClientModel.TypeSpec; |
| 15 | + |
| 16 | +/// <summary> |
| 17 | +/// ASp.NET Core extension methods for mapping a service implementation to a set of HTTP endpoints. |
| 18 | +/// </summary> |
| 19 | +public static class CloudMachineExtensions |
| 20 | +{ |
| 21 | + /// <summary> |
| 22 | + /// Uploads a document to the storage service. |
| 23 | + /// </summary> |
| 24 | + /// <param name="storage"></param> |
| 25 | + /// <param name="multiPartFormData"></param> |
| 26 | + /// <returns></returns> |
| 27 | + public static async Task UploadFormAsync(this StorageServices storage, HttpRequest multiPartFormData) |
| 28 | + { |
| 29 | + IFormCollection form = await multiPartFormData.ReadFormAsync().ConfigureAwait(false); |
| 30 | + IFormFile? file = form.Files.GetFile("file"); |
| 31 | + Stream? fileStram = file!.OpenReadStream(); |
| 32 | + await storage.UploadAsync(fileStram, file.FileName, file.ContentType, overwrite: true).ConfigureAwait(false); |
| 33 | + } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Maps a service implementation to a set of HTTP endpoints. |
| 37 | + /// </summary> |
| 38 | + /// <typeparam name="T"></typeparam> |
| 39 | + /// <param name="routeBuilder"></param> |
| 40 | + /// <param name="serviceImplementation"></param> |
| 41 | + public static void Map<T>(this IEndpointRouteBuilder routeBuilder, T serviceImplementation) where T : class |
| 42 | + { |
| 43 | + Type serviceImplementationType = typeof(T); |
| 44 | + Type serviceDescriptor = GetServiceDescriptor(serviceImplementationType); |
| 45 | + MethodInfo[] serviceOperations = serviceDescriptor.GetMethods(); |
| 46 | + foreach (MethodInfo serviceOperation in serviceOperations) |
| 47 | + { |
| 48 | + RequestDelegate handler = CreateRequestDelegate(serviceImplementation, serviceOperation); |
| 49 | + string name = serviceOperation.Name; |
| 50 | + if (name.EndsWith("Async")) |
| 51 | + name = name.Substring(0, name.Length - "Async".Length); |
| 52 | + routeBuilder.Map($"/{name}", handler); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + private static Type GetServiceDescriptor(Type serviceImplementation) |
| 57 | + { |
| 58 | + Type[] interfaces = serviceImplementation.GetInterfaces(); |
| 59 | + if (interfaces.Length != 1) |
| 60 | + throw new InvalidOperationException($"Service {serviceImplementation} must implement exactly one interface"); |
| 61 | + Type interfaceType = interfaces[0]; |
| 62 | + return interfaceType; |
| 63 | + } |
| 64 | + |
| 65 | + private static RequestDelegate CreateRequestDelegate<T>(T service, MethodInfo implementationMethod) where T : class |
| 66 | + { |
| 67 | + return async (HttpContext context) => { |
| 68 | + HttpRequest request = context.Request; |
| 69 | + |
| 70 | + Type serviceType = service.GetType(); |
| 71 | + Type interfaceType = GetServiceDescriptor(serviceType); |
| 72 | + MethodInfo? interfaceMethod = interfaceType.GetMethod(implementationMethod.Name, BindingFlags.Public | BindingFlags.Instance); |
| 73 | + |
| 74 | + ParameterInfo[] parameters = interfaceMethod!.GetParameters(); |
| 75 | + object[] implementationArguments = new object[parameters.Length]; |
| 76 | + |
| 77 | + foreach (var parameter in parameters) |
| 78 | + { |
| 79 | + implementationArguments[0] = await CreateArgumentAsync(parameter, request).ConfigureAwait(false); |
| 80 | + } |
| 81 | + |
| 82 | + // deal with async APIs |
| 83 | + object? implementationReturnValue = implementationMethod.Invoke(service, implementationArguments); |
| 84 | + if (implementationReturnValue != default) |
| 85 | + { |
| 86 | + Task? task = implementationReturnValue as Task; |
| 87 | + if (task != default) |
| 88 | + { |
| 89 | + await task.ConfigureAwait(false); |
| 90 | + implementationReturnValue = task.GetType().GetProperty("Result")!.GetValue(task); |
| 91 | + } |
| 92 | + else |
| 93 | + { // TODO: we need to deal with ValueTask too |
| 94 | + implementationReturnValue = default; |
| 95 | + } |
| 96 | + } |
| 97 | + else |
| 98 | + { |
| 99 | + Debug.Assert(implementationArguments.Length == 0); |
| 100 | + } |
| 101 | + |
| 102 | + HttpResponse response = context.Response; |
| 103 | + response.StatusCode = 200; |
| 104 | + if (implementationReturnValue != default) |
| 105 | + { |
| 106 | + BinaryData responseBody = Serialize(implementationReturnValue); |
| 107 | + response.ContentLength = responseBody.ToMemory().Length; |
| 108 | + response.ContentType = "application/json"; |
| 109 | + await response.Body.WriteAsync(responseBody.ToArray()).ConfigureAwait(false); |
| 110 | + } |
| 111 | + }; |
| 112 | + } |
| 113 | + |
| 114 | + private static async ValueTask<object> CreateArgumentAsync(ParameterInfo parameter, HttpRequest request) |
| 115 | + { |
| 116 | + Type parameterType = parameter.ParameterType; |
| 117 | + |
| 118 | + if (parameterType == typeof(HttpRequest)) |
| 119 | + { |
| 120 | + return request; |
| 121 | + } |
| 122 | + |
| 123 | + if (parameterType == typeof(Stream)) |
| 124 | + { |
| 125 | + return request.Body; |
| 126 | + } |
| 127 | + |
| 128 | + if (parameterType == typeof(byte[])) |
| 129 | + { |
| 130 | + var bd = await BinaryData.FromStreamAsync(request.Body).ConfigureAwait(false); |
| 131 | + return bd.ToArray(); |
| 132 | + } |
| 133 | + if (parameterType == typeof(BinaryData)) |
| 134 | + { |
| 135 | + string? contentType = request.ContentType; |
| 136 | + var bd = await BinaryData.FromStreamAsync(request.Body, contentType).ConfigureAwait(false); |
| 137 | + return bd; |
| 138 | + } |
| 139 | + if (parameterType == typeof(string)) |
| 140 | + { |
| 141 | + return await new StreamReader(request.Body).ReadToEndAsync().ConfigureAwait(false); |
| 142 | + } |
| 143 | + |
| 144 | + FromQueryAttribute? fqa = parameter.GetCustomAttribute<FromQueryAttribute>(); |
| 145 | + if (fqa != default) |
| 146 | + { |
| 147 | + string? queryValue = request.Query[parameter.Name!]; |
| 148 | + return Convert.ChangeType(queryValue!, parameterType); |
| 149 | + } |
| 150 | + |
| 151 | + FromHeaderAttribute? fha = parameter.GetCustomAttribute<FromHeaderAttribute>(); |
| 152 | + if (fha != default) |
| 153 | + { |
| 154 | + var headerName = fha.Name ?? parameter.Name; |
| 155 | + string? headerValue = request.Headers[headerName!]; |
| 156 | + return Convert.ChangeType(headerValue!, parameterType); |
| 157 | + } |
| 158 | + |
| 159 | + object deserialized = DeserializeModel(parameterType, request.Body); |
| 160 | + return deserialized; |
| 161 | + } |
| 162 | + |
| 163 | + // TODO: this is a hack. We should use MRW |
| 164 | + private static object DeserializeModel(Type modelType, Stream stream) |
| 165 | + { |
| 166 | + var fromJson = modelType.GetMethod("FromJson", BindingFlags.Static); |
| 167 | + if (fromJson == default) |
| 168 | + throw new InvalidOperationException($"{modelType} does not provide FromJson static method"); |
| 169 | + object? deserialized = fromJson.Invoke(null, new object[] { stream }); |
| 170 | + if (deserialized == default) |
| 171 | + throw new InvalidOperationException($"Failed to deserialize {modelType}"); |
| 172 | + return deserialized; |
| 173 | + } |
| 174 | + |
| 175 | + private static BinaryData Serialize(object implementationReturnValue) |
| 176 | + { |
| 177 | + Type type = implementationReturnValue.GetType(); |
| 178 | + if (type.IsGenericType) |
| 179 | + { |
| 180 | + if (type.GetGenericTypeDefinition() == typeof(ValueTask<>)) |
| 181 | + { |
| 182 | + } |
| 183 | + if (type.GetGenericTypeDefinition() == typeof(Task<>)) |
| 184 | + { |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + BinaryData bd = BinaryData.FromObjectAsJson(implementationReturnValue); |
| 189 | + return bd; |
| 190 | + } |
| 191 | +} |
0 commit comments