// ContextToGRPC moves a JWT from context to grpc metadata. Particularly
// useful for clients.
437675
func ContextToGRPC() grpc.ClientRequestFunc {
	return func(ctx context.Context, md *metadata.MD) context.Context {
		token, ok := ctx.Value(JWTTokenContextKey).(string)
		if ok {
			// capital "Key" is illegal in HTTP/2.
			(*md)["authorization"] = []string{generateAuthHeaderFromToken(token)}
		}

		return ctx
	}
}
169210
func GetGRPCHeader(md *metadata.MD, key string) string {
	v := (*md)[key]
	if len(v) < 1 {
		return ""
	}
	return v[len(v)-1]
}
1152969
func (c *ServerTokenCall) Context(ctx context.Context) *ServerTokenCall {
	c.ctx_ = ctx
	return c
}
981960
func (b *Builder) RegisterGRPC(s *grpc.Server) {
	b.controller.Register(s)
}
1040803
func Send(ctx context.Context, err error) error {
	meta, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		meta = metadata.New(nil)
	}
	if trace.IsDebug() {
		SetDebugInfo(err, meta)
	}
	if len(meta) != 0 {
		sendErr := grpc.SendHeader(ctx, meta)
		if sendErr != nil {
			return trace.NewAggregate(err, sendErr)
		}
	}
	return ToGRPC(err)
}
998153
func (s *PutScriptService) Context(context string) *PutScriptService {
	s.context = context
	return s
}
403327
func (s *Span) Context() opentracing.SpanContext {
	s.Lock()
	defer s.Unlock()
	return s.context
}
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)
}
1255966
func (cc *CachingConnector) DialContext(ctx context.Context, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
	logger.Debugf("DialContext: %s", target)

	cc.lock.Lock()
	c, ok := cc.loadConn(target)
	if !ok {
		createdConn, err := cc.createConn(ctx, target, opts...)
		if err != nil {
			cc.lock.Unlock()
			return nil, errors.WithMessage(err, "connection creation failed")
		}
		c = createdConn
	}

	cc.lock.Unlock()

	if err := cc.openConn(ctx, c); err != nil {
		cc.lock.Lock()
		setClosed(c)
		cc.lock.Unlock()
		return nil, errors.Errorf("dialing connection timed out [%s]", target)
	}
	return c.conn, nil
}
412236
func gRPCifyAndLogErr(c context.Context, methodName string, rsp proto.Message, err error) error {
	return grpcutil.GRPCifyAndLogErr(c, err)
}
723679
func withGRPCNamespaceHeader(ctx context.Context, namespace string) context.Context {
	// also store on the grpc headers so it gets picked up by any clients that
	// are using this.
	nsheader := metadata.Pairs(GRPCHeader, namespace)
	md, ok := metadata.FromOutgoingContext(ctx) // merge with outgoing context.
	if !ok {
		md = nsheader
	} else {
		// order ensures the latest is first in this list.
		md = metadata.Join(nsheader, md)
	}

	return metadata.NewOutgoingContext(ctx, md)
}
595538
func EncodeGRPCFindSessionByTokenResponse(_ context.Context, response interface{}) (interface{}, error) {
	res := response.(findSessionByTokenResponse)
	return &pb.FindSessionByTokenReply{
		Session: toPBSession(res.Session),
		Err:     toPBError(res.Err),
	}, nil
}
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
}
740575
func (builder *UpdateGSetCommandBuilder) WithContext(context []byte) *UpdateGSetCommandBuilder {
	builder.protobuf.Context = context
	return builder
}
1120894
func SwarmFromGRPC(c swarmapi.Cluster) types.Swarm {
	swarm := types.Swarm{
		ClusterInfo: types.ClusterInfo{
			ID: c.ID,
			Spec: types.Spec{
				Orchestration: types.OrchestrationConfig{
					TaskHistoryRetentionLimit: &c.Spec.Orchestration.TaskHistoryRetentionLimit,
				},
				Raft: types.RaftConfig{
					SnapshotInterval:           c.Spec.Raft.SnapshotInterval,
					KeepOldSnapshots:           &c.Spec.Raft.KeepOldSnapshots,
					LogEntriesForSlowFollowers: c.Spec.Raft.LogEntriesForSlowFollowers,
					HeartbeatTick:              int(c.Spec.Raft.HeartbeatTick),
					ElectionTick:               int(c.Spec.Raft.ElectionTick),
				},
				EncryptionConfig: types.EncryptionConfig{
					AutoLockManagers: c.Spec.EncryptionConfig.AutoLockManagers,
				},
				CAConfig: types.CAConfig{
					// do not include the signing CA cert or key (it should already be redacted via the swarm APIs) -
					// the key because it's secret, and the cert because otherwise doing a get + update on the spec
					// can cause issues because the key would be missing and the cert wouldn't
					ForceRotate: c.Spec.CAConfig.ForceRotate,
				},
			},
			TLSInfo: types.TLSInfo{
				TrustRoot: string(c.RootCA.CACert),
			},
			RootRotationInProgress: c.RootCA.RootRotation != nil,
			DefaultAddrPool:        c.DefaultAddressPool,
			SubnetSize:             c.SubnetSize,
			DataPathPort:           c.VXLANUDPPort,
		},
		JoinTokens: types.JoinTokens{
			Worker:  c.RootCA.JoinTokens.Worker,
			Manager: c.RootCA.JoinTokens.Manager,
		},
	}

	issuerInfo, err := ca.IssuerFromAPIRootCA(&c.RootCA)
	if err == nil && issuerInfo != nil {
		swarm.TLSInfo.CertIssuerSubject = issuerInfo.Subject
		swarm.TLSInfo.CertIssuerPublicKey = issuerInfo.PublicKey
	}

	heartbeatPeriod, _ := gogotypes.DurationFromProto(c.Spec.Dispatcher.HeartbeatPeriod)
	swarm.Spec.Dispatcher.HeartbeatPeriod = heartbeatPeriod

	swarm.Spec.CAConfig.NodeCertExpiry, _ = gogotypes.DurationFromProto(c.Spec.CAConfig.NodeCertExpiry)

	for _, ca := range c.Spec.CAConfig.ExternalCAs {
		swarm.Spec.CAConfig.ExternalCAs = append(swarm.Spec.CAConfig.ExternalCAs, &types.ExternalCA{
			Protocol: types.ExternalCAProtocol(strings.ToLower(ca.Protocol.String())),
			URL:      ca.URL,
			Options:  ca.Options,
			CACert:   string(ca.CACert),
		})
	}

	// Meta
	swarm.Version.Index = c.Meta.Version.Index
	swarm.CreatedAt, _ = gogotypes.TimestampFromProto(c.Meta.CreatedAt)
	swarm.UpdatedAt, _ = gogotypes.TimestampFromProto(c.Meta.UpdatedAt)

	// Annotations
	swarm.Spec.Annotations = annotationsFromGRPC(c.Spec.Annotations)

	return swarm
}
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
	}
}
252542
func (c *FinalizeGsUploadCall) Context(ctx context.Context) *FinalizeGsUploadCall {
	c.ctx_ = ctx
	return c
}