Beispiel #1
0
        private async Task SendSuccessAsync()
        {
            AmazonStepFunctionsClient client         = new AmazonStepFunctionsClient();
            SendTaskSuccessRequest    successRequest = new SendTaskSuccessRequest();

            successRequest.TaskToken = taskToken;
            Dictionary <String, String> result = new Dictionary <String, String>
            {
                { "Result", "Success" },
                { "Message", "Completed" }
            };

            string requestOutput = JsonConvert.SerializeObject(result, Formatting.Indented);

            successRequest.Output = requestOutput;
            try
            {
                await client.SendTaskSuccessAsync(successRequest);
            }
            catch (Exception error)
            {
                Console.WriteLine("ERROR : SendSuccessAsync : " + error.Message);
                Console.WriteLine("ERROR : SendSuccessAsync : " + error.StackTrace);
            }
            await Task.CompletedTask;
        }
Beispiel #2
0
        private static async Task ProcessNotificationAsync(McmaApiRequest request, McmaApiResponse response)
        {
            Logger.Debug(nameof(ProcessNotificationAsync));
            Logger.Debug(request.ToMcmaJson().ToString());

            var notification = request.JsonBody.ToMcmaObject <Notification>();

            if (notification == null)
            {
                response.StatusCode    = (int)HttpStatusCode.BadRequest;
                response.StatusMessage = "Missing notification in request body";
                return;
            }

            if (notification.Content == null)
            {
                response.StatusCode    = (int)HttpStatusCode.BadRequest;
                response.StatusMessage = "Missing notification content";
                return;
            }

            var job = notification.Content.ToMcmaObject <Job>();

            var taskToken = request.QueryStringParameters["taskToken"];

            var stepFunctionClient = new AmazonStepFunctionsClient();

            switch (job.Status)
            {
            case "COMPLETED":
                Logger.Debug($"Sending task success for task token {taskToken}");
                await stepFunctionClient.SendTaskSuccessAsync(new SendTaskSuccessRequest
                {
                    TaskToken = taskToken,
                    Output    = $"\"{notification.Source}\""
                });

                break;

            case "FAILED":
                Logger.Debug($"Sending task failure for task token {taskToken}");
                var error = job.Type + " failed execution";
                var cause = job.Type + " with id '" + job.Id + "' failed execution with statusMessage '" + job.StatusMessage + "'";

                await stepFunctionClient.SendTaskFailureAsync(new SendTaskFailureRequest
                {
                    TaskToken = taskToken,
                    Error     = error,
                    Cause     = cause
                });

                break;
            }
        }
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var s3Client           = new AmazonS3Client();
            var stepFunctionclient = new AmazonStepFunctionsClient();
            var bucket             = Environment.GetEnvironmentVariable("STEP_FUNCTION_DEMO_BUCKET");
            var requestObjects     = await s3Client.ListObjectsAsync(new ListObjectsRequest
            {
                BucketName = bucket,
                Prefix     = "TaskRequest"
            });

            foreach (var obj in requestObjects.S3Objects)
            {
                var s3object = await s3Client.GetObjectAsync(new GetObjectRequest
                {
                    BucketName = bucket,
                    Key        = obj.Key
                });

                using var sr = new StreamReader(s3object.ResponseStream);
                var data = JsonSerializer.Deserialize <JobWithTaskToken>(await sr.ReadToEndAsync());
                if (data.State.Data == 10)
                {
                    data.State.Resolved = true;
                }

                await s3Client.PutObjectAsync(new PutObjectRequest
                {
                    BucketName  = bucket,
                    Key         = $"TaskResponse/Response-{System.DateTime.Now.ToString("MMddyyyyhhmmss")}.json",
                    ContentBody = JsonSerializer.Serialize(data)
                });

                if (!string.IsNullOrEmpty(data.TaskToken))
                {
                    await stepFunctionclient.SendTaskSuccessAsync(new SendTaskSuccessRequest
                    {
                        TaskToken = data.TaskToken,
                        Output    = JsonSerializer.Serialize(data.State)
                    });
                }

                await s3Client.CopyObjectAsync(new CopyObjectRequest
                {
                    SourceBucket      = obj.BucketName,
                    DestinationBucket = bucket,
                    SourceKey         = obj.Key,
                    DestinationKey    = obj.Key.Replace("TaskRequest", "Completed")
                });

                await s3Client.DeleteObjectAsync(bucket, obj.Key);
            }
        }
        private static async Task ProcessNotificationAsync(McmaApiRequestContext requestContext)
        {
            Logger.Debug(nameof(ProcessNotificationAsync));
            Logger.Debug(requestContext.Request.ToMcmaJson().ToString());

            if (requestContext.IsBadRequestDueToMissingBody(out Notification notification))
            {
                return;
            }

            if (notification.Content == null)
            {
                requestContext.Response.StatusCode    = (int)HttpStatusCode.BadRequest;
                requestContext.Response.StatusMessage = "Missing notification content";
                return;
            }

            var job = notification.Content.ToMcmaObject <Job>();

            var taskToken = requestContext.Request.QueryStringParameters["taskToken"];

            if (job.Status == JobStatus.Completed)
            {
                using (var stepFunctionClient = new AmazonStepFunctionsClient())
                    await stepFunctionClient.SendTaskSuccessAsync(new SendTaskSuccessRequest
                    {
                        TaskToken = taskToken,
                        Output    = $"\"{notification.Source}\""
                    });
            }
            else if (job.Status == JobStatus.Failed)
            {
                using (var stepFunctionClient = new AmazonStepFunctionsClient())
                    await stepFunctionClient.SendTaskFailureAsync(new SendTaskFailureRequest
                    {
                        TaskToken = taskToken,
                        Error     = job.Type + " failed execution",
                        Cause     = job.Type + " with id '" + job.Id + "' failed execution with statusMessage '" + job.StatusMessage + "'"
                    });
            }
            else
            {
                Logger.Debug($"Ignoring notification for updated status of '{job.Status}'");
            }
        }
