private async Task WriteResponsesAsync(HttpContext context, IDocumentWriter writer, ExecutionResult[] results)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = 200;

            if (results.Length == 1)
            {
                await writer.WriteAsync(context.Response.Body, results[0]);

                return;
            }

            using (var sw = new StreamWriter(context.Response.Body, Encoding.UTF8))
            {
                sw.AutoFlush = true;
                sw.Write("[");
                for (int i = 0; i <= results.Length - 2; i++)
                {
                    await writer.WriteAsync(context.Response.Body, results[i]);

                    sw.Write(",");
                }
                await writer.WriteAsync(context.Response.Body, results[results.Length - 1]);

                sw.Write("]");
            }
        }
Example #2
0
        private async Task WriteResponseAsync(HttpContext context, ExecutionResult executionResult)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = executionResult.Errors?.Any() == true ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.OK;

            await _documentWriter.WriteAsync(context.Response.Body, executionResult);
        }
Example #3
0
        public async Task InvokeAsync(HttpContext httpContext, ISchema schema)
        {
            if (
                !httpContext.Request.Path.StartsWithSegments(_options.EndPoint) ||
                !string.Equals(httpContext.Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
            {
                await _next(httpContext);

                return;
            }

            var request = await JsonSerializer.DeserializeAsync <GraphQLRequest>(
                httpContext.Request.Body,
                new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            }
                );

            var result = await _executor.ExecuteAsync(doc =>
            {
                doc.Schema        = schema;
                doc.Query         = request.Query;
                doc.Inputs        = request.Variables.ToInputs();
                doc.OperationName = request.OperationName;
            }).ConfigureAwait(false);

            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode  = 200;

            await _writer.WriteAsync(httpContext.Response.Body, result);
        }
Example #4
0
        private Task WriteResponseAsync(HttpContext context, IDocumentWriter writer, ExecutionResult result)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = 200; // OK

            return(writer.WriteAsync(context.Response.Body, result));
        }
Example #5
0
        private async Task WriteResponseAsync(HttpContext context, ExecutionResult result)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = 200; // OK

            await _writer.WriteAsync(context.Response.Body, result);
        }
Example #6
0
        private static Task WriteUnauthorizedResponseAsync(HttpContext context, IDocumentWriter writer, ExecutionResult result)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)HttpStatusCode.Unauthorized;

            return(writer.WriteAsync(context.Response.Body, result));
        }
Example #7
0
        private Task WriteResponseAsync(HttpContext context, IDocumentWriter writer, ExecutionResult result)
        {
            context.Response.ContentType = JsonContentType;
            context.Response.StatusCode  = (int)HttpStatusCode.OK;

            return(writer.WriteAsync(context.Response.Body, result));
        }
        private Task WriteResponseAsync <T>(HttpContext context, IDocumentWriter writer, T result) where T : class
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = 200; // OK


            return(writer.WriteAsync(context.Response.Body, result));
        }
Example #9
0
        public async Task <HttpResponseMessage> PostAsync(HttpRequestMessage request, GraphQLQuery query, CancellationToken cancellation)
        {
            var inputs         = query?.Variables?.ToInputs();
            var queryToExecute = query.Query;

            if (!string.IsNullOrWhiteSpace(query.NamedQuery))
            {
                queryToExecute = _namedQueries[query.NamedQuery];
            }

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema        = _schema;
                _.Query         = queryToExecute;
                _.OperationName = query.OperationName;
                _.Inputs        = inputs;

                _.ComplexityConfiguration = new ComplexityConfiguration {
                    MaxDepth = 15
                };
                _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
                _.CancellationToken = cancellation;
#if (DEBUG)
                _.ExposeExceptions = true;
                _.EnableMetrics    = true;
#endif
            }).ConfigureAwait(false);

            var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;

            var response = request.CreateResponse(httpResult);

            var stream = new MemoryStream();

            await _writer.WriteAsync(stream, result);

            stream.Position = 0L;

            response.Content = new StreamContent(stream);

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); // MimeMapping.GetMimeMapping(imagePath)

            return(response);
        }
