Esempio n. 1
0
        public async Task ShouldPublishMessagesWithIdsToSQS(
            SNSEvent snsEvent,
            SNSEvent.SNSRecord record1,
            SNSEvent.SNSRecord record2,
            Request request1,
            Request request2,
            [Frozen] IAmazonSQS sqs,
            [Frozen] ISnsRecordMapper mapper,
            [Target] Handler handler,
            CancellationToken cancellationToken
            )
        {
            snsEvent.Records = new List <SNSEvent.SNSRecord> {
                record1, record2
            };

            mapper.MapToRequest(Is(record1)).Returns(request1);
            mapper.MapToRequest(Is(record2)).Returns(request2);

            await handler.Handle(snsEvent, cancellationToken);

            await sqs.Received().SendMessageBatchAsync(Any <SendMessageBatchRequest>(), Is(cancellationToken));

            var request = TestUtils.GetArg <SendMessageBatchRequest>(sqs, nameof(IAmazonSQS.SendMessageBatchAsync), 0);

            request.Entries.Should().Contain(entry => entry.Id == request1.Id.ToString());
            request.Entries.Should().Contain(entry => entry.Id == request2.Id.ToString());
        }
Esempio n. 2
0
        public void TestFunction()
        {
            var function = new Function();
            var context  = new TestLambdaContext();

            SNSEvent.SNSMessage snsMessage = new SNSEvent.SNSMessage {
                Message   = "{\"notificationType\":\"Bounce\",\"bounce\":{\"bounceType\":\"Permanent\",\"feedbackId\":\"feedback_id\",\"bouncedRecipients\":[{\"emailAddress\":\"[email protected]\"}]}}",
                Timestamp = DateTime.Parse("1/1/1990")
            };
            SNSEvent.SNSRecord snsRecord = new SNSEvent.SNSRecord {
                EventSource          = "event_source",
                EventSubscriptionArn = "event_subscription_arn",
                EventVersion         = "event_version",
                Sns = snsMessage
            };
            List <SNSEvent.SNSRecord> recordList = new List <SNSEvent.SNSRecord>();

            recordList.Add(snsRecord);
            SNSEvent snsEvent = new SNSEvent {
                Records = recordList
            };

            var retval = function.FunctionHandler(snsEvent, context);

            Assert.Equal("okay", retval.Result);
        }
Esempio n. 3
0
        private async Task ProcessMessageAsync(SNSEvent.SNSRecord message, ILambdaContext context)
        {
            context.Logger.LogLine(message.Sns.Message);

            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
Esempio n. 4
0
        private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)
        {
            context.Logger.LogLine($"Processed record {record.Sns.Message}");

            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
        private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)
        {
            context.Logger.LogLine($"Processed record {record.Sns.Message}");

            var message        = JsonConvert.DeserializeObject <AdvertConfirmedMessage>(record.Sns.Message);
            var advertDocument = MappingHelper.Map(message);
            await _client.IndexDocumentAsync(advertDocument);
        }
