Exemple #1
0
        public static EventRequest <dynamic> ToEventRequest(this DynamodbStreamRecord record)
        {
            var     request = new EventRequest <dynamic>();
            dynamic data    = new ExpandoObject();
            var     dict    = (IDictionary <string, object>)data;

            if (record.EventName == "REMOVE" || record.EventName == "MODIFY")
            {
                dict["old"] = JToken.Parse(Document.FromAttributeMap(record.Dynamodb.OldImage).ToJson());
            }
            else
            {
                dict["old"] = JToken.Parse("{}");
            }

            if (record.EventName == "INSERT" || record.EventName == "MODIFY")
            {
                dict["new"] = JToken.Parse(Document.FromAttributeMap(record.Dynamodb.NewImage).ToJson());
            }
            else
            {
                dict["new"] = JToken.Parse("{}");
            }
            request.Metadata        = request.Metadata ?? new ExpandoObject();
            request.Metadata.action = _actionMap[record.EventName];

            request.Data = data;
            return(request);
        }
Exemple #2
0
 public async Task DynamoDBEvent_should_get_parsed_not_diffed_When_removed()
 {
     _eventBridgeClientMock.Setup(p => p.PutEventsAsync(It.IsAny <PutEventsRequest>(), It.IsAny <CancellationToken>())).Callback <PutEventsRequest, CancellationToken>((per, ct) => ValidateRemove(per)).ReturnsAsync(new PutEventsResponse());
     var record = new DynamodbStreamRecord {
         EventName = "REMOVE", Dynamodb = new StreamRecord {
             OldImage = Document.FromJson(JsonConvert.SerializeObject(new TestEvent {
                 Id = "1", Name = "Old"
             })).ToAttributeMap(), NewImage = Document.FromJson(JsonConvert.SerializeObject(new TestEvent {
                 Id = "1", Name = "New"
             })).ToAttributeMap()
         }
     };
     await _client.Send("test", record);
 }
        private void SendUpdatesToStore(DynamodbStreamRecord record, ILambdaContext context)
        {
            // We need to extract Person get his purchase history and come up with payload using Machine Learning
            // It should also have the device name to be published to
            AttributeValue customerIdValueAttr = record.Dynamodb.Keys[IdIdentifier];
            AttributeValue newLocationAttr     = (record.Dynamodb.NewImage != null) ? record.Dynamodb.NewImage[LocationIdentifier] : null;
            AttributeValue oldLocationAttr     = (record.Dynamodb.OldImage != null) ? record.Dynamodb.OldImage[LocationIdentifier] : null;

            int    customerId  = Convert.ToInt32(customerIdValueAttr.N);
            string newLocation = newLocationAttr?.S;
            string oldLocation = oldLocationAttr?.S;

            context.Logger.LogLine($"CustomerId:{customerId};OldLocation:{oldLocation};NewLocation:{newLocation};");
            if (string.Compare(oldLocation, newLocation, true) != 0)
            {
                if ((string.IsNullOrWhiteSpace(oldLocation)) && (newLocation == Entrance))
                {
                    context.Logger.LogLine($"Customer entered the store. Updating Missing stock information.");
                    UpdateMissingStockInformation(customerId, context);
                }
                else if (newLocation.StartsWith(Aisle))
                {
                    context.Logger.LogLine($"Customer location updated from {oldLocation} to {newLocation}.");
                    // Send highlight signal for new location and clear signal to old location
                    if (newLocation.StartsWith(Aisle))
                    {
                        List <string> customerPreferences = GetCustomerPreferences(customerId, newLocation);
                        NotifyAisle(customerId, newLocation, customerPreferences, "Highlight");

                        string allPrefs = string.Empty;
                        foreach (string preference in customerPreferences)
                        {
                            allPrefs += (preference + ", ");
                        }
                        context.Logger.LogLine($"Notifcations Sent to {newLocation} to highlight items of customer recommendations: {allPrefs}.");
                    }
                    if (oldLocation.StartsWith(Aisle))
                    {
                        NotifyAisle(customerId, oldLocation, GetCustomerPreferences(customerId, oldLocation), "TurnOff");
                        context.Logger.LogLine($"Notifcations Sent to {oldLocation} to stop highlighting items customer recommendations.");
                    }
                }
            }
        }
Exemple #4
0
        public async Task <bool> DoSomethingAsync(DynamodbStreamRecord record, ILambdaLogger logger)
        {
            string ParentId = "", TraceId = "", TraceParentId = "";

            logger.LogLine($"Event ID: {record.EventID}");
            logger.LogLine($"Event Name: {record.EventName}");

            using (var writer = new StringWriter())
            {
                _jsonSerializer.Serialize(writer, record.Dynamodb);

                var hasParentTrace = record.Dynamodb.NewImage.TryGetValue("ParentTraceId", out AttributeValue value);
                if (hasParentTrace)
                {
                    logger.LogLine($"ParentTraceId: {value.S}");
                    TraceParentId = value.S;
                    var traceInfo = value.S.Split("-");
                    if (traceInfo.Length == 4)
                    {
                        TraceId  = traceInfo[1];
                        ParentId = traceInfo[2];
                    }
                }

                var streamRecordJson = writer.ToString();

                logger.LogLine($"DynamoDB Record:");
                logger.LogLine(streamRecordJson);
            }

            try
            {
                Activity activity = null;

                try
                {
                    if (!string.IsNullOrEmpty(TraceParentId))
                    {
                        activity = _activitySource.StartActivity("call-api", ActivityKind.Client,
                                                                 TraceParentId, startTime: DateTimeOffset.UtcNow);
                    }
                    else
                    {
                        activity = _activitySource.StartActivity("call-api", ActivityKind.Client);
                    }

                    logger.LogLine("Activity StartTimeUtc: " + activity?.StartTimeUtc);
                    logger.LogLine("OtlpEndpointUrl: " + _settings.DistributedTracingOptions.OtlpEndpointUrl);

                    if (!string.IsNullOrEmpty(_settings.SampleApiTwoTestEndpointUrl))
                    {
                        logger.LogLine("Calling SampleApi.Two");
                        var response = await _settings.SampleApiTwoTestEndpointUrl
                                       .WithHeader("traceparent", activity.Id)
                                       .GetStringAsync();

                        logger.LogLine($"SampleApi.Two called successfully: {response}");
                    }
                    return(true);
                }
                finally
                {
                    activity?.Stop();
                    activity?.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger.LogLine($"Error occured: {ex.Message}");
                return(false);
            }
        }
Exemple #5
0
 public async Task <EventResponse> Send(string detailType, DynamodbStreamRecord item)
 {
     return(await Send(detailType, (IList <DynamodbStreamRecord>) new List <DynamodbStreamRecord> {
         item
     }));
 }