Example #10
0
        private async Task WriteResponseAsync(HttpContext context, ExecutionResult result)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = result.Errors?.Any() == true ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.OK;

            // Console.WriteLine("E");
            Console.WriteLine();
            await _writer.WriteAsync(context.Response.Body, result);
        }
        /// <summary>
        /// Writes the <paramref name="value"/> to string.
        /// </summary>
        public static async Task <string> WriteToStringAsync <T>(this IDocumentWriter writer, T value)
        {
            using var stream = new MemoryStream();
            await writer.WriteAsync(stream, value).ConfigureAwait(false);

            stream.Position  = 0;
            using var reader = new StreamReader(stream, _utf8Encoding);
            return(await reader.ReadToEndAsync().ConfigureAwait(false));
        }
Example #12
0
        public async Task ProcessAsync(EventData m)
        {
            var message = messageParser.MessageToRawMessage(m);

            logger.Debug("Saving message...", () => { });
            await documentWriter.WriteAsync(MessageToDocument(message));

            logger.Debug("Analyzing message...", () => { });
            await alarms.ProcessAsync(message);
        }
Example #13
0
        private async Task WriteResponseAsync(HttpContext context, ExecutionResult result)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = result.Errors?.Any() == true
                ? result.Errors.First().Code.Equals("authorization")
                    ? (int)HttpStatusCode.Unauthorized : (int)HttpStatusCode.BadRequest
                : (int)HttpStatusCode.OK;

            await _writer.WriteAsync(context.Response.Body, result);
        }
Example #14
0
        /// <summary>
        /// Writes the <paramref name="value"/> to string.
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static async Task <string> WriteToStringAsync(this IDocumentWriter writer,
                                                             ExecutionResult value,
                                                             Encoding encoding = null)
        {
            var resolvedEncoding = encoding ?? Encoding.UTF8;

            using (var buffer = await writer.WriteAsync(value).ConfigureAwait(false))
            {
                return(buffer.Result.Array != null
                    ? resolvedEncoding.GetString(buffer.Result.Array, buffer.Result.Offset,
                                                 buffer.Result.Count)
                    : null);
            }
        }
Example #15
0
        private Task WriteBadRequestResponseAsync(HttpContext context, IDocumentWriter writer, string errorMessage)
        {
            var result = new ExecutionResult
            {
                Errors = new ExecutionErrors
                {
                    new ExecutionError(errorMessage)
                }
            };

            context.Response.ContentType = JsonContentType;
            context.Response.StatusCode  = (int)HttpStatusCode.BadRequest;

            return(writer.WriteAsync(context.Response.Body, result));
        }
Example #16
0
        /// <summary>
        /// Writes the <paramref name="value"/> to string.
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static async Task <string> WriteToStringAsync(
            this IDocumentWriter writer,
            ExecutionResult value)
        {
            using (var stream = new MemoryStream())
            {
                await writer.WriteAsync(stream, value);

                stream.Position = 0;
                using (var reader = new StreamReader(stream, DocumentWriter.Utf8Encoding))
                {
                    return(await reader.ReadToEndAsync());
                }
            }
        }
