forked from dtm-labs/dtm
/
type.go
65 lines (57 loc) · 1.95 KB
/
type.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* Copyright (c) 2021 yedf. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
package dtmgrpc
import (
context "context"
"errors"
"github.com/dtm-labs/dtmdriver"
"github.com/sllt/dtm/client/dtmcli"
"github.com/sllt/dtm/client/dtmcli/dtmimp"
"github.com/sllt/dtm/client/dtmgrpc/dtmgimp"
grpc "google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
emptypb "google.golang.org/protobuf/types/known/emptypb"
)
// DtmError2GrpcError translate dtm error to grpc error
func DtmError2GrpcError(res interface{}) error {
e, ok := res.(error)
if ok && errors.Is(e, dtmimp.ErrFailure) {
return status.New(codes.Aborted, e.Error()).Err()
} else if ok && errors.Is(e, dtmimp.ErrOngoing) {
return status.New(codes.FailedPrecondition, e.Error()).Err()
}
return e
}
// GrpcError2DtmError translate grpc error to dtm error
func GrpcError2DtmError(err error) error {
st, _ := status.FromError(err)
if st != nil && st.Code() == codes.Aborted {
// version lower then v1.10, will specify Ongoing in code Aborted
if st.Message() == dtmcli.ResultOngoing {
return dtmcli.ErrOngoing
}
return dtmcli.ErrorMessage2Error(st.Message(), dtmcli.ErrFailure)
} else if st != nil && st.Code() == codes.FailedPrecondition {
return dtmcli.ErrorMessage2Error(st.Message(), dtmcli.ErrOngoing)
}
return err
}
// MustGenGid must gen a gid from grpcServer
func MustGenGid(grpcServer string) string {
dc := dtmgimp.MustGetDtmClient(grpcServer)
r, err := dc.NewGid(context.Background(), &emptypb.Empty{})
dtmimp.E2P(err)
return r.Gid
}
// UseDriver use the specified driver to handle grpc urls
func UseDriver(driverName string) error {
return dtmdriver.Use(driverName)
}
// AddUnaryInterceptor adds grpc.UnaryClientInterceptor
func AddUnaryInterceptor(interceptor grpc.UnaryClientInterceptor) {
dtmgimp.ClientInterceptors = append(dtmgimp.ClientInterceptors, interceptor)
}