Beispiel #5
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine(request.Body);
            var input = JsonSerializer.Deserialize <Payload>(request.Body);

            context.Logger.LogLine(JsonSerializer.Serialize(input.OrderID));

            //Get Order details
            List <Order> allDocs = await GetOrderDetails(input);

            var savedState = allDocs.FirstOrDefault();

            //Callback step function
            SendTaskSuccessResponse sendTaskSuccessResponse;

            using (var amazonStepFunctionsClient = new AmazonStepFunctionsClient())
            {
                //Set Stepfunction output data.
                var data = new
                {
                    IsApproved = input.IsApproved
                };
                var jsonData = JsonSerializer.Serialize(data);
                var startExecutionRequest = new StartExecutionRequest
                {
                    Input = jsonData,
                };
                var result = amazonStepFunctionsClient.SendTaskSuccessAsync(new SendTaskSuccessRequest()
                {
                    TaskToken = savedState.Token, Output = jsonData
                }).Result;
            }
            APIGatewayProxyResponse response = new APIGatewayProxyResponse()
            {
                Body = "Successfully invoked stepfunction.", StatusCode = 200
            };

            return(response);
        }
Beispiel #6
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="request">Instance of APIGatewayProxyRequest</param>
        /// <param name="context">AWS Lambda Context</param>
        /// <returns>Instance of APIGatewayProxyResponse</returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var body = JsonConvert.DeserializeObject <Dictionary <string, string> >(request?.Body);

            var isIncidentId = Guid.TryParse(body["IncidentId"], out var incidentId);
            var isExamId     = Guid.TryParse(body["ExamId"], out var examId);
            var isScore      = Int32.TryParse(body["Score"], out var score);
            var token        = body["TaskToken"];

            if (!isIncidentId || !isExamId | !isScore | !(token.Length >= 1 & token.Length <= 1024))
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }
                    }
                });
            }

            Console.WriteLine($"IncidentId: {incidentId}");
            Console.WriteLine($"ExamId: {examId}");
            Console.WriteLine($"Score: {score}");
            Console.WriteLine($"Token: {token}");

            var incident = _incidentRepository.GetIncidentById(incidentId);
            var exam     = incident.Exams.Find(e => e.ExamId == examId);

            exam.Score = score;

            _incidentRepository.SaveIncident(incident);

            Console.WriteLine(JsonConvert.SerializeObject(incident));

            var sendTaskSuccessRequest = new SendTaskSuccessRequest
            {
                TaskToken = token,
                Output    = JsonConvert.SerializeObject(incident)
            };

            try
            {
                _amazonStepFunctionsClient.SendTaskSuccessAsync(sendTaskSuccessRequest).Wait();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "application/json" },
                    { "Access-Control-Allow-Origin", "*" },
                    { "Access-Control-Allow-Headers", "Content-Type" },
                    { "Access-Control-Allow-Methods", "OPTIONS,POST" }
                }
            });
        }