Skip to content

DynamoDB events have milliseconds, not seconds, in their timestamps which crashes deserialization #839

Closed

Description

@cdegroot

Description

I'm creating a lambda to process DynamoDB events streamed through Kinesis, which means they're wrapped in base64, etcetera. During processing I pull them out and then deserialize them to DynamoDBv2 records:

            var serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();
            var dynamoEvent = serializer.Deserialize<Amazon.DynamoDBv2.Model.Record>(BaseObserver.GenerateStreamFromString(dynamoData));

Reproduction Steps

This gist: https://gist.github.com/cdegroot/6e8e1957d9d08a595b3918dce3e16d84. Note that all I did was to add a couple of zeros to the test event.

Logs

Stacktrace:

  X TestDynamoParsing [8ms]
  Error Message:
   Test method Canary.EventStore.Tests.BaseObserverTests.TestDynamoParsing threw exception: 
Amazon.Lambda.Serialization.Json.JsonSerializerException: Error converting the Lambda event JSON payload to type Amazon.DynamoDBv2.Model.Record: Value to add was out of range. (Parameter 'value') ---> System.ArgumentOutOfRangeException: Value to add was out of range. (Parameter 'value')                                                                                    
  Stack Trace:
      at System.DateTime.Add(Double value, Int32 scale)
   at System.DateTime.AddSeconds(Double value)
   at Amazon.Lambda.Serialization.Json.JsonNumberToDateTimeDataConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)
   at Amazon.Lambda.Serialization.Json.JsonSerializer.Deserialize[T](Stream requestStream)
--- End of inner exception stack trace ---
    at Amazon.Lambda.Serialization.Json.JsonSerializer.Deserialize[T](Stream requestStream

Environment

  • Build Version: 1.2.0
  • OS Info: Ubuntu 20.10
  • Build Environment: Terminal dotnet test etc.
  • Targeted .NET Platform: 3.1

Resolution

  • 👋 I can/would-like-to implement a fix for this problem myself

I can look later, will just kill the last three digits with a regex for now, but the usual fix is to take a cut-off value (100000000000 - somewhere in the 6th millenium) and if it's above, interpret as millisecs, if not, as secs.

Of course, the proper fix is to make DynamoDB emit always one or the other :)


This is a 🐛 bug-report