Esempio n. 6
0
        private async Task ProcessMessageAsync(SNSEvent.SNSRecord message, ILambdaContext context)
        {
            context.Logger.LogLine($"Processed message {message.Sns.Message}");

            await DynamoHelper.UpdateTable(message.Sns.Message);

            context.Logger.LogLine($"Processed DynamoDB update");
        }
        private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)
        {
            // All log statements are written to CloudWatch by default. For more information, see
            // https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html
            context.Logger.LogLine($"Processed record {record.Sns.Message}");

            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
Esempio n. 8
0
 private static SetInstanceShutdownDto Deserialize(SNSEvent.SNSRecord snsEventRecord)
 {
     using (TextReader textReader = new StringReader(snsEventRecord.Sns.Message))
     {
         using (JsonReader reader = new JsonTextReader(textReader))
         {
             return(JsonSerializer.Deserialize <SetInstanceShutdownDto>(reader));
         }
     }
 }
 public Request MapToRequest(SNSEvent.SNSRecord record)
 {
     return(new Request(ChannelEndpoint.CreateMessage)
     {
         Parameters = { ["channel.id"] = record.Sns.MessageAttributes["Brighid.SourceId"].Value },
         RequestBody = serializer.Serialize(new CreateMessagePayload
         {
             Content = record.Sns.Message,
         }),
     });
 }
Esempio n. 10
0
        private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)
        {
            context.Logger.LogLine($"Processed record: {record.Sns.Message}");
            context.Logger.LogLine($"MessageId: {record.Sns.MessageId}");
            context.Logger.LogLine($"Subject: {record.Sns.Subject}");
            string version = Environment.GetEnvironmentVariable("mandia_version");

            context.Logger.LogLine($"mandia version: {version}");
            context.Logger.LogLine($"Version: 2");


            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
Esempio n. 11
0
        public SesEvent ParseRecord(SNSEvent.SNSRecord record, ILambdaContext context)
        {
            context.Logger.LogLine($"Parsing record for {record.Sns.Type} from source {record.EventSource}.");

            var notification = JsonSerializer.Deserialize <SesNotification>(record.Sns.Message, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                DictionaryKeyPolicy  = JsonNamingPolicy.CamelCase
            });

            var evt = new SesEvent
            {
                EventType = notification.NotificationType,
                Timestamp = notification.Mail.Timestamp,
                // MessageId = notification.Mail.
                Source           = notification.Mail.Source,
                SourceArn        = notification.Mail.SourceArn,
                SourceIp         = notification.Mail.SourceIp,
                SendingAccountId = notification.Mail.SendingAccountId,
                FromAddress      = notification.Mail.CommonHeaders.From.First(),
                Subject          = notification.Mail.CommonHeaders.Subject,
                MessageDate      = notification.Mail.CommonHeaders.Date,
                // Recipients = notification.Mail.CommonHeaders.To
            };

            if (notification.Mail.CommonHeaders.To?.Any() ?? false)
            {
                foreach (var toAddr in notification.Mail.CommonHeaders.To.Where(x => !string.IsNullOrEmpty(x)))
                {
                    if (toAddr.Contains(","))
                    {
                        evt.Recipients.AddRange(toAddr.Split(',', StringSplitOptions.RemoveEmptyEntries));
                    }
                    else
                    {
                        evt.Recipients.Add(toAddr);
                    }
                }
            }

            switch (notification.NotificationType)
            {
            case "Bounce" when notification.Bounce != null:
                evt.SubType    = $"{notification.Bounce.BounceType} - {notification.Bounce.BounceSubType}";
                evt.FeedbackId = notification.Bounce.FeedbackId;
                break;
            }

            return(evt);
        }
            public void ShouldSetChannelIdParameter(
                string channelId,
                SNSEvent.SNSRecord record,
                [Target] SnsRecordMapper mapper
                )
            {
                record.Sns.MessageAttributes["Brighid.SourceId"] = new SNSEvent.MessageAttribute {
                    Type = "String", Value = channelId
                };

                var result = mapper.MapToRequest(record);

                result.Parameters["channel.id"].Should().Be(channelId);
            }
Esempio n. 13
0
        private bool hasMessage(SNSEvent.SNSRecord snsRecord)
        {
            var msg = string.Empty;

            if (snsRecord == null)
            {
                return(false);
            }
            try {
                msg = snsRecord.Sns.Message;
            } catch (NullReferenceException e) {
                return(false);
            }
            return(!string.IsNullOrEmpty(msg));
        }
            public void ShouldSetEndpointToChannelCreateMessage(
                string channelId,
                SNSEvent.SNSRecord record,
                [Target] SnsRecordMapper mapper
                )
            {
                record.Sns.MessageAttributes["Brighid.SourceId"] = new SNSEvent.MessageAttribute {
                    Type = "String", Value = channelId
                };

                var result = mapper.MapToRequest(record);

                result.Endpoint.Category.Should().Be('c');
                result.Endpoint.Value.Should().Be(ChannelEndpoint.CreateMessage);
            }
