// UnaryServerInterceptor returns a new unary server interceptors that adds logrus.Entry to the context.
515560
func UnaryServerInterceptor(entry *logrus.Entry, opts ...Option) grpc.UnaryServerInterceptor {
	o := evaluateServerOpt(opts)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		startTime := time.Now()
		newCtx := newLoggerForCall(ctx, entry, info.FullMethod, startTime)

		resp, err := handler(newCtx, req)

		if !o.shouldLog(info.FullMethod, err) {
			return resp, err
		}
		code := o.codeFunc(err)
		level := o.levelFunc(code)
		durField, durVal := o.durationFunc(time.Since(startTime))
		fields := logrus.Fields{
			"grpc.code": code.String(),
			durField:    durVal,
		}
		if err != nil {
			fields[logrus.ErrorKey] = err
		}

		levelLogf(
			ctx_logrus.Extract(newCtx).WithFields(fields), // re-extract logger from newCtx, as it may have extra fields that changed in the holder.
			level,
			"finished unary call with code "+code.String())

		return resp, err
	}
}
270234
func ErrorCodeUnaryServerInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		resp, err = handler(ctx, req)
		return resp, kubeErrToGRPC(err)
	}
}
767904
func (jf openTracingService) AddGrpcServerOptions(addInterceptors func(s grpc.StreamServerInterceptor, u grpc.UnaryServerInterceptor)) {
	addInterceptors(otgrpc.OpenTracingStreamServerInterceptor(jf.Tracer), otgrpc.OpenTracingServerInterceptor(jf.Tracer))
}
598701
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor {
	o := evaluateOptions(opts)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		newCtx := newTagsForCtx(ctx)
		if o.requestFieldsFunc != nil {
			setRequestFieldTags(newCtx, o.requestFieldsFunc, info.FullMethod, req)
		}
		return handler(newCtx, req)
	}
}
385130
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor {
	o := evaluateOptions(opts)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if o.filterOutFunc != nil && !o.filterOutFunc(ctx, info.FullMethod) {
			return handler(ctx, req)
		}
		newCtx, serverSpan := newServerSpanFromInbound(ctx, o.tracer, info.FullMethod)
		resp, err := handler(newCtx, req)
		finishServerSpan(ctx, serverSpan, err)
		return resp, err
	}
}
1359381
func chainStreamClientInterceptors(cc *ClientConn) {
	interceptors := cc.dopts.chainStreamInts
	// Prepend dopts.streamInt to the chaining interceptors if it exists, since streamInt will
	// be executed before any other chained interceptors.
	if cc.dopts.streamInt != nil {
		interceptors = append([]StreamClientInterceptor{cc.dopts.streamInt}, interceptors...)
	}
	var chainedInt StreamClientInterceptor
	if len(interceptors) == 0 {
		chainedInt = nil
	} else if len(interceptors) == 1 {
		chainedInt = interceptors[0]
	} else {
		chainedInt = func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) {
			return interceptors[0](ctx, desc, cc, method, getChainStreamer(interceptors, 0, streamer), opts...)
		}
	}
	cc.dopts.streamInt = chainedInt
}
1132399
func (o Middleware) SubscribeInterceptor(opts pubsub.HandlerOptions, next pubsub.MsgHandler) pubsub.MsgHandler {
	return func(ctx context.Context, m pubsub.Msg) error {
		start := time.Now()
		err := next(ctx, m)
		elapsed := time.Now().Sub(start)

		var traceID string
		span := opentracing.SpanFromContext(ctx)
		if span != nil {
			zs, ok := span.Context().(zipkintracing.SpanContext)
			if ok {
				traceID = zs.TraceID.ToHex()
			}
		}

		fields := logrus.Fields{
			"component": "pubsub",
			"topic":     opts.Topic,
			"handler":   opts.Name,
			"duration":  elapsed,
			"metadata":  m.Metadata,
		}

		if err != nil {
			de, ok := err.(errors.DropboxError)
			if ok {
				fields["err"] = de.GetMessage()
			} else {
				fields["err"] = err
			}
		}

		if m.ID != "" {
			fields["id"] = m.ID
		}

		if traceID != "" {
			fields["trace-id"] = traceID
		}

		logrus.WithFields(fields).Debug("Processed PubSub Msg")
		return err
	}
}
1169788
func PanicLoggerUnaryServerInterceptor(log *logrus.Entry) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
		defer func() {
			if r := recover(); r != nil {
				log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack())
				err = status.Errorf(codes.Internal, "%s", r)
			}
		}()
		return handler(ctx, req)
	}
}
1298187
func UserAgentUnaryServerInterceptor(clientName, constraintStr string) grpc.UnaryServerInterceptor {
	userAgentEnforcer := newUserAgentEnforcer(clientName, constraintStr)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if err := userAgentEnforcer(ctx); err != nil {
			return nil, err
		}
		return handler(ctx, req)
	}
}
1149872
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor {
	o := evaluateOptions(opts)
	return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		newCtx := newTagsForCtx(stream.Context())
		if o.requestFieldsFunc == nil {
			// Short-circuit, don't do the expensive bit of allocating a wrappedStream.
			wrappedStream := grpc_middleware.WrapServerStream(stream)
			wrappedStream.WrappedContext = newCtx
			return handler(srv, wrappedStream)
		}
		wrapped := &wrappedStream{stream, info, o, newCtx, true}
		err := handler(srv, wrapped)
		return err
	}
}
70253
func (eu ServerErrorUnwrapper) UnwrapError(arg interface{}) (appError error, dispatchError error) {
	s, ok := arg.(*keybase1.Status)
	if !ok {
		return nil, errors.New("Error converting arg to keybase1.Status object in ServerErrorUnwrapper.UnwrapError")
	}

	if s == nil || s.Code == 0 {
		return nil, nil
	}

	switch s.Code {
	case StatusCodeServerError:
		appError = ServerError{Msg: s.Desc}
		break
	case StatusCodeServerErrorBadRequest:
		appError = ServerErrorBadRequest{Msg: s.Desc}
		break
	case StatusCodeServerErrorUnauthorized:
		appError = ServerErrorUnauthorized{Msg: s.Desc}
		break
	case StatusCodeServerErrorOverQuota:
		quotaErr := ServerErrorOverQuota{Msg: s.Desc}
		for _, f := range s.Fields {
			if f.Key == "QUOTA_USAGE" {
				quotaErr.Usage, _ = strconv.ParseInt(f.Value, 10, 64)
			} else if f.Key == "QUOTA_LIMIT" {
				quotaErr.Limit, _ = strconv.ParseInt(f.Value, 10, 64)
			} else if f.Key == "QUOTA_THROTTLE" {
				quotaErr.Throttled, _ = strconv.ParseBool(f.Value)
			}
		}
		appError = quotaErr
		break
	case StatusCodeServerErrorBlockNonExistent:
		appError = ServerErrorBlockNonExistent{Msg: s.Desc}
		break
	case StatusCodeServerErrorBlockArchived:
		appError = ServerErrorBlockArchived{Msg: s.Desc}
		break
	case StatusCodeServerErrorNoPermission:
		appError = ServerErrorNoPermission{Msg: s.Desc}
		break
	case StatusCodeServerErrorThrottle:
		appError = ServerErrorThrottle{Msg: s.Desc}
		break
	case StatusCodeServerErrorBlockDeleted:
		appError = ServerErrorBlockDeleted{Msg: s.Desc}
		break
	case StatusCodeServerErrorNonceNonExistent:
		appError = ServerErrorNonceNonExistent{Msg: s.Desc}
		break
	case StatusCodeServerErrorMaxRefExceeded:
		appError = ServerErrorMaxRefExceeded{Msg: s.Desc}
		break
	default:
		ase := libkb.AppStatusError{
			Code:   s.Code,
			Name:   s.Name,
			Desc:   s.Desc,
			Fields: make(map[string]string),
		}
		for _, f := range s.Fields {
			ase.Fields[f.Key] = f.Value
		}
		appError = ase
	}

	return appError, nil
}
804167
func RegisterInterceptor(s ServiceInfoProvider, i *Interceptor) (err error) {
	if i.trackPeers {
		return nil
	}

	infos := s.GetServiceInfo()
	for sn, info := range infos {
		for _, m := range info.Methods {
			t := handlerType(m.IsClientStream, m.IsServerStream)

			for c := uint32(0); c <= 15; c++ {
				requestLabels := prometheus.Labels{
					"service": sn,
					"handler": m.Name,
					"code":    codes.Code(c).String(),
					"type":    t,
				}
				messageLabels := prometheus.Labels{
					"service": sn,
					"handler": m.Name,
				}

				// server
				if _, err = i.monitoring.server.errors.GetMetricWith(requestLabels); err != nil {
					return err
				}
				if _, err = i.monitoring.server.requestsTotal.GetMetricWith(requestLabels); err != nil {
					return err
				}
				if _, err = i.monitoring.server.requestDuration.GetMetricWith(requestLabels); err != nil {
					return err
				}
				if m.IsClientStream {
					if _, err = i.monitoring.server.messagesReceived.GetMetricWith(messageLabels); err != nil {
						return err
					}
				}
				if m.IsServerStream {
					if _, err = i.monitoring.server.messagesSend.GetMetricWith(messageLabels); err != nil {
						return err
					}
				}
			}
		}
	}
	return nil
}
1210904
func (c Context) AnErr(key string, err error) Context {
	marshaled := ErrorMarshalFunc(err)
	switch m := marshaled.(type) {
	case nil:
		return c
	case LogObjectMarshaler:
		return c.Object(key, m)
	case error:
		return c.Str(key, m.Error())
	case string:
		return c.Str(key, m)
	default:
		return c.Interface(key, m)
	}
}
930204
func (eu ServerErrorUnwrapper) UnwrapError(arg interface{}) (appError error, dispatchError error) {
	s, ok := arg.(*keybase1.Status)
	if !ok {
		return nil, errors.New("Error converting arg to keybase1.Status object in ServerErrorUnwrapper.UnwrapError")
	}

	if s == nil || s.Code == 0 {
		return nil, nil
	}

	switch s.Code {
	case StatusCodeServerError:
		appError = ServerError{errors.New(s.Desc)}
		break
	case StatusCodeServerErrorBadRequest:
		appError = ServerErrorBadRequest{Reason: s.Desc}
		break
	case StatusCodeServerErrorConflictRevision:
		appError = ServerErrorConflictRevision{Desc: s.Desc}
		break
	case StatusCodeServerErrorConflictPrevRoot:
		appError = ServerErrorConflictPrevRoot{Desc: s.Desc}
		break
	case StatusCodeServerErrorConflictDiskUsage:
		appError = ServerErrorConflictDiskUsage{Desc: s.Desc}
		break
	case StatusCodeServerErrorLocked:
		appError = ServerErrorLocked{}
		break
	case StatusCodeServerErrorUnauthorized:
		appError = ServerErrorUnauthorized{}
		break
	case StatusCodeServerErrorThrottle:
		var suggestedRetryIn *time.Duration
		for _, kv := range s.Fields {
			if kv.Key == "suggestedRetryInMS" {
				if ms, err := strconv.Atoi(kv.Value); err != nil {
					d := time.Duration(ms) * time.Millisecond
					suggestedRetryIn = &d
				}
				break
			}
		}
		appError = ServerErrorThrottle{
			Err:              errors.New(s.Desc),
			SuggestedRetryIn: suggestedRetryIn,
		}
		break
	case StatusCodeServerErrorConditionFailed:
		shouldThrottle := false
		for _, kv := range s.Fields {
			if kv.Key == "ShouldThrottle" {
				shouldThrottle, _ = strconv.ParseBool(kv.Value)
				break
			}
		}
		appError = ServerErrorConditionFailed{
			Err:            errors.New(s.Desc),
			ShouldThrottle: shouldThrottle,
		}
		break
	case StatusCodeServerErrorWriteAccess:
		appError = ServerErrorWriteAccess{}
		break
	case StatusCodeServerErrorConflictFolderMapping:
		appError = ServerErrorConflictFolderMapping{Desc: s.Desc}
		break
	case StatusCodeServerErrorTooManyFoldersCreated:
		err := ServerErrorTooManyFoldersCreated{}
		for _, f := range s.Fields {
			switch f.Key {
			case "Limit":
				err.Limit, _ = strconv.ParseUint(f.Value, 10, 64)
			case "Created":
				err.Created, _ = strconv.ParseUint(f.Value, 10, 64)
			}
		}
		appError = err
		break
	case StatusCodeServerErrorCannotReadFinalizedTLF:
		appError = ServerErrorCannotReadFinalizedTLF{}
		break
	case StatusCodeServerErrorLockConflict:
		appError = ServerErrorLockConflict{}
		break
	case StatusCodeServerErrorClassicTLFDoesNotExist:
		appError = ServerErrorClassicTLFDoesNotExist{}
		break
	case StatusCodeServerErrorMissingFolderHandle:
		appError = ServerErrorMissingFolderHandle{}
		break
	default:
		ase := libkb.AppStatusError{
			Code:   s.Code,
			Name:   s.Name,
			Desc:   s.Desc,
			Fields: make(map[string]string),
		}
		for _, f := range s.Fields {
			ase.Fields[f.Key] = f.Value
		}
		appError = ase
	}

	return appError, nil
}
426540
func PayloadUnaryClientInterceptor(logger *zap.Logger, decider grpc_logging.ClientPayloadLoggingDecider) grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		if !decider(ctx, method) {
			return invoker(ctx, method, req, reply, cc, opts...)
		}
		logEntry := logger.With(newClientLoggerFields(ctx, method)...)
		logProtoMessageAsJson(logEntry, req, "grpc.request.content", "client request payload logged as grpc.request.content")
		err := invoker(ctx, method, req, reply, cc, opts...)
		if err == nil {
			logProtoMessageAsJson(logEntry, reply, "grpc.response.content", "client response payload logged as grpc.response.content")
		}
		return err
	}
}
213264
func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption {
	return grpc.UnaryInterceptor(ChainUnaryServer(interceptors...))
}
766339
func UnaryClientInterceptor(opts ...Option) grpc.UnaryClientInterceptor {
	o := evaluateOptions(opts)
	return func(parentCtx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		if o.filterOutFunc != nil && !o.filterOutFunc(parentCtx, method) {
			return invoker(parentCtx, method, req, reply, cc, opts...)
		}
		newCtx, clientSpan := newClientSpanFromContext(parentCtx, o.tracer, method)
		err := invoker(newCtx, method, req, reply, cc, opts...)
		finishClientSpan(clientSpan, err)
		return err
	}
}