// decodeGRPCSumRequest is a transport/grpc.DecodeRequestFunc that converts a
// gRPC sum request to a user-domain sum request. Primarily useful in a server.
438688
func decodeGRPCSumRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
	req := grpcReq.(*pb.SumRequest)
	return addendpoint.SumRequest{A: int(req.A), B: int(req.B)}, nil
}
1171384
func ToGRPC(err error) error {
	if err == nil {
		return nil
	}
	userMessage := trace.UserMessage(err)
	if trace.IsNotFound(err) {
		return grpc.Errorf(codes.NotFound, userMessage)
	}
	if trace.IsAlreadyExists(err) {
		return grpc.Errorf(codes.AlreadyExists, userMessage)
	}
	if trace.IsAccessDenied(err) {
		return grpc.Errorf(codes.PermissionDenied, userMessage)
	}
	if trace.IsCompareFailed(err) {
		return grpc.Errorf(codes.FailedPrecondition, userMessage)
	}
	if trace.IsBadParameter(err) || trace.IsOAuth2(err) {
		return grpc.Errorf(codes.InvalidArgument, userMessage)
	}
	if trace.IsLimitExceeded(err) {
		return grpc.Errorf(codes.ResourceExhausted, userMessage)
	}
	if trace.IsConnectionProblem(err) {
		return grpc.Errorf(codes.Unavailable, userMessage)
	}
	if trace.IsNotImplemented(err) {
		return grpc.Errorf(codes.Unimplemented, userMessage)
	}
	return grpc.Errorf(codes.Unknown, userMessage)
}
1028942
func (*MsgCodec) DecodeMsg(data []byte, msg api.Message) error {
	if msg == nil {
		return errors.New("nil message passed in")
	}

	var header interface{}

	// check which header is expected
	switch msg.GetMessageType() {
	case api.RequestMessage:
		header = new(VppRequestHeader)
	case api.ReplyMessage:
		header = new(VppReplyHeader)
	case api.EventMessage:
		header = new(VppEventHeader)
	default:
		header = new(VppOtherHeader)
	}

	buf := bytes.NewReader(data)

	// decode message header
	if err := struc.Unpack(buf, header); err != nil {
		return fmt.Errorf("failed to decode message header: %+v, error: %v", header, err)
	}

	// decode message content
	if err := struc.Unpack(buf, msg); err != nil {
		return fmt.Errorf("failed to decode message data: %+v, error: %v", data, err)
	}

	return nil
}
1369376
func NewGRPCClient(config ClientConfig) (*GRPCClient, error) {
	client := &GRPCClient{}

	// parse secure options
	err := client.parseSecureOptions(config.SecOpts)
	if err != nil {
		return client, err
	}

	// keepalive options
	var kap keepalive.ClientParameters
	if config.KaOpts != nil {
		kap = keepalive.ClientParameters{
			Time:    config.KaOpts.ClientInterval,
			Timeout: config.KaOpts.ClientTimeout}
	} else {
		// use defaults
		kap = keepalive.ClientParameters{
			Time:    DefaultKeepaliveOptions.ClientInterval,
			Timeout: DefaultKeepaliveOptions.ClientTimeout}
	}
	kap.PermitWithoutStream = true
	// set keepalive
	client.dialOpts = append(client.dialOpts, grpc.WithKeepaliveParams(kap))
	// Unless asynchronous connect is set, make connection establishment blocking.
	if !config.AsyncConnect {
		client.dialOpts = append(client.dialOpts, grpc.WithBlock())
		client.dialOpts = append(client.dialOpts, grpc.FailOnNonTempDialError(true))
	}
	client.timeout = config.Timeout
	// set send/recv message size to package defaults
	client.maxRecvMsgSize = MaxRecvMsgSize
	client.maxSendMsgSize = MaxSendMsgSize

	return client, nil
}
1048305
func InjectGRPC(md *metadata.MD) propagation.Injector {
	return func(sc model.SpanContext) error {
		if (model.SpanContext{}) == sc {
			return ErrEmptyContext
		}

		if sc.Debug {
			setGRPCHeader(md, Flags, "1")
		} else if sc.Sampled != nil {
			// Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled,
			// we don't send "X-B3-Sampled" if Debug is set.
			if *sc.Sampled {
				setGRPCHeader(md, Sampled, "1")
			} else {
				setGRPCHeader(md, Sampled, "0")
			}
		}

		if !sc.TraceID.Empty() && sc.ID > 0 {
			// set identifiers
			setGRPCHeader(md, TraceID, sc.TraceID.String())
			setGRPCHeader(md, SpanID, sc.ID.String())
			if sc.ParentID != nil {
				setGRPCHeader(md, ParentSpanID, sc.ParentID.String())
			}
		}

		return nil
	}
}
1363753
func (p *flowSpecPrefix6) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
	p.typ = BGPFlowSpecType(data[0])
	p.Offset = data[2]
	prefix := append([]byte{data[1]}, data[3:]...)
	return p.Prefix.DecodeFromBytes(prefix, options...)
}
916402
func DecodeHTTPRedirectRequest(requestURLHeader string) httptransport.DecodeRequestFunc {
	return func(_ context.Context, r *http.Request) (interface{}, error) {
		hostname := ""
		requestURL := r.Header.Get(requestURLHeader)
		if u, err := url.ParseRequestURI(requestURL); err == nil {
			hostname = u.Host
		}
		return redirectRequest{
			RequestURL: requestURL,
			Hostname:   hostname,
		}, nil
	}
}
34687
func ErrorFromGRPC(err error) error {
	// io.EOF is end of stream. Don't treat it as an error.
	if err == nil || err == io.EOF {
		return nil
	}
	code := codes.Unknown
	if s, ok := status.FromError(err); ok {
		code = s.Code()
	}
	return vterrors.Errorf(vtrpcpb.Code(code), "vttablet: %v", err)
}
554557
func FromGRPC(err error) error {
	if err == nil {
		return nil
	}

	var cls error // divide these into error classes, becomes the cause

	switch code(err) {
	case codes.InvalidArgument:
		cls = ErrInvalidArgument
	case codes.AlreadyExists:
		cls = ErrAlreadyExists
	case codes.NotFound:
		cls = ErrNotFound
	case codes.Unavailable:
		cls = ErrUnavailable
	case codes.FailedPrecondition:
		cls = ErrFailedPrecondition
	case codes.Unimplemented:
		cls = ErrNotImplemented
	default:
		cls = ErrUnknown
	}

	msg := rebaseMessage(cls, err)
	if msg != "" {
		err = errors.Wrap(cls, msg)
	} else {
		err = errors.WithStack(cls)
	}

	return err
}
1021378
func (s Server) ServeGRPC(ctx context.Context, req interface{}) (retctx context.Context, resp interface{}, err error) {
	// Retrieve gRPC metadata.
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		md = metadata.MD{}
	}

	if len(s.finalizer) > 0 {
		defer func() {
			for _, f := range s.finalizer {
				f(ctx, err)
			}
		}()
	}

	for _, f := range s.before {
		ctx = f(ctx, md)
	}

	var (
		request  interface{}
		response interface{}
		grpcResp interface{}
	)

	request, err = s.dec(ctx, req)
	if err != nil {
		s.errorHandler.Handle(ctx, err)
		return ctx, nil, err
	}

	response, err = s.e(ctx, request)
	if err != nil {
		s.errorHandler.Handle(ctx, err)
		return ctx, nil, err
	}

	var mdHeader, mdTrailer metadata.MD
	for _, f := range s.after {
		ctx = f(ctx, &mdHeader, &mdTrailer)
	}

	grpcResp, err = s.enc(ctx, response)
	if err != nil {
		s.errorHandler.Handle(ctx, err)
		return ctx, nil, err
	}

	if len(mdHeader) > 0 {
		if err = grpc.SendHeader(ctx, mdHeader); err != nil {
			s.errorHandler.Handle(ctx, err)
			return ctx, nil, err
		}
	}

	if len(mdTrailer) > 0 {
		if err = grpc.SetTrailer(ctx, mdTrailer); err != nil {
			s.errorHandler.Handle(ctx, err)
			return ctx, nil, err
		}
	}

	return ctx, grpcResp, nil
}
33914
func (service *Service) DecodeRequest(req *http.Request, v interface{}) error {
	body, contentType := req.Body, req.Header.Get("Content-Type")
	defer body.Close()

	if err := service.Decoder.Decode(v, body, contentType); err != nil {
		return fmt.Errorf("failed to decode request body with content type %#v: %s", contentType, err)
	}

	return nil
}
1027924
func DecodeGRPCCreateSessionRequest(_ context.Context, request interface{}) (interface{}, error) {
	req := request.(*pb.CreateSessionRequest)
	return createSessionRequest{
		Session: toSession(req.Session),
	}, nil
}
409505
func (c *Client) grpc() (proto.AuthServiceClient, error) {
	// it's ok to lock here, because Dial below is not locking
	c.Lock()
	defer c.Unlock()

	if c.grpcClient != nil {
		return c.grpcClient, nil
	}
	dialer := grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
		if c.isClosed() {
			return nil, trace.ConnectionProblem(nil, "client is closed")
		}
		c, err := c.DialContext(context.TODO(), "tcp", addr)
		if err != nil {
			log.Debugf("Dial to addr %v failed: %v.", addr, err)
		}
		return c, err
	})
	tlsConfig := c.TLS.Clone()
	tlsConfig.NextProtos = []string{http2.NextProtoTLS}
	log.Debugf("GRPC(): keep alive %v count: %v.", c.KeepAlivePeriod, c.KeepAliveCount)
	conn, err := grpc.Dial(teleport.APIDomain,
		dialer,
		grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
		grpc.WithKeepaliveParams(keepalive.ClientParameters{
			Time:    c.KeepAlivePeriod,
			Timeout: c.KeepAlivePeriod * time.Duration(c.KeepAliveCount),
		}),
	)
	if err != nil {
		return nil, trail.FromGRPC(err)
	}
	c.conn = conn
	c.grpcClient = proto.NewAuthServiceClient(c.conn)

	return c.grpcClient, nil
}
434344
func GRPCSupport() bool {
	verString := os.Getenv(PluginVaultVersionEnv)
	// If the env var is empty, we fall back to netrpc for backward compatibility.
	if verString == "" {
		return false
	}
	if verString != "unknown" {
		ver, err := version.NewVersion(verString)
		if err != nil {
			return true
		}
		// Due to some regressions on 0.9.2 & 0.9.3 we now require version 0.9.4
		// to allow the plugin framework to default to gRPC.
		constraint, err := version.NewConstraint(">= 0.9.4")
		if err != nil {
			return true
		}
		return constraint.Check(ver)
	}
	return true
}
655642
func (z *Series) DecodeMsg(dc *msgp.Reader) (err error) {
	var field []byte
	_ = field
	var zb0001 uint32
	zb0001, err = dc.ReadMapHeader()
	if err != nil {
		err = msgp.WrapError(err)
		return
	}
	for zb0001 > 0 {
		zb0001--
		field, err = dc.ReadMapKeyPtr()
		if err != nil {
			err = msgp.WrapError(err)
			return
		}
		switch msgp.UnsafeString(field) {
		case "Target":
			z.Target, err = dc.ReadString()
			if err != nil {
				err = msgp.WrapError(err, "Target")
				return
			}
		case "Datapoints":
			var zb0002 uint32
			zb0002, err = dc.ReadArrayHeader()
			if err != nil {
				err = msgp.WrapError(err, "Datapoints")
				return
			}
			if cap(z.Datapoints) >= int(zb0002) {
				z.Datapoints = (z.Datapoints)[:zb0002]
			} else {
				z.Datapoints = make([]schema.Point, zb0002)
			}
			for za0001 := range z.Datapoints {
				err = z.Datapoints[za0001].DecodeMsg(dc)
				if err != nil {
					err = msgp.WrapError(err, "Datapoints", za0001)
					return
				}
			}
		case "Tags":
			var zb0003 uint32
			zb0003, err = dc.ReadMapHeader()
			if err != nil {
				err = msgp.WrapError(err, "Tags")
				return
			}
			if z.Tags == nil {
				z.Tags = make(map[string]string, zb0003)
			} else if len(z.Tags) > 0 {
				for key := range z.Tags {
					delete(z.Tags, key)
				}
			}
			for zb0003 > 0 {
				zb0003--
				var za0002 string
				var za0003 string
				za0002, err = dc.ReadString()
				if err != nil {
					err = msgp.WrapError(err, "Tags")
					return
				}
				za0003, err = dc.ReadString()
				if err != nil {
					err = msgp.WrapError(err, "Tags", za0002)
					return
				}
				z.Tags[za0002] = za0003
			}
		case "Interval":
			z.Interval, err = dc.ReadUint32()
			if err != nil {
				err = msgp.WrapError(err, "Interval")
				return
			}
		case "QueryPatt":
			z.QueryPatt, err = dc.ReadString()
			if err != nil {
				err = msgp.WrapError(err, "QueryPatt")
				return
			}
		case "QueryFrom":
			z.QueryFrom, err = dc.ReadUint32()
			if err != nil {
				err = msgp.WrapError(err, "QueryFrom")
				return
			}
		case "QueryTo":
			z.QueryTo, err = dc.ReadUint32()
			if err != nil {
				err = msgp.WrapError(err, "QueryTo")
				return
			}
		case "QueryCons":
			err = z.QueryCons.DecodeMsg(dc)
			if err != nil {
				err = msgp.WrapError(err, "QueryCons")
				return
			}
		case "Consolidator":
			err = z.Consolidator.DecodeMsg(dc)
			if err != nil {
				err = msgp.WrapError(err, "Consolidator")
				return
			}
		default:
			err = dc.Skip()
			if err != nil {
				err = msgp.WrapError(err)
				return
			}
		}
	}
	return
}
9422
func NewGRPCProviderServerShim(p terraform.ResourceProvider) *GRPCProviderServer {
	sp, ok := p.(*schema.Provider)
	if !ok {
		return nil
	}

	return &GRPCProviderServer{
		provider: sp,
	}
}
67128
func WithGRPCOptions(opt ...grpc.CallOption) CallOption {
	return grpcOpt(append([]grpc.CallOption(nil), opt...))
}