customizations.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package dynamodb
  2. import (
  3. "bytes"
  4. "hash/crc32"
  5. "io"
  6. "io/ioutil"
  7. "math"
  8. "strconv"
  9. "time"
  10. "github.com/aws/aws-sdk-go/aws"
  11. "github.com/aws/aws-sdk-go/aws/awserr"
  12. "github.com/aws/aws-sdk-go/aws/client"
  13. "github.com/aws/aws-sdk-go/aws/request"
  14. )
  15. type retryer struct {
  16. client.DefaultRetryer
  17. }
  18. func (d retryer) RetryRules(r *request.Request) time.Duration {
  19. delay := time.Duration(math.Pow(2, float64(r.RetryCount))) * 50
  20. return delay * time.Millisecond
  21. }
  22. func init() {
  23. initClient = func(c *client.Client) {
  24. r := retryer{}
  25. if c.Config.MaxRetries == nil || aws.IntValue(c.Config.MaxRetries) == aws.UseServiceDefaultRetries {
  26. r.NumMaxRetries = 10
  27. } else {
  28. r.NumMaxRetries = *c.Config.MaxRetries
  29. }
  30. c.Retryer = r
  31. c.Handlers.Build.PushBack(disableCompression)
  32. c.Handlers.Unmarshal.PushFront(validateCRC32)
  33. }
  34. }
  35. func drainBody(b io.ReadCloser, length int64) (out *bytes.Buffer, err error) {
  36. if length < 0 {
  37. length = 0
  38. }
  39. buf := bytes.NewBuffer(make([]byte, 0, length))
  40. if _, err = buf.ReadFrom(b); err != nil {
  41. return nil, err
  42. }
  43. if err = b.Close(); err != nil {
  44. return nil, err
  45. }
  46. return buf, nil
  47. }
  48. func disableCompression(r *request.Request) {
  49. r.HTTPRequest.Header.Set("Accept-Encoding", "identity")
  50. }
  51. func validateCRC32(r *request.Request) {
  52. if r.Error != nil {
  53. return // already have an error, no need to verify CRC
  54. }
  55. // Checksum validation is off, skip
  56. if aws.BoolValue(r.Config.DisableComputeChecksums) {
  57. return
  58. }
  59. // Try to get CRC from response
  60. header := r.HTTPResponse.Header.Get("X-Amz-Crc32")
  61. if header == "" {
  62. return // No header, skip
  63. }
  64. expected, err := strconv.ParseUint(header, 10, 32)
  65. if err != nil {
  66. return // Could not determine CRC value, skip
  67. }
  68. buf, err := drainBody(r.HTTPResponse.Body, r.HTTPResponse.ContentLength)
  69. if err != nil { // failed to read the response body, skip
  70. return
  71. }
  72. // Reset body for subsequent reads
  73. r.HTTPResponse.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes()))
  74. // Compute the CRC checksum
  75. crc := crc32.ChecksumIEEE(buf.Bytes())
  76. if crc != uint32(expected) {
  77. // CRC does not match, set a retryable error
  78. r.Retryable = aws.Bool(true)
  79. r.Error = awserr.New("CRC32CheckFailed", "CRC32 integrity check failed", nil)
  80. }
  81. }