From 0095552c3dca9ce63b159dd7fad25433d39488b2 Mon Sep 17 00:00:00 2001 From: Masakazu Ohtsuka Date: Mon, 26 Oct 2026 23:51:22 +0200 Subject: [PATCH] Migrate to AWS SDK for Go v2 - Replace firehoseiface.FirehoseAPI with FirehoseAPI, an interface that has only PutRecordBatch of *firehose.Client (v2). - Use types.Record (value) in place of *firehose.Record for Enqueue and ErrorHandler. - Rewrite isRetryable with smithy error types. It keeps the set of retryable errors of v1 (request.IsErrorRetryable, IsErrorThrottle, HTTP 429/500/502/503/504, and "read: connection reset by peer"). - Set the go directive to 1.24 (the minimum of aws-sdk-go-v2) and drop github.com/aws/aws-sdk-go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Khu7nnDtvrt5NV5H7kvCn6 --- README.md | 14 ++-- firequeue.go | 166 +++++++++++++++++++++++++++++++++++++--------- firequeue_test.go | 62 ++++++++--------- go.mod | 14 ++-- go.sum | 45 +++---------- retry_test.go | 88 ++++++++++++++++++++++++ 6 files changed, 279 insertions(+), 110 deletions(-) create mode 100644 retry_test.go diff --git a/README.md b/README.md index a24f35b..dae96df 100644 --- a/README.md +++ b/README.md @@ -19,19 +19,21 @@ firequeue is to ensure putting items to Amazon Kinesis Data Firehose with an in- import ( "context" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/firehose" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/firehose" + "github.com/aws/aws-sdk-go-v2/service/firehose/types" ) func main() { - sess := session.Must(session.NewSession()) - fh := firehose.New(sess) + ctx := context.Background() + cfg, err := config.LoadDefaultConfig(ctx) + ... + fh := firehose.NewFromConfig(cfg) fq := firequeue.New(fh, "DELIVERY_STREAM_NAME") - ctx := context.Background() go fq.Loop(ctx) // We should start looping before sending items - err := fq.Enqueue(&firehose.Record{...}) + err = fq.Enqueue(types.Record{...}) ... } ``` diff --git a/firequeue.go b/firequeue.go index 24eaf73..e5548be 100644 --- a/firequeue.go +++ b/firequeue.go @@ -6,19 +6,26 @@ import ( "expvar" "fmt" "log" + "net" + "net/url" "strings" "sync" "sync/atomic" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/service/firehose" - "github.com/aws/aws-sdk-go/service/firehose/firehoseiface" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/firehose" + "github.com/aws/aws-sdk-go-v2/service/firehose/types" + "github.com/aws/smithy-go" + smithyhttp "github.com/aws/smithy-go/transport/http" "github.com/cenkalti/backoff/v4" ) +// FirehoseAPI is the part of *firehose.Client that Queue uses. +type FirehoseAPI interface { + PutRecordBatch(ctx context.Context, params *firehose.PutRecordBatchInput, optFns ...func(*firehose.Options)) (*firehose.PutRecordBatchOutput, error) +} + // Option is a type for constructor options type Option func(*Queue) @@ -30,7 +37,7 @@ func Parallel(i int) Option { } // ErrorHandler is an option to specify the error handler -func ErrorHandler(fn func(error, []*firehose.Record)) Option { +func ErrorHandler(fn func(error, []types.Record)) Option { return func(q *Queue) { q.errorHandler = fn } @@ -76,10 +83,10 @@ func BatchInterval(period time.Duration) Option { } // New return new Queue -func New(fh firehoseiface.FirehoseAPI, DeliveryStreamName string, opts ...Option) *Queue { +func New(fh FirehoseAPI, DeliveryStreamName string, opts ...Option) *Queue { q := &Queue{ - queue: make([]*firehose.Record, 0), - workerCh: make(chan []*firehose.Record), + queue: make([]types.Record, 0), + workerCh: make(chan []types.Record), firehose: fh, initialized: make(chan struct{}), DeliveryStreamName: aws.String(DeliveryStreamName), @@ -92,9 +99,9 @@ func New(fh firehoseiface.FirehoseAPI, DeliveryStreamName string, opts ...Option // Queue manages a sending list for firehose type Queue struct { - queue []*firehose.Record + queue []types.Record mu sync.RWMutex - workerCh chan []*firehose.Record + workerCh chan []types.Record initialized chan struct{} initMu sync.Mutex @@ -102,8 +109,8 @@ type Queue struct { para int inFlightBatchCounter int32 maxQueueLength int - firehose firehoseiface.FirehoseAPI - errorHandler func(error, []*firehose.Record) + firehose FirehoseAPI + errorHandler func(error, []types.Record) batchSize int batchInterval time.Duration DeliveryStreamName *string @@ -207,10 +214,14 @@ func (q *Queue) loop(ctx context.Context) { } } +// isRetryable keeps the set of retryable errors that firequeue had with +// aws-sdk-go v1 (request.IsErrorRetryable, request.IsErrorThrottle and the +// HTTP status codes below). func isRetryable(err error) bool { - if reqfailure, ok := err.(awserr.RequestFailure); ok { + var respErr *smithyhttp.ResponseError + if errors.As(err, &respErr) { // ref. https://github.com/aws/aws-sdk-go/blob/fe72a52350a8962175bb71c531ec9724ce48abd8/aws/request/retryer.go#L228-L250 - switch reqfailure.StatusCode() { + switch respErr.HTTPStatusCode() { case 429, 500, @@ -220,21 +231,114 @@ func isRetryable(err error) bool { return true } } - return request.IsErrorRetryable(err) || - request.IsErrorThrottle(err) || - isErrConnectionResetByPeer(err) + return isErrorRetryable(err) || isErrConnectionResetByPeer(err) +} + +// retryableErrorCodes are the API error codes that aws-sdk-go v1 retried: +// retryableCodes, credsExpiredCodes and throttleCodes in aws/request/retryer.go. +// v1 also had the client-side codes "RequestError" and "ResponseTimeout". +// v2 does not use these codes. isErrorRetryable examines +// smithyhttp.RequestSendError in place of "RequestError". +var retryableErrorCodes = map[string]struct{}{ + "RequestTimeout": {}, + "RequestTimeoutException": {}, + + "ExpiredToken": {}, + "ExpiredTokenException": {}, + "RequestExpired": {}, + + "ProvisionedThroughputExceededException": {}, + "ThrottledException": {}, + "Throttling": {}, + "ThrottlingException": {}, + "RequestLimitExceeded": {}, + "RequestThrottled": {}, + "RequestThrottledException": {}, + "TooManyRequestsException": {}, + "PriorRequestNotComplete": {}, + "TransactionInProgressException": {}, + "EC2ThrottledException": {}, +} + +// isErrorRetryable follows request.IsErrorRetryable and +// request.IsErrorThrottle of aws-sdk-go v1 for the errors that the v2 client +// returns. +func isErrorRetryable(err error) bool { + // v1 did not retry "RequestCanceled". v2 returns *smithy.CanceledError or + // *aws.RequestCanceledError when the context is done. + var canceledErr interface{ CanceledError() bool } + if errors.As(err, &canceledErr) && canceledErr.CanceledError() { + return false + } + var apiErr smithy.APIError + if errors.As(err, &apiErr) { + _, ok := retryableErrorCodes[apiErr.ErrorCode()] + return ok + } + // v1 "SerializationError": v1 retried it when it retried the cause, + // and did not retry it without a cause. + var deserializationErr *smithy.DeserializationError + if errors.As(err, &deserializationErr) { + return deserializationErr.Err != nil && shouldRetryError(deserializationErr.Err) + } + // v1 "RequestError": v1 retried it when it retried the cause, + // and retried it without a cause. + var sendErr *smithyhttp.RequestSendError + if errors.As(err, &sendErr) { + return shouldRetryError(sendErr.Err) + } + // v1 did not retry errors from parameter validation either. + return false +} + +// shouldRetryError is the part of request.shouldRetryError in aws-sdk-go v1 +// that examines the causes of "RequestError" and "SerializationError". +// ref. https://github.com/aws/aws-sdk-go/blob/v1.35.33/aws/request/retryer.go#L168-L226 +func shouldRetryError(err error) bool { + switch e := err.(type) { + case *url.Error: + if strings.Contains(e.Error(), "connection refused") { + return true + } + return shouldRetryError(e.Err) + case interface{ Temporary() bool }: + if netErr, ok := e.(*net.OpError); ok && netErr.Op == "dial" { + return true + } + return e.Temporary() || isErrConnectionReset(err) + case nil: + return true + default: + switch err.Error() { + case "net/http: request canceled", + "net/http: request canceled while waiting for connection": + return false + } + return true + } } -// request.isErrConnectionReset, which is used inside request.IsErrorRetryable, -// intentionally marks false (do not retry) if it contains "read: connection reset". +// isErrConnectionReset is request.isErrConnectionReset in aws-sdk-go v1. +// It intentionally marks false (do not retry) if it contains "read: connection reset". // ref. https://github.com/aws/aws-sdk-go/blob/7814a7f61bf93cb54d00a5f97918c5501f07d351/aws/request/connection_reset_error.go#L7-L18 -// However, in firehose, the connection reset by peer error often bursts, so it is to be retry +func isErrConnectionReset(err error) bool { + msg := err.Error() + if strings.Contains(msg, "read: connection reset") { + return false + } + return strings.Contains(msg, "use of closed network connection") || + strings.Contains(msg, "connection reset") || + strings.Contains(msg, "broken pipe") +} + +// isErrConnectionResetByPeer catches "read: connection reset by peer", which isErrConnectionReset does not retry. +// In firehose, the connection reset by peer error often bursts, so it is to be retry func isErrConnectionResetByPeer(err error) bool { return strings.Contains(err.Error(), "read: connection reset by peer") } // Enqueue add data to queue -func (q *Queue) Enqueue(r *firehose.Record) error { +func (q *Queue) Enqueue(r types.Record) error { select { case <-q.initialized: // nop and continue to send @@ -271,7 +375,7 @@ func (q *Queue) sendBatch(bf backoff.BackOff) time.Duration { return q.batchInterval } -func (q *Queue) createBatch() []*firehose.Record { +func (q *Queue) createBatch() []types.Record { q.mu.Lock() defer q.mu.Unlock() @@ -280,13 +384,13 @@ func (q *Queue) createBatch() []*firehose.Record { batchSize = len(q.queue) } - batch := make([]*firehose.Record, batchSize) + batch := make([]types.Record, batchSize) copy(batch, q.queue) q.queue = q.queue[batchSize:] return batch } -func (q *Queue) attemptToSendBatch(batch []*firehose.Record) error { +func (q *Queue) attemptToSendBatch(batch []types.Record) error { atomic.AddInt32(&q.inFlightBatchCounter, 1) defer atomic.AddInt32(&q.inFlightBatchCounter, -1) @@ -297,7 +401,7 @@ func (q *Queue) attemptToSendBatch(batch []*firehose.Record) error { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - resp, err := q.firehose.PutRecordBatchWithContext(ctx, input) + resp, err := q.firehose.PutRecordBatch(ctx, input) if err != nil { // Handle non-retryable errors directly. if !isRetryable(err) { @@ -318,18 +422,18 @@ func (q *Queue) attemptToSendBatch(batch []*firehose.Record) error { return nil } -func (q *Queue) retryFailedRecords(batch []*firehose.Record, resp *firehose.PutRecordBatchOutput) { - retryRecords := make([]*firehose.Record, 0, *resp.FailedPutCount) +func (q *Queue) retryFailedRecords(batch []types.Record, resp *firehose.PutRecordBatchOutput) { + retryRecords := make([]types.Record, 0, *resp.FailedPutCount) for i, record := range batch { - if resp.RequestResponses != nil && resp.RequestResponses[i] != nil && resp.RequestResponses[i].ErrorCode != nil { + if resp.RequestResponses != nil && resp.RequestResponses[i].ErrorCode != nil { q.retryCount.Add(1) retryRecords = append(retryRecords, record) } } q.push(retryRecords...) } -func (q *Queue) handleError(err error, r []*firehose.Record) { +func (q *Queue) handleError(err error, r []types.Record) { if q.errorHandler != nil { q.errorHandler(err, r) return @@ -352,7 +456,7 @@ func (q *Queue) remaining() bool { return q.len() > 0 || q.inFlightBatch() } -func (q *Queue) push(r ...*firehose.Record) { +func (q *Queue) push(r ...types.Record) { q.mu.Lock() defer q.mu.Unlock() q.queue = append(q.queue, r...) diff --git a/firequeue_test.go b/firequeue_test.go index b2b8904..dd7685e 100644 --- a/firequeue_test.go +++ b/firequeue_test.go @@ -9,11 +9,10 @@ import ( "testing" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/service/firehose" - "github.com/aws/aws-sdk-go/service/firehose/firehoseiface" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/firehose" + "github.com/aws/aws-sdk-go-v2/service/firehose/types" + "github.com/aws/smithy-go" "github.com/natureglobal/firequeue" ) @@ -33,33 +32,32 @@ const ( var ecm = retryable -func (te *testAWSError) Code() string { +func (te *testAWSError) ErrorCode() string { switch ecm { case retryable: - return request.ErrCodeResponseTimeout + return "RequestTimeout" case unretryable: - return request.CanceledErrorCode + return "InvalidArgumentException" default: return "" } } -func (te *testAWSError) Message() string { +func (te *testAWSError) ErrorMessage() string { return "msg" } -func (te *testAWSError) OrigErr() error { - return fmt.Errorf("retryable error!") +func (te *testAWSError) ErrorFault() smithy.ErrorFault { + return smithy.FaultUnknown } -var _ awserr.Error = (*testAWSError)(nil) +var _ smithy.APIError = (*testAWSError)(nil) func init() { rand.Seed(time.Now().UTC().UnixNano()) } type testFirehose struct { - firehoseiface.FirehoseAPI counter uint32 } @@ -67,32 +65,32 @@ type testFirehose struct { // 0 means no error, 10 means always error. var fhErrorRate = 3 -func (tf *testFirehose) PutRecordBatch(input *firehose.PutRecordBatchInput) (*firehose.PutRecordBatchOutput, error) { +func (tf *testFirehose) PutRecordBatch(_ context.Context, input *firehose.PutRecordBatchInput, _ ...func(*firehose.Options)) (*firehose.PutRecordBatchOutput, error) { if rand.Intn(10) >= fhErrorRate { return &firehose.PutRecordBatchOutput{ - FailedPutCount: aws.Int64(0), + FailedPutCount: aws.Int32(0), }, nil } - var failedPutCounter int64 + var failedPutCounter int32 inputLength := len(input.Records) - firehoseResp := make([]*firehose.PutRecordBatchResponseEntry, inputLength) + firehoseResp := make([]types.PutRecordBatchResponseEntry, inputLength) for i := 0; i < inputLength; i++ { if rand.Intn(10) < fhErrorRate { - firehoseResp[i] = &firehose.PutRecordBatchResponseEntry{ + firehoseResp[i] = types.PutRecordBatchResponseEntry{ ErrorCode: aws.String("test_error"), ErrorMessage: aws.String("test_error_message"), } failedPutCounter++ } else { - firehoseResp[i] = &firehose.PutRecordBatchResponseEntry{ + firehoseResp[i] = types.PutRecordBatchResponseEntry{ RecordId: aws.String(fmt.Sprintf("%d", atomic.LoadUint32(&tf.counter))), } } } resp := &firehose.PutRecordBatchOutput{ RequestResponses: firehoseResp, - FailedPutCount: aws.Int64(failedPutCounter), + FailedPutCount: aws.Int32(failedPutCounter), } if failedPutCounter > 0 { @@ -101,9 +99,7 @@ func (tf *testFirehose) PutRecordBatch(input *firehose.PutRecordBatchInput) (*fi return resp, nil } -func (tf *testFirehose) PutRecordBatchWithContext(_ context.Context, r *firehose.PutRecordBatchInput, _ ...request.Option) (*firehose.PutRecordBatchOutput, error) { - return tf.PutRecordBatch(r) -} +var _ firequeue.FirehoseAPI = (*testFirehose)(nil) // success func TestQueue(t *testing.T) { @@ -141,7 +137,7 @@ func TestQueue(t *testing.T) { time.Sleep(1000 * time.Millisecond) for i := 0; i < tc.times; i++ { - err := q.Enqueue(&firehose.Record{ + err := q.Enqueue(types.Record{ Data: []byte("test"), }) if err != nil { @@ -194,7 +190,7 @@ func TestQueue_Para(t *testing.T) { time.Sleep(1000 * time.Millisecond) for i := 0; i < tc.times; i++ { - err := q.Enqueue(&firehose.Record{ + err := q.Enqueue(types.Record{ Data: []byte("test"), }) if err != nil { @@ -232,7 +228,7 @@ func TestQueue_SendWithoutLoop(t *testing.T) { tf := &testFirehose{} q := firequeue.New(tf, "env") - err := q.Enqueue(nil) + err := q.Enqueue(types.Record{}) if err == nil || !strings.Contains(err.Error(), "loop has not yet started") { t.Errorf("loop has not yet started error should be occurred but: %s", err) } @@ -280,7 +276,7 @@ func TestQueue_DrainProcess(t *testing.T) { time.Sleep(1000 * time.Millisecond) for i := 0; i < tt.count; i++ { - err := q.Enqueue(&firehose.Record{ + err := q.Enqueue(types.Record{ Data: []byte("test"), }) if err != nil { @@ -320,7 +316,7 @@ func TestQueue_DrainProcessPara(t *testing.T) { time.Sleep(1000 * time.Millisecond) for i := 0; i < tt.count; i++ { - err := q.Enqueue(&firehose.Record{ + err := q.Enqueue(types.Record{ Data: []byte("test"), }) if err != nil { @@ -352,7 +348,7 @@ func TestStats(t *testing.T) { time.Sleep(1000 * time.Millisecond) for i := 0; i < 100; i++ { - err := q.Enqueue(&firehose.Record{ + err := q.Enqueue(types.Record{ Data: []byte("test"), }) if err != nil { @@ -386,11 +382,11 @@ func TestStats_QueueFullError(t *testing.T) { go q.Loop(ctx) time.Sleep(1000 * time.Millisecond) - err := q.Enqueue(&firehose.Record{}) + err := q.Enqueue(types.Record{}) if err != nil { t.Errorf("error should not be occurred but: %s", err) } - err = q.Enqueue(&firehose.Record{}) + err = q.Enqueue(types.Record{}) if err == nil { t.Errorf("error should be occurred but not") } @@ -412,7 +408,7 @@ func TestStat_RetryCount(t *testing.T) { go q.Loop(ctx) time.Sleep(1000 * time.Millisecond) for i := 0; i < 10; i++ { - err := q.Enqueue(&firehose.Record{}) + err := q.Enqueue(types.Record{}) if err != nil { t.Errorf("error should not be occurred but: %s", err) } @@ -437,7 +433,7 @@ func TestStat_UnRetryableErrorCount(t *testing.T) { go q.Loop(ctx) time.Sleep(1000 * time.Millisecond) - err := q.Enqueue(&firehose.Record{}) + err := q.Enqueue(types.Record{}) if err != nil { t.Errorf("error should not be occurred but: %s", err) } diff --git a/go.mod b/go.mod index 23d1cde..50b0b77 100644 --- a/go.mod +++ b/go.mod @@ -1,11 +1,15 @@ module github.com/natureglobal/firequeue -go 1.14 +go 1.24 require ( - github.com/aws/aws-sdk-go v1.35.33 + github.com/aws/aws-sdk-go-v2 v1.47.4 + github.com/aws/aws-sdk-go-v2/service/firehose v1.52.6 + github.com/aws/smithy-go v1.28.6 github.com/cenkalti/backoff/v4 v4.1.0 - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/kr/pretty v0.1.0 // indirect - gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect +) + +require ( + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.7 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.7 // indirect ) diff --git a/go.sum b/go.sum index f239452..9339d56 100644 --- a/go.sum +++ b/go.sum @@ -1,37 +1,12 @@ -github.com/aws/aws-sdk-go v1.35.33 h1:8qPRZqCRok5i7VNN51k/Ky7CuyoXMdSs4mUfKyCqvPw= -github.com/aws/aws-sdk-go v1.35.33/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= +github.com/aws/aws-sdk-go-v2 v1.47.4 h1:bTvk6UdSSSvaQsfLVj1JRDEEqj/PDRwGf1KanaRzau0= +github.com/aws/aws-sdk-go-v2 v1.47.4/go.mod h1:XkrjAZvr705Nytv6PkPUhoSB2W9+vVHBp5oAWpkh8Ak= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.7 h1:fSNAt6hs4qLjb9tMZc6vj3PHlOCYGXK2JjJZ7AW2tf4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.7/go.mod h1:TMav+EuXQu5kNpZZz/6rIC8xx4mCsW+6AKHrjvOSAsE= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.7 h1:7NS6kqBjkWIN8P/AEdmtyq6eQGAhN1oHTZdzXclpH6Y= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.7/go.mod h1:1PFqtAUsIgF1nEVojzRJSf/v88zjzqrGW+w+UAtkXyQ= +github.com/aws/aws-sdk-go-v2/service/firehose v1.52.6 h1:qzgCLkXjA2Wajd4R7FP+N9tCWXkERA7oUSuAI4DDNW4= +github.com/aws/aws-sdk-go-v2/service/firehose v1.52.6/go.mod h1:HGPH3SG362zcQHdg24LX3nbW9ULc/vhPIK+PEoAWkJM= +github.com/aws/smithy-go v1.28.6 h1:Pj+/sUviNYjow8ELRtNwKHZ9ECeF+7pATX3+shjLIrw= +github.com/aws/smithy-go v1.28.6/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/cenkalti/backoff/v4 v4.1.0 h1:c8LkOFQTzuO0WBM/ae5HdGQuZPfPxp7lqBRwQRm4fSc= github.com/cenkalti/backoff/v4 v4.1.0/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b h1:uwuIcX0g4Yl1NC5XAz37xsr2lTtcqevgzYNVt49waME= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/retry_test.go b/retry_test.go new file mode 100644 index 0000000..aedd44f --- /dev/null +++ b/retry_test.go @@ -0,0 +1,88 @@ +package firequeue + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/url" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/retry" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + "github.com/aws/smithy-go" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +func TestIsRetryable(t *testing.T) { + operationError := func(err error) error { + return &smithy.OperationError{ServiceID: "Firehose", OperationName: "PutRecordBatch", Err: err} + } + responseError := func(statusCode int, err error) error { + return operationError(&awshttp.ResponseError{ + ResponseError: &smithyhttp.ResponseError{ + Response: &smithyhttp.Response{Response: &http.Response{StatusCode: statusCode}}, + Err: err, + }, + }) + } + apiError := func(statusCode int, code string) error { + return responseError(statusCode, &smithy.GenericAPIError{Code: code, Message: "msg"}) + } + sendError := func(err error) error { + return operationError(&smithyhttp.RequestSendError{Err: err}) + } + urlError := func(err error) error { + return &url.Error{Op: "Post", URL: "https://firehose.ap-northeast-1.amazonaws.com/", Err: err} + } + opError := func(op string, err error) error { + return &net.OpError{Op: op, Net: "tcp", Err: err} + } + + testCases := []struct { + name string + err error + want bool + }{ + {"429", apiError(429, "TooManyRequests"), true}, + {"500", apiError(500, "ServiceUnavailableException"), true}, + {"502", apiError(502, "BadGateway"), true}, + {"503", apiError(503, "ServiceUnavailableException"), true}, + {"504", apiError(504, "GatewayTimeout"), true}, + {"501", apiError(501, "NotImplemented"), false}, + {"400 throttle code", apiError(400, "ThrottlingException"), true}, + {"400 retryable code", apiError(400, "RequestTimeout"), true}, + {"400 expired creds code", apiError(400, "ExpiredTokenException"), true}, + {"400 invalid argument", apiError(400, "InvalidArgumentException"), false}, + {"400 resource not found", apiError(400, "ResourceNotFoundException"), false}, + {"400 limit exceeded", apiError(400, "LimitExceededException"), false}, + {"503 after max attempts", &retry.MaxAttemptsError{Attempt: 3, Err: apiError(503, "ServiceUnavailableException")}, true}, + {"canceled", operationError(&smithy.CanceledError{Err: context.DeadlineExceeded}), false}, + {"canceled while retry backoff", operationError(&aws.RequestCanceledError{Err: context.Canceled}), false}, + {"context done before attempt", operationError(context.Canceled), false}, + {"validation", operationError(&smithy.InvalidParamsError{Context: "PutRecordBatchInput"}), false}, + {"dial", sendError(urlError(opError("dial", errors.New("no such host")))), true}, + {"connection refused", sendError(urlError(opError("dial", errors.New("connect: connection refused")))), true}, + {"read: connection reset by peer", sendError(urlError(opError("read", errors.New("connection reset by peer")))), true}, + {"write: connection reset by peer", sendError(urlError(opError("write", errors.New("connection reset by peer")))), true}, + {"write: broken pipe", sendError(urlError(opError("write", errors.New("broken pipe")))), true}, + {"use of closed network connection", sendError(urlError(opError("read", net.ErrClosed))), true}, + {"read: not temporary", sendError(urlError(opError("read", errors.New("no route to host")))), false}, + {"EOF", sendError(urlError(io.EOF)), true}, + {"request canceled", sendError(urlError(errors.New("net/http: request canceled"))), false}, + {"deserialization", responseError(200, &smithy.DeserializationError{Err: errors.New("unexpected end of JSON input")}), true}, + {"deserialization of 400", responseError(400, &smithy.DeserializationError{Err: errors.New("unexpected end of JSON input")}), true}, + {"deserialization without cause", responseError(200, &smithy.DeserializationError{}), false}, + {"send without cause", sendError(nil), true}, + {"unknown", errors.New("unknown"), false}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if got := isRetryable(tc.err); got != tc.want { + t.Errorf("isRetryable(%v) = %t, want %t", tc.err, got, tc.want) + } + }) + } +}