Esempio n. 15
0
        private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)
        {
            try
            {
                var sesEvent = ParseRecord(record, context);
                await SaveEventAsync(sesEvent);

                context.Logger.LogLine($"Processed record for {sesEvent.EventType}");
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"Error: {ex.Message}");
            }

            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
            public void ShouldSetBody(
                string channelId,
                string expectedBody,
                SNSEvent.SNSRecord record,
                [Frozen] ISerializer serializer,
                [Target] SnsRecordMapper mapper
                )
            {
                serializer.Serialize(Any <CreateMessagePayload>()).Returns(expectedBody);

                record.Sns.Message = expectedBody;
                record.Sns.MessageAttributes["Brighid.SourceId"] = new SNSEvent.MessageAttribute {
                    Type = "String", Value = channelId
                };

                var result = mapper.MapToRequest(record);

                result.RequestBody.Should().Be(expectedBody);
            }
        private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)
        {
            context.Logger.LogLine($"Processed record {record.Sns.Message}");

            var message = System.Text.Json.JsonSerializer.Deserialize <TestMessage>(record.Sns.Message);

            await amazonDynamoDB.UpdateItemAsync(new UpdateItemRequest
            {
                TableName = "message-processor",
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "pk", new AttributeValue($"SnsProcessor|{message.TestId}") }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":incr", new AttributeValue {
                          N = "1"
                      } },
                    { ":end", new AttributeValue(DateTimeOffset.UtcNow.ToString("o")) }
                },
                UpdateExpression = "SET MessageCount = MessageCount + :incr, EndTime = :end"
            });
        }
Esempio n. 18
0
        private async Task ProcessSnsEvent(SNSEvent.SNSRecord snsEventRecord, ILambdaContext context)
        {
            var instanceShutdownDto = Deserialize(snsEventRecord);

            await UpdateInstanceTags(instanceShutdownDto, context);
        }
Esempio n. 19
0
        public void Setup()
        {
            // APIGatewayProxy
            _baseAPIGatewayProxyRequest = new APIGatewayProxyRequest
            {
                HttpMethod = "POST",
                Path       = "/test/path",
            };

            _baseAPIGatewayProxyResponse = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
            };

            // ApplicationLoadBalancer
            var albRequestContext = new ApplicationLoadBalancerRequest.ALBRequestContext
            {
                Elb = new ApplicationLoadBalancerRequest.ElbInfo()
            };

            albRequestContext.Elb.TargetGroupArn = TestArn;
            _baseApplicationLoadBalancerRequest  = new ApplicationLoadBalancerRequest
            {
                HttpMethod     = "POST",
                Path           = "/test/path",
                RequestContext = albRequestContext,
            };

            _baseApplicationLoadBalancerResponse = new ApplicationLoadBalancerResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
            };

            // SQSEvent
            var sqsRecord = new SQSEvent.SQSMessage
            {
                EventSourceArn = TestArn
            };

            _baseSQSEvent = new SQSEvent
            {
                Records = new List <SQSEvent.SQSMessage> {
                    sqsRecord
                },
            };

            // SNSEvent
            var snsMessaage = new SNSEvent.SNSMessage()
            {
                Message = "Test Message",
            };
            var snsRecord = new SNSEvent.SNSRecord
            {
                EventSubscriptionArn = TestArn,
                Sns = snsMessaage
            };

            _baseSNSEvent = new SNSEvent
            {
                Records = new List <SNSEvent.SNSRecord> {
                    snsRecord
                },
            };

            // KinesisEvent
            var kinesisRecord = new KinesisEvent.KinesisEventRecord
            {
                EventSourceARN = TestArn
            };

            _baseKinesisEvent = new KinesisEvent
            {
                Records = new List <KinesisEvent.KinesisEventRecord> {
                    kinesisRecord
                },
            };

            // S3Event
            var s3Record = new Amazon.S3.Util.S3EventNotification.S3EventNotificationRecord
            {
                S3 = new Amazon.S3.Util.S3EventNotification.S3Entity
                {
                    Bucket = new Amazon.S3.Util.S3EventNotification.S3BucketEntity
                    {
                        Arn = TestArn
                    }
                }
            };

            _baseS3Event = new S3Event
            {
                Records = new List <Amazon.S3.Util.S3EventNotification.S3EventNotificationRecord> {
                    s3Record
                },
            };

            // DynamoDBEvent
            var dynamoDBRecord = new DynamoDBEvent.DynamodbStreamRecord
            {
                EventSourceArn = TestArn
            };

            _baseDynamoDBEvent = new DynamoDBEvent
            {
                Records = new List <DynamoDBEvent.DynamodbStreamRecord> {
                    dynamoDBRecord
                },
            };

            // KinesisFirehoseEvent
            _baseKinesisFirehoseEvent = new KinesisFirehoseEvent
            {
                DeliveryStreamArn = TestArn,
            };
        }