utils.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. Copyright © The ESO Authors
  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. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package mysterybox
  14. import (
  15. "crypto/sha256"
  16. "encoding/hex"
  17. "fmt"
  18. "google.golang.org/grpc/codes"
  19. "google.golang.org/grpc/status"
  20. )
  21. // HashBytes calculate a hash of the bytes by sha256 algorithm.
  22. func HashBytes(b []byte) string {
  23. sum := sha256.Sum256(b)
  24. return hex.EncodeToString(sum[:])
  25. }
  26. // MapGrpcErrors maps grpc errors to human-readable errors.
  27. func MapGrpcErrors(op string, err error) error {
  28. st, ok := status.FromError(err)
  29. if !ok {
  30. return err
  31. }
  32. //nolint:exhaustive // intentionally handle only specific gRPC codes
  33. switch st.Code() {
  34. case codes.NotFound:
  35. return fmt.Errorf("%s: not found: %w", op, err)
  36. case codes.Unauthenticated, codes.PermissionDenied:
  37. return fmt.Errorf("%s: auth error: %w", op, err)
  38. case codes.Unavailable:
  39. return fmt.Errorf("%s: service unavailable: %w", op, err)
  40. case codes.DeadlineExceeded:
  41. return fmt.Errorf("%s: deadline exceeded: %w", op, err)
  42. case codes.Internal:
  43. return fmt.Errorf("%s: internal error: %w", op, err)
  44. default:
  45. return err
  46. }
  47. }