Example #17
0
        private Task WriteBadRequestResponseAsync(HttpContext context, IDocumentWriter writer, string errorMessage)
        {
            var result = new ExecutionResult()
            {
                Errors = new ExecutionErrors()
                {
                    new ExecutionError(errorMessage)
                }
            };

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = 400; // Bad Request

            return(writer.WriteAsync(context.Response.Body, result));
        }
        public override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IDocumentWriter documentWriter = context.HttpContext.RequestServices.GetRequiredService <IDocumentWriter>();

            HttpResponse response = context.HttpContext.Response;

            response.ContentType = CONTENT_TYPE;
            response.StatusCode  = StatusCodes.Status200OK;

            return(documentWriter.WriteAsync(response.Body, _executionResult));
        }
        private async Task <IntrospectionQueryData> GetSchemaAsync(ISchema schema)
        {
            var options = new ExecutionOptions
            {
                Schema = schema,
                Query  = IntrospectionQuery.GetQuery()
            };
            var result = await _documentExecuter.ExecuteAsync(options);

            using var stream = new MemoryStream();
            await _documentWriter.WriteAsync(stream, result);

            stream.Position = 0;
            var response = await IntrospectionQuery.DeserializeAsync(stream);

            return(response?.Data);
        }
Example #20
0
        private async Task WriteMessageAsync(OperationMessage message)
        {
            if (_socket.CloseStatus.HasValue)
            {
                return;
            }

            var stream = new WebsocketWriterStream(_socket);

            try
            {
                await _documentWriter.WriteAsync(stream, message);
            }
            finally
            {
                await stream.FlushAsync();

                stream.Dispose();
            }
        }
        /// <summary>
        ///     Invokes the middleware with the specified context.
        /// </summary>
        /// <param name="context">
        ///     The context.
        /// </param>
        /// <returns>
        ///     A <see cref="Task" /> representing the middleware invocation.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     Throws <see cref="ArgumentNullException" /> if <paramref name="context" />.
        /// </exception>
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (ShouldRespondToRequest(context.Request))
            {
                var executionResult = await ExecuteAsync(context.Request);

                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = (executionResult.Errors?.Count ?? 0) == 0 ? 200 : 400;
                await writer.WriteAsync(context.Response.Body, executionResult);
            }
            else
            {
                await next(context);
            }
        }
Example #22
0
        public async Task <IActionResult> GraphQL(
            [FromBody] GraphQLRequest request,
            [FromServices] ISchema schema,
            [FromServices] IDocumentExecuter executor,
            [FromServices] IDocumentWriter writer)
        {
            var result = await executor.ExecuteAsync(
                doc =>
            {
                doc.Schema           = schema;
                doc.Query            = request.Query;
                doc.Inputs           = request.Variables.ToInputs();
                doc.ExposeExceptions = true;
            }
                ).ConfigureAwait(false);

            var bytes = await writer.WriteAsync(result);

            return(Ok(JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bytes.Result))));
        }
Example #23
0
        public override async Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IDocumentWriter documentWriter = context.HttpContext.RequestServices.GetRequiredService <IDocumentWriter>();

            HttpResponse response = context.HttpContext.Response;

            response.ContentType = CONTENT_TYPE;
            response.StatusCode  = StatusCodes.Status200OK;

            // Azure functions 3 disallowing async IO and newtonsoft json is not able to
            // make real async IO, we need copy to a MemoryStream.
            // After graphql has switch to System.Text.Json this can be written directly to response.Body
            using var stream = new MemoryStream();
            await documentWriter.WriteAsync(stream, _executionResult);

            stream.Position = 0;
            await stream.CopyToAsync(response.Body);
        }