Activity

  1. added
    bugThis issue is a bug.
    needs-triageThis issue or PR still needs to be triaged.
    on Mar 23, 2021
  2. ashishdhingra commented on Mar 23, 2021

    @ashishdhingra
    Contributor

    Hi @cdegroot,

    Good afternoon.

    Looking at the code, looks like it is an automated unit test code where your test data is real record from DynamoDB Streams. Could you please share the source for the JSON string? In you JSON string, the value for ApproximateCreationDateTime is 1480642020000. However, the example at https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.Tutorial.html, has value 1479499740 for example. Notice the extra last 3 digits, as pointed by you as well. Not sure if there is an issue with your test data. While I didn't got a chance to examine the actual event received from DynamoDB stream, just wanted to validate your test data.

    Thanks,
    Ashish

  3. added
    response-requestedWaiting on additional info and feedback. Will move to close soon in 7 days.
    and removed
    needs-triageThis issue or PR still needs to be triaged.
    on Mar 23, 2021
  4. cdegroot commented on Mar 24, 2021

    @cdegroot
    Author

    I created that test based on real data I saw flowing so I could reproduce (and work around the issue). I won't share our full data in public, but hopefully the following exposition helps.

    From another (JS-based) Kinesis consumer, which is logging full Kinesis events, I copied an event:

    var kinesisData = @"{""Records"":[{""kinesis"":{""kinesisSchemaVersion"":""1.0"",""partitionKey"":""D7FE246F3E699C3B143D2A8378D17223"",""sequenceNumber"":""49616371596847055066813995925388293329944250222301413394"",""data"":""eyJhd3....1vZGIifQ=="",""approximateArrivalTimestamp"":1616427312.824},""eventSource"":""aws:kinesis"",""eventVersion"":""1.0"",""eventID"":""shardId-000000000001:49616371596847055066813995925388293329944250222301413394"",""eventName"":""aws:kinesis:record"",""invokeIdentityArn"":""arn:aws:iam::..."",""awsRegion"":""us-east-1"",""eventSourceARN"":""arn:aws:kinesis:us-east-1:147803588724:stream...""}]}";
    

    I snipped most of the payload for brevity and privacy, but base64 decoding it:

    {
      "awsRegion": "us-east-1",
      "dynamodb": {
        "ApproximateCreationDateTime": 1616427312786,
        "Keys": {
          "Id": {
            "S": "SHARED/User/0gKQCSqc3bQUW90Fch6oCv"
          },
          "Version": {
            "N": "1"
          }
        },
        "NewImage": {
          "Event": {
            "S": "..."
          },
          "Version": {
            "N": "1"
          },
          "Id": {
            "S": "SHARED/User/0gKQCSqc3bQUW90Fch6oCv"
          },
          "Type": {
            "S": "InviteDeleted"
          }
        },
        "SizeBytes": 452
      },
      "eventID": "408c266f-06b0-43e6-9e31-68f530664e6c",
      "eventName": "INSERT",
      "userIdentity": null,
      "recordFormat": "application/json",
      "tableName": "dev1-EventLog",
      "eventSource": "aws:dynamodb"
    }
    

    (again edited for brevity and privacy). As you can see, there's a 13 digit timestamp in there. I added three zeroes to the existing test data (which I think I snipped from here] to reproduce the issue.

  5. removed
    response-requestedWaiting on additional info and feedback. Will move to close soon in 7 days.
    on Mar 25, 2021
  6. ashishdhingra commented on Apr 2, 2021

    @ashishdhingra
    Contributor

    Hi @cdegroot,

    Good afternoon.

    Unfortunately I'm unable to reproduce the issue. Used the below steps:

    1. Created DynamoDb table HighScoresWithStream with:
    • Username (String) as Primary partition key and Game (String) as Primary sort key
    • DynamoDB stream enabled (View type as New and old images)
    1. Created the following Lambda function:
      .csproj
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
        <AWSProjectType>Lambda</AWSProjectType>
    
        <!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
        <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Amazon.Lambda.Core" Version="2.0.0" />
        <PackageReference Include="Amazon.Lambda.DynamoDBEvents" Version="2.0.0" />
        <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.1.0" />
      </ItemGroup>
    </Project>

    Function.cs

    using Amazon.Lambda.Core;
    using System.IO;
    
    // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
    [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
    
    namespace DynamoDbStream_Issue839
    {
        public class Function
        {
            public void FunctionHandler(DynamoDBEvent dynamoDBEvent, ILambdaContext context)
            {
                context.Logger.LogLine($"DynamoDBEvent received with {dynamoDBEvent.Records.Count} records.");
                foreach (var record in dynamoDBEvent.Records)
                {
                    context.Logger.LogLine($"{record.EventID}:{record.EventName}, Dynamodb.ApproximateCreationDateTime:{record.Dynamodb.ApproximateCreationDateTime}");
                }
            }
        }
    }

    aws-lambda-tools-defaults.json

    {
        "Information" : [
            "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
            "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
            "dotnet lambda help",
            "All the command line options for the Lambda command can be specified in this file."
        ],
        "profile"     : "default",
        "region"      : "us-east-2",
        "configuration" : "Release",
        "framework"     : "netcoreapp3.1",
        "function-runtime" : "dotnetcore3.1",
        "function-memory-size" : 256,
        "function-timeout"     : 30,
        "function-handler"     : "DynamoDbStream_Issue839::DynamoDbStream_Issue839.Function::FunctionHandler",
        "function-name"        : "StreamConsumer",
        "package-type"         : "Zip",
        "function-role"        : "arn:aws:iam::139480602983:role/lambda_exec_StreamConsumer-0",
        "tracing-mode"         : "PassThrough",
        "environment-variables" : "",
        "image-tag"             : "",
        "function-description"  : ""
    }

    NOTE: To keep things simple for reproduction, the role lambda_exec_StreamConsumer-0 has AWSLambdaExecute and AmazonDynamoDBFullAccess policies attached.

    1. Published the Lambda function to AWS.
    2. In AWS Lambda console, added DynamoDB trgigger for table HighScoresWithStream
    3. Added some records to DynamoDB database.
    4. Examined the CloudWatch logs:
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    |   timestamp   |                                                                                                                                              message                                                                                                                                               |
    |---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
    | 1617405537095 | START RequestId: 4c7331ac-6882-449b-8488-e78994536976 Version: $LATEST                                                                                                                                                                                                                             |
    | 1617405537203 | DynamoDBEvent received with 1 records.                                                                                                                                                                                                                                                             |
    | 1617405537282 | 1d507e4abd270fc658c78593be3ad773:INSERT, Dynamodb.ApproximateCreationDateTime:4/2/2021 11:18:18 PM                                                                                                                                                                                                 |
    | 1617405537300 | END RequestId: 4c7331ac-6882-449b-8488-e78994536976                                                                                                                                                                                                                                                |
    | 1617405537300 | REPORT RequestId: 4c7331ac-6882-449b-8488-e78994536976 Duration: 202.58 ms Billed Duration: 203 ms Memory Size: 256 MB Max Memory Used: 70 MB                                                                                                                                                      |
    | 1617405565785 | START RequestId: 5bbf64d3-7f10-437d-bd00-4185c5b3c8fe Version: $LATEST                                                                                                                                                                                                                             |
    | 1617405565790 | DynamoDBEvent received with 1 records.                                                                                                                                                                                                                                                             |
    | 1617405565790 | 421616e0bcb058e190f341ed8227f4e5:INSERT, Dynamodb.ApproximateCreationDateTime:4/2/2021 11:19:25 PM                                                                                                                                                                                                 |
    | 1617405565790 | END RequestId: 5bbf64d3-7f10-437d-bd00-4185c5b3c8fe                                                                                                                                                                                                                                                |
    | 1617405565790 | REPORT RequestId: 5bbf64d3-7f10-437d-bd00-4185c5b3c8fe Duration: 3.31 ms Billed Duration: 4 ms Memory Size: 256 MB Max Memory Used: 70 MB                                                                                                                                                                                                                                                                                                                   |
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    1. Modified the code in Function.cs to below to capture JSON:
    using Amazon.Lambda.Core;
    using System.IO;
    
    // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
    [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
    
    namespace DynamoDbStream_Issue839
    {
        public class Function
        {
            public Stream FunctionHandler(Stream userInput, ILambdaContext context)
            {
                string jsonString;
                using (var reader = new StreamReader(userInput))
                {
                    jsonString = reader.ReadToEnd();
                }
    
                context.Logger.LogLine($"JSON received: {jsonString}");
    
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jsonString);
                MemoryStream stream = new MemoryStream(bytes);
                return stream;
            }
        }
    }
    1. Republished the Lambda.
    2. Added record to DynamoDB table.
    3. Examined the CloudWatch logs:
    JSON received: 
    {
        "Records": [
            {
                "eventID": "1416c843df272af3718f3173fb9b0363",
                "eventName": "INSERT",
                "eventVersion": "1.1",
                "eventSource": "aws:dynamodb",
                "awsRegion": "us-east-2",
                "dynamodb": {
                    "ApproximateCreationDateTime": 1617406031,
                    "Keys": {
                        "Game": {
                            "S": "testgame"
                        },
                        "Username": {
                            "S": "multiple"
                        }
                    },
                    "NewImage": {
                        "Game": {
                            "S": "testgame"
                        },
                        "Username": {
                            "S": "multiple"
                        }
                    },
                    "SequenceNumber": "5800000000005804693158",
                    "SizeBytes": 56,
                    "StreamViewType": "NEW_AND_OLD_IMAGES"
                },
                "eventSourceARN": "arn:aws:dynamodb:us-east-2:139480602983:table/HighScoresWithStream/stream/2021-04-02T22:37:03.187"
            }
        ]
    }
    

    As you could see from JSON captured above, the ApproximateCreationDateTime has value with 10 digits (not 13 digits).

    Please let me know if this helps.

    Thanks,
    Ashish

  7. added
    response-requestedWaiting on additional info and feedback. Will move to close soon in 7 days.
    and removed on Apr 2, 2021
  8. github-actions commented on Apr 17, 2021

    @github-actions
    Contributor

    This issue has not recieved a response in 2 weeks. If you want to keep this issue open, please just leave a comment below and auto-close will be canceled.

  9. added
    closing-soonThis issue will automatically close in 4 days unless further comments are made.
    on Apr 17, 2021
  10. removed
    closing-soonThis issue will automatically close in 4 days unless further comments are made.
    on Apr 24, 2021
  11. 7 remaining items

  12. Tragetaschen commented on Mar 2, 2022

    @Tragetaschen

    Shouldn't this be reopened and kept open then?

  13. ashovlin commented on Mar 10, 2022

    @ashovlin
    Member

    Agreed, reopening.

    It does appear that the service response may vary depending on context.

    1. DynamoDB Streams - https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_StreamRecord.html

    The approximate date and time when the stream record was created, in UNIX epoch time format and rounded down to the closest second.

    1. Kinesis - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/kds.html

    ApproximateCreationDateTime indicates the time of the modification in milliseconds.

    I think we may be able to either try to recognize that we're within a Kinesis context, or else DateTimeConverter could be expanded to handle both seconds and milliseconds as the original issue suggested.

  14. added and removed
    response-requestedWaiting on additional info and feedback. Will move to close soon in 7 days.
    on Mar 10, 2022
  15. added
    p2This is a standard priority issue
    and removed on Nov 1, 2022
  16. ashishdhingra commented on Apr 22, 2024

    @ashishdhingra
    Contributor

    @cdegroot Good afternoon. The issue should be addressed as part of PR #1710. Could you please try upgrading to latest versions of Amazon.Lambda.Serialization.Json and Amazon.Lambda.Serialization.SystemTextJson, and verify if the issue is resolved?

    Thanks,
    Ashish

  17. added
    response-requestedWaiting on additional info and feedback. Will move to close soon in 7 days.
    on Apr 22, 2024
  18. github-actions commented on Apr 24, 2024

    @github-actions
    Contributor

    Comments on closed issues are hard for our team to see.
    If you need more assistance, please either tag a team member or open a new issue that references this one.
    If you wish to keep having a conversation with other community members under this issue feel free to do so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugThis issue is a bug.module/lambda-client-libp2This is a standard priority issuequeuedresponse-requestedWaiting on additional info and feedback. Will move to close soon in 7 days.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions