|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Linq; |
| 4 | +using System.Net; |
| 5 | +using System.Net.Http; |
| 6 | +using System.Text; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Microsoft.AspNetCore.Http; |
| 9 | +//using QueryCollection = Microsoft.AspNetCore.Http.QueryCollection; |
| 10 | +using Microsoft.AspNetCore.WebUtilities; |
| 11 | +using Microsoft.Azure.Functions.Worker.Http; |
| 12 | +using Microsoft.Extensions.Primitives; |
| 13 | + |
| 14 | +namespace HotChocolate.AzureFunctionsProxy |
| 15 | +{ |
| 16 | + public class GraphQLHttpContextShim : IDisposable, IAsyncDisposable |
| 17 | + { |
| 18 | + protected HttpContext HttpContextShim { get; set; } |
| 19 | + |
| 20 | + public HttpRequestData IsolatedProcessHttpRequestData { get; protected set; } |
| 21 | + |
| 22 | + public string ContentType { get; protected set; } |
| 23 | + |
| 24 | + public GraphQLHttpContextShim(HttpRequestData httpRequestData) |
| 25 | + { |
| 26 | + this.IsolatedProcessHttpRequestData = httpRequestData ?? throw new ArgumentNullException(nameof(httpRequestData)); |
| 27 | + this.ContentType = httpRequestData.GetContentType(); |
| 28 | + } |
| 29 | + |
| 30 | + /// <summary> |
| 31 | + /// Create an HttpContext (AspNetCore compatible) that can be provided to the AzureFunctionsProxy for GraphQL execution. |
| 32 | + /// All pertinent data from the HttpRequestData provided by the Azure Functions Isolated Process will be marshalled |
| 33 | + /// into the HttpContext for HotChocolate to consume. |
| 34 | + /// </summary> |
| 35 | + /// <returns></returns> |
| 36 | + public virtual async Task<HttpContext> CreateGraphQLHttpContextAsync() |
| 37 | + { |
| 38 | + var httpRequestData = this.IsolatedProcessHttpRequestData; |
| 39 | + |
| 40 | + var httpContextShim = BuildGraphQLHttpContext( |
| 41 | + requestHttpMethod: httpRequestData.Method, |
| 42 | + requestUri: httpRequestData.Url, |
| 43 | + requestHeadersCollection: httpRequestData.Headers, |
| 44 | + requestBody: await httpRequestData.ReadAsStringAsync().ConfigureAwait(false), |
| 45 | + requestBodyContentType: httpRequestData.GetContentType() |
| 46 | + ); |
| 47 | + |
| 48 | + //Ensure we track the HttpContext internally for cleanup when disposed! |
| 49 | + this.HttpContextShim = httpContextShim; |
| 50 | + return httpContextShim; |
| 51 | + } |
| 52 | + |
| 53 | + protected virtual HttpContext BuildGraphQLHttpContext( |
| 54 | + string requestHttpMethod, |
| 55 | + Uri requestUri, |
| 56 | + HttpHeadersCollection requestHeadersCollection, |
| 57 | + string requestBody = null, |
| 58 | + string requestBodyContentType = "application/json" |
| 59 | + ) |
| 60 | + { |
| 61 | + //Initialize the root Http Context (Container)... |
| 62 | + var httpContext = new DefaultHttpContext(); |
| 63 | + |
| 64 | + //Initialize the Http Request... |
| 65 | + var httpRequest = httpContext.Request; |
| 66 | + httpRequest.Scheme = requestUri.Scheme; |
| 67 | + httpRequest.Path = new PathString(requestUri.AbsolutePath); |
| 68 | + httpRequest.Method = requestHttpMethod ?? HttpMethod.Post.Method; |
| 69 | + httpRequest.QueryString = new QueryString(requestUri.Query); |
| 70 | + |
| 71 | + //Ensure we marshall across all Headers from teh Client Request... |
| 72 | + if (requestHeadersCollection?.Any() == true) |
| 73 | + foreach(var header in requestHeadersCollection) |
| 74 | + httpRequest.Headers.Add(header.Key, new StringValues(header.Value.ToArray())); |
| 75 | + |
| 76 | + if (!string.IsNullOrEmpty(requestBody)) |
| 77 | + { |
| 78 | + //Initialize a valid Stream for the Request (must be tracked & Disposed of!) |
| 79 | + var requestBodyBytes = Encoding.UTF8.GetBytes(requestBody); |
| 80 | + httpRequest.Body = new MemoryStream(requestBodyBytes); |
| 81 | + httpRequest.ContentType = requestBodyContentType; |
| 82 | + httpRequest.ContentLength = requestBodyBytes.Length; |
| 83 | + } |
| 84 | + |
| 85 | + //Initialize the Http Response... |
| 86 | + var httpResponse = httpContext.Response; |
| 87 | + //Initialize a valid Stream for the Response (must be tracked & Disposed of!) |
| 88 | + //NOTE: Default Body is a NullStream...which ignores all Reads/Writes. |
| 89 | + httpResponse.Body = new MemoryStream(); |
| 90 | + |
| 91 | + return httpContext; |
| 92 | + } |
| 93 | + |
| 94 | + /// <summary> |
| 95 | + /// Create an HttpResponseData containing the proxied GraphQL results; marshalled back from |
| 96 | + /// the HttpContext that HotChocolate populates. |
| 97 | + /// </summary> |
| 98 | + /// <returns></returns> |
| 99 | + public async Task<HttpResponseData> CreateHttpResponseDataAsync() |
| 100 | + { |
| 101 | + var graphqlResponseBytes = ReadResponseBytes(); |
| 102 | + var httpContext = this.HttpContextShim; |
| 103 | + var httpStatusCode = (HttpStatusCode)httpContext.Response.StatusCode; |
| 104 | + |
| 105 | + //Initialize the Http Response... |
| 106 | + var httpRequestData = this.IsolatedProcessHttpRequestData; |
| 107 | + var response = httpRequestData.CreateResponse(httpStatusCode); |
| 108 | + |
| 109 | + //Marshall over all Headers from the HttpContext... |
| 110 | + //Note: This should also handle Cookies (not tested).... |
| 111 | + var responseHeaders = httpContext.Response?.Headers; |
| 112 | + if (responseHeaders?.Any() == true) |
| 113 | + foreach (var header in responseHeaders) |
| 114 | + response.Headers.Add(header.Key, header.Value.Select(sv => sv.ToString())); |
| 115 | + |
| 116 | + //Marshall the original response Bytes from HotChocolate... |
| 117 | + //Note: This enables full support for GraphQL Json results/errors, binary downloads, SDL, & BCP binary data. |
| 118 | + await response.WriteBytesAsync(graphqlResponseBytes).ConfigureAwait(false); |
| 119 | + |
| 120 | + return response; |
| 121 | + } |
| 122 | + |
| 123 | + public byte[] ReadResponseBytes() |
| 124 | + { |
| 125 | + if (HttpContextShim?.Response?.Body is not MemoryStream responseMemoryStream) |
| 126 | + return null; |
| 127 | + |
| 128 | + var bytes = responseMemoryStream.ToArray(); |
| 129 | + return bytes; |
| 130 | + |
| 131 | + } |
| 132 | + |
| 133 | + public virtual string ReadResponseContentAsString() |
| 134 | + { |
| 135 | + var responseContent = Encoding.UTF8.GetString(ReadResponseBytes()); |
| 136 | + return responseContent; |
| 137 | + } |
| 138 | + |
| 139 | + public ValueTask DisposeAsync() |
| 140 | + { |
| 141 | + this.Dispose(); |
| 142 | + return ValueTask.CompletedTask; |
| 143 | + } |
| 144 | + |
| 145 | + public virtual void Dispose() |
| 146 | + { |
| 147 | + DisposeHttpContext(); |
| 148 | + GC.SuppressFinalize(this); |
| 149 | + } |
| 150 | + |
| 151 | + protected virtual void DisposeHttpContext() |
| 152 | + { |
| 153 | + var httpContext = this.HttpContextShim; |
| 154 | + httpContext?.Request?.Body?.Dispose(); |
| 155 | + httpContext?.Response?.Body?.Dispose(); |
| 156 | + |
| 157 | + this.HttpContextShim = null; |
| 158 | + } |
| 159 | + } |
| 160 | +} |
0 commit comments