Example #24
0
        private async Task CreateAlarmAsync(
            RuleApiModel rule,
            RawMessage deviceMessage,
            string alarmDescription)
        {
            var created = DateTime.UtcNow;

            var alarm = new Alarm
            {
                Id                  = Guid.NewGuid().ToString(),
                DateCreated         = created,
                DateModified        = created,
                MessageReceivedTime = deviceMessage.ReceivedTime,
                Description         = alarmDescription,
                DeviceId            = deviceMessage.DeviceId,
                Status              = NewAlarmStatus,
                RuleId              = rule.Id,
                RuleServerity       = rule.Severity,
                RuleDescription     = rule.Description
            };

            await documentWriter.WriteAsync(AlarmToDocument(alarm));
        }
 private async Task WriteResponseAsync(HttpContext context, ExecutionResult result)
 {
     context.Response.ContentType = "application/json";
     if (result.Errors?.Any() == true)
     {
         if (result.Errors.ElementAt(0).Code.Equals("authorization"))
         {
             context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
         }
         else if (result.Errors.ElementAt(0).Code.Equals("NOT_FOUND"))
         {
             context.Response.StatusCode = (int)HttpStatusCode.NotFound;
         }
         else if (result.Errors.ElementAt(0).Code.Equals("FORBIDEN"))
         {
             context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
         }
         else if (result.Errors.ElementAt(0).Code.Equals("SERVER_ERROR"))
         {
             context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
         }
         else if (result.Errors.ElementAt(0).Code.Equals("CONFLICT"))
         {
             context.Response.StatusCode = (int)HttpStatusCode.Conflict;
         }
         else
         {
             context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
         }
     }
     else
     {
         context.Response.StatusCode = (int)HttpStatusCode.OK;
     }
     await _writer.WriteAsync(context.Response.Body, result);
 }
        private async Task ExecuteAsync(HttpContext context, ISchemaFactory schemaService)
        {
            var schema = await schemaService.GetSchema();

            AbpGraphQLRequest request = null;

            if (HttpMethods.IsPost(context.Request.Method))
            {
                var mediaType = new MediaType(context.Request.ContentType);

                try
                {
                    if (mediaType.IsSubsetOf(JsonMediaType))
                    {
                        using (var sr = new StreamReader(context.Request.Body))
                        {
                            using (var jsonTextReader = new JsonTextReader(sr))
                            {
                                request = Serializer.Deserialize <AbpGraphQLRequest>(jsonTextReader);
                            }
                        }
                    }
                    else if (mediaType.IsSubsetOf(GraphQLMediaType))
                    {
                        request = new AbpGraphQLRequest();

                        using (var sr = new StreamReader(context.Request.Body))
                        {
                            request.Query = await sr.ReadToEndAsync();
                        }
                    }
                    else if (context.Request.Query.ContainsKey("query"))
                    {
                        request = new AbpGraphQLRequest
                        {
                            Query = context.Request.Query["query"]
                        };


                        if (context.Request.Query.ContainsKey("variables"))
                        {
                            request.Variables = JObject.Parse(context.Request.Query["variables"]);
                        }

                        if (context.Request.Query.ContainsKey("operationName"))
                        {
                            request.OperationName = context.Request.Query["operationName"];
                        }
                    }
                }
                catch (Exception e)
                {
                    await WriteErrorAsync(context, "An error occured while processing the GraphQL query", e);

                    return;
                }
            }
            else if (HttpMethods.IsGet(context.Request.Method))
            {
                if (!context.Request.Query.ContainsKey("query"))
                {
                    await WriteErrorAsync(context, "The 'query' query string parameter is missing");

                    return;
                }

                request = new AbpGraphQLRequest
                {
                    Query = context.Request.Query["query"]
                };
            }

            var queryToExecute = request.Query;

            if (!string.IsNullOrEmpty(request.NamedQuery))
            {
                var namedQueries = context.RequestServices.GetServices <INamedQueryProvider>();

                var queries = namedQueries
                              .SelectMany(dict => dict.Resolve())
                              .ToDictionary(pair => pair.Key, pair => pair.Value);

                queryToExecute = queries[request.NamedQuery];
            }

            var result = await _executor.ExecuteAsync(_ =>
            {
                _.Schema        = schema;
                _.Query         = queryToExecute;
                _.OperationName = request.OperationName;
                _.Inputs        = request.Variables.ToInputs();
                _.UserContext   = _options.BuildUserContext?.Invoke(context);

#if DEBUG
                _.ExposeExceptions = true;
#endif
            });

            var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;

            context.Response.StatusCode  = (int)httpResult;
            context.Response.ContentType = "application/json";

            await _writer.WriteAsync(context.Response.Body, result);
        }