github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/doltcore/remotestorage/retry.go (about)

     1  // Copyright 2019 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package remotestorage
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  	"fmt"
    21  	"net/http"
    22  
    23  	"github.com/cenkalti/backoff"
    24  	"google.golang.org/grpc/codes"
    25  	"google.golang.org/grpc/status"
    26  )
    27  
    28  var HttpError = errors.New("http")
    29  
    30  // ProcessHttpResp converts an http.Response, and error into a RetriableCallState
    31  func processHttpResp(resp *http.Response, err error) error {
    32  	if errors.Is(err, context.Canceled) {
    33  		return backoff.Permanent(err)
    34  	}
    35  
    36  	if err == nil {
    37  		if resp.StatusCode/100 == 2 {
    38  			return nil
    39  		}
    40  
    41  		return fmt.Errorf("error: %w %d", HttpError, resp.StatusCode)
    42  	}
    43  
    44  	return err
    45  }
    46  
    47  // ProcessGrpcErr converts an error from a Grpc call into a RetriableCallState
    48  func processGrpcErr(err error) error {
    49  	if err == nil {
    50  		return nil
    51  	}
    52  
    53  	st, ok := status.FromError(err)
    54  
    55  	if !ok {
    56  		return err
    57  	}
    58  
    59  	switch st.Code() {
    60  	case codes.OK:
    61  		return nil
    62  
    63  	case codes.Canceled,
    64  		codes.Unknown,
    65  		codes.DeadlineExceeded,
    66  		codes.Aborted,
    67  		codes.Internal,
    68  		codes.DataLoss,
    69  		codes.ResourceExhausted,
    70  		codes.Unavailable:
    71  		return err
    72  
    73  	case codes.InvalidArgument,
    74  		codes.NotFound,
    75  		codes.AlreadyExists,
    76  		codes.PermissionDenied,
    77  		codes.FailedPrecondition,
    78  		codes.Unimplemented,
    79  		codes.OutOfRange,
    80  		codes.Unauthenticated:
    81  		return backoff.Permanent(err)
    82  	}
    83  
    84  	return err
    85  }