// Licensed to the LF AI & Data foundation under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package grpcproxy

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/cockroachdb/errors"
	"github.com/gin-gonic/gin"
	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	"github.com/soheilhy/cmux"
	clientv3 "go.etcd.io/etcd/client/v3"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.uber.org/atomic"
	"golang.org/x/net/http2"
	"golang.org/x/net/http2/h2c"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/health/grpc_health_v1"
	"google.golang.org/grpc/keepalive"
	"google.golang.org/grpc/status"

	"github.com/milvus-io/milvus-proto/go-api/v3/commonpb"
	"github.com/milvus-io/milvus-proto/go-api/v3/federpb"
	"github.com/milvus-io/milvus-proto/go-api/v3/milvuspb"
	mix "github.com/milvus-io/milvus/internal/distributed/mixcoord/client"
	"github.com/milvus-io/milvus/internal/distributed/proxy/httpserver"
	"github.com/milvus-io/milvus/internal/distributed/streaming"
	"github.com/milvus-io/milvus/internal/distributed/utils"
	mhttp "github.com/milvus-io/milvus/internal/http"
	"github.com/milvus-io/milvus/internal/proxy"
	"github.com/milvus-io/milvus/internal/proxy/accesslog"
	"github.com/milvus-io/milvus/internal/proxy/connection"
	"github.com/milvus-io/milvus/internal/storage"
	"github.com/milvus-io/milvus/internal/types"
	"github.com/milvus-io/milvus/internal/util/componentutil"
	"github.com/milvus-io/milvus/internal/util/dependency"
	_ "github.com/milvus-io/milvus/internal/util/grpcclient"
	"github.com/milvus-io/milvus/internal/util/hookutil"
	"github.com/milvus-io/milvus/pkg/v3/metrics"
	"github.com/milvus-io/milvus/pkg/v3/mlog"
	"github.com/milvus-io/milvus/pkg/v3/proto/internalpb"
	"github.com/milvus-io/milvus/pkg/v3/proto/proxypb"
	"github.com/milvus-io/milvus/pkg/v3/tracer"
	"github.com/milvus-io/milvus/pkg/v3/util"
	"github.com/milvus-io/milvus/pkg/v3/util/etcd"
	"github.com/milvus-io/milvus/pkg/v3/util/interceptor"
	"github.com/milvus-io/milvus/pkg/v3/util/merr"
	"github.com/milvus-io/milvus/pkg/v3/util/metricsinfo"
	"github.com/milvus-io/milvus/pkg/v3/util/paramtable"
	"github.com/milvus-io/milvus/pkg/v3/util/typeutil"
)

var (
	errMissingMetadata = status.Errorf(codes.InvalidArgument, "missing metadata")
	errInvalidToken    = status.Errorf(codes.Unauthenticated, "invalid token")
	// registerHTTPHandlerOnce avoid register http handler multiple times
	registerHTTPHandlerOnce sync.Once
	// only for test
	enableCustomInterceptor = true
	// only for test, register internal interface to external service
	enableRegisterProxyServer = false
)

const apiPathPrefix = "/api/v1"

// Server is the Proxy Server
type Server struct {
	grpc_health_v1.UnimplementedHealthServer
	milvuspb.UnimplementedMilvusServiceServer

	ctx                context.Context
	wg                 sync.WaitGroup
	grpcHTTPWg         sync.WaitGroup
	proxy              types.ProxyComponent
	httpListener       net.Listener
	grpcListener       net.Listener
	tcpServer          cmux.CMux
	httpServer         *http.Server
	grpcInternalServer *grpc.Server
	grpcExternalServer *grpc.Server
	listenerManager    *listenerManager

	serverID atomic.Int64

	etcdCli        *clientv3.Client
	mixCoordClient types.MixCoordClient
}

// NewServer create a Proxy server.
func NewServer(ctx context.Context, factory dependency.Factory) (*Server, error) {
	server := &Server{
		ctx: ctx,
	}

	var err error
	server.proxy, err = proxy.NewProxy(server.ctx, factory)
	if err != nil {
		return nil, err
	}
	return server, err
}

func authenticate(c *gin.Context) {
	username, password, ok := httpserver.ParseUsernamePassword(c)
	if ok {
		if proxy.PasswordVerify(c, username, password) {
			mlog.Debug(context.TODO(), "auth successful", mlog.String("username", username))
			c.Set(httpserver.ContextUsername, username)
			c.Set(httpserver.ContextToken, fmt.Sprintf("%s%s%s", username, util.CredentialSeparator, password))
			return
		}
	}
	rawToken := httpserver.GetAuthorization(c)
	if rawToken != "" && !strings.Contains(rawToken, util.CredentialSeparator) {
		user, err := proxy.VerifyAPIKey(rawToken)
		if err == nil {
			c.Set(httpserver.ContextUsername, user)
			c.Set(httpserver.ContextToken, rawToken)
			return
		}
		mlog.Warn(context.TODO(), "fail to verify apikey", mlog.Err(err))
	}

	hookutil.GetExtension().ReportAction(context.Background(), nil, &milvuspb.BoolResponse{
		Status: merr.Status(merr.ErrNeedAuthenticate),
	}, nil, c.FullPath(), hookutil.ActionAuthorize)
	c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{mhttp.HTTPReturnCode: merr.Code(merr.ErrNeedAuthenticate), mhttp.HTTPReturnMessage: merr.ErrNeedAuthenticate.Error()})
}

// registerHTTPServer register the http server, panic when failed
func (s *Server) registerHTTPServer() {
	// (Embedded Milvus Only) Discard gin logs if logging is disabled.
	// We might need to put these logs in some files in the further.
	// But we don't care about these logs now, at least not in embedded Milvus.
	if !proxy.Params.ProxyCfg.GinLogging.GetAsBool() {
		gin.DefaultWriter = io.Discard
		gin.DefaultErrorWriter = io.Discard
	}
	if !proxy.Params.HTTPCfg.DebugMode.GetAsBool() {
		gin.SetMode(gin.ReleaseMode)
	}
	metricsGinHandler := gin.Default()
	apiv1 := metricsGinHandler.Group(apiPathPrefix)
	apiv1.Use(httpserver.RequestHandlerFunc)
	// Add authentication middleware if authorization is enabled
	// This ensures the metrics port follows the same security policy as the main HTTP server
	if proxy.Params.CommonCfg.AuthorizationEnabled.GetAsBool() {
		apiv1.Use(authenticate)
	}
	handlers := httpserver.NewHandlers(s.proxy)
	handlers.RegisterRoutesTo(apiv1)
	if p, ok := s.proxy.(*proxy.Proxy); ok {
		p.RegisterRestRouter(apiv1)
	}
	mhttp.Register(&mhttp.Handler{
		Path:        mhttp.RootPath,
		HandlerFunc: nil,
		Handler:     metricsGinHandler.Handler(),
	})
}

func (s *Server) httpHandler(ginHandler http.Handler) http.Handler {
	if s.listenerManager == nil || !s.listenerManager.portShareMode {
		return ginHandler
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.ProtoMajor == 2 && strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc") {
			s.grpcHTTPWg.Add(1)
			defer s.grpcHTTPWg.Done()
			s.grpcExternalServer.ServeHTTP(w, r)
			return
		}
		ginHandler.ServeHTTP(w, r)
	})
}

func (s *Server) serveHTTP(listener net.Listener) error {
	if err := s.httpServer.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, cmux.ErrServerClosed) {
		return err
	}
	return nil
}

func (s *Server) startHTTPServer(errChan chan error) {
	defer s.wg.Done()
	ginHandler := gin.New()
	ginHandler.Use(httpserver.MetricsHandlerFunc)
	ginHandler.Use(httpserver.TraceIDHandlerFunc)
	ginHandler.Use(accesslog.AccessLogMiddleware)
	ginHandler.Use(httpserver.LoggerHandlerFunc(), gin.Recovery())
	ginHandler.Use(httpserver.RequestHandlerFunc)
	ginHandler.Use(func(c *gin.Context) {
		c.Set(httpserver.ContextUsername, "")
	})
	if proxy.Params.CommonCfg.AuthorizationEnabled.GetAsBool() {
		ginHandler.Use(authenticate)
	}
	app := ginHandler.Group("/v1")
	httpserver.NewHandlersV1(s.proxy).RegisterRoutesToV1(app)
	appV2 := ginHandler.Group("/v2/vectordb")
	httpserver.NewHandlersV2(s.proxy).RegisterRoutesToV2(appV2)
	http2Server := &http2.Server{}
	Params := &proxy.Params.HTTPCfg
	s.httpServer = &http.Server{
		Handler:           h2c.NewHandler(s.httpHandler(ginHandler), http2Server),
		ReadHeaderTimeout: Params.ReadHeaderTimeout.GetAsDurationByParse(),
		ReadTimeout:       Params.ReadTimeout.GetAsDurationByParse(),
		WriteTimeout:      Params.WriteTimeout.GetAsDurationByParse(),
		IdleTimeout:       Params.IdleTimeout.GetAsDurationByParse(),
		MaxHeaderBytes:    Params.MaxHeaderBytes.GetAsInt(),
	}
	if err := http2.ConfigureServer(s.httpServer, http2Server); err != nil {
		errChan <- err
		return
	}
	errChan <- nil
	if s.listenerManager.portShareMode {
		serveErrChan := make(chan error, 2)
		go func() { serveErrChan <- s.serveHTTP(s.listenerManager.HTTP2Listener()) }()
		go func() { serveErrChan <- s.serveHTTP(s.listenerManager.HTTPListener()) }()
		for i := 0; i < 2; i++ {
			if err := <-serveErrChan; err != nil {
				mlog.Error(s.ctx, "start Proxy http server to listen failed", mlog.Err(err))
				errChan <- err
				return
			}
		}
	} else if err := s.serveHTTP(s.listenerManager.HTTPListener()); err != nil {
		mlog.Error(s.ctx, "start Proxy http server to listen failed", mlog.Err(err))
		errChan <- err
		return
	}
	mlog.Info(s.ctx, "Proxy http server exited")
}

func (s *Server) startInternalRPCServer(errChan chan error) {
	s.wg.Add(1)
	go s.startInternalGrpc(errChan)
}

func (s *Server) startExternalRPCServer(errChan chan error) {
	s.wg.Add(1)
	go s.startExternalGrpc(errChan)
}

func (s *Server) startExternalGrpc(errChan chan error) {
	defer s.wg.Done()
	Params := &paramtable.Get().ProxyGrpcServerCfg
	kaep := keepalive.EnforcementPolicy{
		MinTime:             5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection
		PermitWithoutStream: true,            // Allow pings even when there are no active streams
	}

	kasp := keepalive.ServerParameters{
		Time:    60 * time.Second, // Ping the client if it is idle for 60 seconds to ensure the connection is still active
		Timeout: 10 * time.Second, // Wait 10 second for the ping ack before assuming the connection is dead
	}

	limiter, err := s.proxy.GetRateLimiter()
	if err != nil {
		mlog.Error(context.TODO(), "Get proxy rate limiter failed", mlog.Err(err))
		errChan <- err
		return
	}
	mlog.Debug(context.TODO(), "Get proxy rate limiter done")

	var unaryServerOption grpc.ServerOption
	if enableCustomInterceptor {
		unaryServerOption = grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
			streaming.ForwardLegacyProxyUnaryServerInterceptor(),
			proxy.DatabaseInterceptor(),
			UnaryRequestStatsInterceptor,
			accesslog.UnaryAccessLogInterceptor,
			proxy.GrpcAuthInterceptor(proxy.AuthenticationInterceptor),
			proxy.UnaryServerInterceptor(proxy.PrivilegeInterceptor),
			proxy.UnaryServerHookInterceptor(),
			mlog.UnaryServerInterceptor(typeutil.ProxyRole),
			proxy.RateLimitInterceptor(limiter),
			accesslog.UnaryUpdateAccessInfoInterceptor,
			proxy.TraceLogInterceptor,
			connection.KeepActiveInterceptor,
		))
	} else {
		unaryServerOption = grpc.EmptyServerOption{}
	}

	grpcOpts := []grpc.ServerOption{
		grpc.KeepaliveEnforcementPolicy(kaep),
		grpc.KeepaliveParams(kasp),
		grpc.MaxRecvMsgSize(Params.ServerMaxRecvSize.GetAsInt()),
		grpc.MaxSendMsgSize(Params.ServerMaxSendSize.GetAsInt()),
		unaryServerOption,
		grpc.StatsHandler(tracer.GetDynamicOtelGrpcServerStatsHandler()),
		grpc.StatsHandler(metrics.NewGRPCSizeStatsHandler().
			// both inbound and outbound
			WithTargetMethods(
				milvuspb.MilvusService_Search_FullMethodName,
				milvuspb.MilvusService_HybridSearch_FullMethodName,
				milvuspb.MilvusService_Query_FullMethodName,
			).
			// inbound only
			WithInboundRecord(milvuspb.MilvusService_Insert_FullMethodName,
				milvuspb.MilvusService_Delete_FullMethodName,
				milvuspb.MilvusService_Upsert_FullMethodName)),
	}

	if Params.TLSMode.GetAsInt() == 1 {
		creds, err := credentials.NewServerTLSFromFile(Params.ServerPemPath.GetValue(), Params.ServerKeyPath.GetValue())
		if err != nil {
			mlog.Warn(context.TODO(), "proxy can't create creds", mlog.Err(err))
			errChan <- err
			return
		}
		grpcOpts = append(grpcOpts, grpc.Creds(creds))
	} else if Params.TLSMode.GetAsInt() == 2 {
		cert, err := tls.LoadX509KeyPair(Params.ServerPemPath.GetValue(), Params.ServerKeyPath.GetValue())
		if err != nil {
			mlog.Warn(context.TODO(), "proxy cant load x509 key pair", mlog.Err(err))
			errChan <- err
			return
		}

		certPool := x509.NewCertPool()
		rootBuf, err := storage.ReadFile(Params.CaPemPath.GetValue())
		if err != nil {
			mlog.Warn(context.TODO(), "failed read ca pem", mlog.Err(err))
			errChan <- err
			return
		}
		if !certPool.AppendCertsFromPEM(rootBuf) {
			mlog.Warn(context.TODO(), "fail to append ca to cert")
			errChan <- merr.WrapErrParameterInvalidMsg("fail to append ca to cert")
			return
		}

		tlsConf := &tls.Config{
			ClientAuth:   tls.RequireAndVerifyClientCert,
			Certificates: []tls.Certificate{cert},
			ClientCAs:    certPool,
			MinVersion:   tls.VersionTLS13,
		}
		grpcOpts = append(grpcOpts, grpc.Creds(credentials.NewTLS(tlsConf)))
	}
	s.grpcExternalServer = grpc.NewServer(grpcOpts...)

	if enableRegisterProxyServer {
		proxypb.RegisterProxyServer(s.grpcExternalServer, s)
	}

	milvuspb.RegisterMilvusServiceServer(s.grpcExternalServer, s)
	milvuspb.RegisterClientTelemetryServiceServer(s.grpcExternalServer, s)
	grpc_health_v1.RegisterHealthServer(s.grpcExternalServer, s)
	errChan <- nil

	mlog.Debug(context.TODO(), "create Proxy grpc server",
		mlog.Any("enforcement policy", kaep),
		mlog.Any("server parameters", kasp))

	if s.listenerManager.portShareMode {
		mlog.Info(context.TODO(), "Proxy external grpc server is served by shared http2 server")
		return
	}
	if err := s.grpcExternalServer.Serve(s.listenerManager.ExternalGrpcListener()); err != nil && err != cmux.ErrServerClosed {
		mlog.Error(context.TODO(), "failed to serve on Proxy's listener", mlog.Err(err))
		errChan <- err
		return
	}
	mlog.Info(context.TODO(), "Proxy external grpc server exited")
}

func (s *Server) startInternalGrpc(errChan chan error) {
	defer s.wg.Done()
	Params := &paramtable.Get().ProxyGrpcServerCfg
	kaep := keepalive.EnforcementPolicy{
		MinTime:             5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection
		PermitWithoutStream: true,            // Allow pings even when there are no active streams
	}

	kasp := keepalive.ServerParameters{
		Time:    60 * time.Second, // Ping the client if it is idle for 60 seconds to ensure the connection is still active
		Timeout: 10 * time.Second, // Wait 10 second for the ping ack before assuming the connection is dead
	}

	opts := tracer.GetInterceptorOpts()
	grpcOpts := []grpc.ServerOption{
		grpc.KeepaliveEnforcementPolicy(kaep),
		grpc.KeepaliveParams(kasp),
		grpc.MaxRecvMsgSize(Params.ServerMaxRecvSize.GetAsInt()),
		grpc.MaxSendMsgSize(Params.ServerMaxSendSize.GetAsInt()),
		grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
			otelgrpc.UnaryServerInterceptor(opts...),
			mlog.UnaryServerInterceptor(typeutil.ProxyRole),
			interceptor.ClusterValidationUnaryServerInterceptor(),
			interceptor.ServerIDValidationUnaryServerInterceptor(func() int64 {
				if s.serverID.Load() == 0 {
					s.serverID.Store(paramtable.GetNodeID())
				}
				return s.serverID.Load()
			}),
		)),
		grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
			mlog.StreamServerInterceptor(typeutil.ProxyRole),
			interceptor.ClusterValidationStreamServerInterceptor(),
			interceptor.ServerIDValidationStreamServerInterceptor(func() int64 {
				if s.serverID.Load() == 0 {
					s.serverID.Store(paramtable.GetNodeID())
				}
				return s.serverID.Load()
			}),
		)),
		grpc.StatsHandler(tracer.GetDynamicOtelGrpcServerStatsHandler()),
	}

	grpcOpts = append(grpcOpts, utils.EnableInternalTLS("Proxy"))
	s.grpcInternalServer = grpc.NewServer(grpcOpts...)
	proxypb.RegisterProxyServer(s.grpcInternalServer, s)
	grpc_health_v1.RegisterHealthServer(s.grpcInternalServer, s)
	errChan <- nil

	mlog.Info(context.TODO(), "create Proxy internal grpc server",
		mlog.Any("enforcement policy", kaep),
		mlog.Any("server parameters", kasp))

	if err := s.grpcInternalServer.Serve(s.listenerManager.InternalGrpcListener()); err != nil {
		mlog.Error(context.TODO(), "failed to internal serve on Proxy's listener", mlog.Err(err))
		errChan <- err
		return
	}
	mlog.Info(context.TODO(), "Proxy internal grpc server exited")
}

func (s *Server) Prepare() error {
	listenerManager, err := newListenerManager(s.ctx)
	if err != nil {
		return err
	}
	s.listenerManager = listenerManager
	return nil
}

// Start start the Proxy Server
func (s *Server) Run() error {
	mlog.Info(context.TODO(), "init Proxy server")
	if err := s.init(); err != nil {
		mlog.Warn(context.TODO(), "init Proxy server failed", mlog.Err(err))
		return err
	}
	mlog.Info(context.TODO(), "init Proxy server done")

	mlog.Info(context.TODO(), "start Proxy server")
	if err := s.start(); err != nil {
		mlog.Warn(context.TODO(), "start Proxy server failed", mlog.Err(err))
		return err
	}
	mlog.Info(context.TODO(), "start Proxy server done")
	return nil
}

func (s *Server) init() error {
	etcdConfig := &paramtable.Get().EtcdCfg
	Params := &paramtable.Get().ProxyGrpcServerCfg
	mlog.Info(context.TODO(), "Proxy init service's parameter table done")
	HTTPParams := &paramtable.Get().HTTPCfg
	mlog.Info(context.TODO(), "Proxy init http server's parameter table done")

	accesslog.InitAccessLogger(paramtable.Get())
	serviceName := fmt.Sprintf("Proxy ip: %s, port: %d", Params.IP, Params.Port.GetAsInt())
	mlog.Info(context.TODO(), "init Proxy's tracer done", mlog.String("service name", serviceName))

	etcdCli, err := etcd.CreateEtcdClient(
		etcdConfig.UseEmbedEtcd.GetAsBool(),
		etcdConfig.EtcdEnableAuth.GetAsBool(),
		etcdConfig.EtcdAuthUserName.GetValue(),
		etcdConfig.EtcdAuthPassword.GetValue(),
		etcdConfig.EtcdUseSSL.GetAsBool(),
		etcdConfig.Endpoints.GetAsStrings(),
		etcdConfig.EtcdTLSCert.GetValue(),
		etcdConfig.EtcdTLSKey.GetValue(),
		etcdConfig.EtcdTLSCACert.GetValue(),
		etcdConfig.EtcdTLSMinVersion.GetValue(),
		etcdConfig.ClientOptions()...)
	if err != nil {
		mlog.Debug(context.TODO(), "Proxy connect to etcd failed", mlog.Err(err))
		return err
	}
	s.etcdCli = etcdCli
	s.proxy.SetAddress(s.listenerManager.internalGrpcListener.Address())

	errChan := make(chan error, 1)
	{
		s.startInternalRPCServer(errChan)
		if err := <-errChan; err != nil {
			mlog.Error(context.TODO(), "failed to create internal rpc server", mlog.Err(err))
			return err
		}
	}
	{
		s.startExternalRPCServer(errChan)
		if err := <-errChan; err != nil {
			mlog.Error(context.TODO(), "failed to create external rpc server", mlog.Err(err))
			return err
		}
	}

	if s.mixCoordClient == nil {
		var err error
		mlog.Debug(context.TODO(), "create MixCoordClient client for Proxy")
		s.mixCoordClient, err = mix.NewClient(s.ctx)
		if err != nil {
			mlog.Warn(context.TODO(), "failed to create MixCoordClient client for Proxy", mlog.Err(err))
			return err
		}
		mlog.Debug(context.TODO(), "create MixCoordClient client for Proxy done")
	}

	mlog.Debug(context.TODO(), "Proxy wait for MixCoordClient to be healthy")
	if err := componentutil.WaitForComponentHealthy(s.ctx, s.mixCoordClient, "MixCoord", 1000000, time.Millisecond*200); err != nil {
		mlog.Warn(context.TODO(), "Proxy failed to wait for MixCoord to be healthy", mlog.Err(err))
		return err
	}
	mlog.Debug(context.TODO(), "Proxy wait for MixCoord to be healthy done")

	mlog.Debug(context.TODO(), "set MixCoord client for Proxy")
	s.proxy.SetMixCoordClient(s.mixCoordClient)
	mlog.Debug(context.TODO(), "set MixCoord client for Proxy done")

	if HTTPParams.Enabled.GetAsBool() {
		registerHTTPHandlerOnce.Do(func() {
			mlog.Info(context.TODO(), "register Proxy http server")
			s.registerHTTPServer()
		})
	}

	mlog.Debug(context.TODO(), fmt.Sprintf("update Proxy's state to %s", commonpb.StateCode_Initializing.String()))
	s.proxy.UpdateStateCode(commonpb.StateCode_Initializing)

	mlog.Debug(context.TODO(), "init Proxy")
	if err := s.proxy.Init(); err != nil {
		mlog.Warn(context.TODO(), "failed to init Proxy", mlog.Err(err))
		return err
	}
	mlog.Debug(context.TODO(), "init Proxy done")
	// nolint
	// Intentionally print to stdout, which is usually a sign that Milvus is ready to serve.
	fmt.Println("---Milvus Proxy successfully initialized and ready to serve!---")

	return nil
}

func (s *Server) start() error {
	if err := s.proxy.Start(); err != nil {
		mlog.Warn(context.TODO(), "failed to start Proxy server", mlog.Err(err))
		return err
	}

	if err := s.proxy.Register(); err != nil {
		mlog.Warn(context.TODO(), "failed to register Proxy", mlog.Err(err))
		return err
	}

	if s.listenerManager.HTTPListener() != nil {
		mlog.Info(context.TODO(), "start Proxy http server")
		errChan := make(chan error, 1)
		s.wg.Add(1)
		go s.startHTTPServer(errChan)
		if err := <-errChan; err != nil {
			mlog.Error(context.TODO(), "failed to create http rpc server", mlog.Err(err))
			return err
		}
	}

	return nil
}

// Stop stop the Proxy Server
func (s *Server) Stop() (err error) {
	logger := mlog.With()
	if s.listenerManager != nil {
		logger = mlog.With(
			mlog.String("internal address", s.listenerManager.internalGrpcListener.Address()),
			mlog.String("external address", s.listenerManager.externalGrpcListener.Address()))
	}
	logger.Info(s.ctx, "Proxy stopping")
	defer func() {
		logger.Info(s.ctx, "Proxy stopped", mlog.Err(err))
	}()

	if s.etcdCli != nil {
		defer s.etcdCli.Close()
	}

	gracefulWg := sync.WaitGroup{}

	gracefulWg.Add(1)
	go func() {
		defer gracefulWg.Done()

		portShareMode := s.listenerManager != nil && s.listenerManager.portShareMode
		if portShareMode && s.httpServer != nil {
			logger.Info(s.ctx, "Proxy shutdown http server...")
			ctx, cancel := context.WithTimeout(context.Background(), paramtable.Get().ProxyGrpcServerCfg.GracefulStopTimeout.GetAsDuration(time.Second))
			if err := s.httpServer.Shutdown(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) && !errors.Is(err, cmux.ErrServerClosed) {
				logger.Warn(s.ctx, "Proxy failed to shutdown http server", mlog.Err(err))
			}
			cancel()
		}

		if s.grpcExternalServer != nil {
			logger.Info(s.ctx, "Proxy stop external grpc server")
			if portShareMode {
				s.grpcHTTPWg.Wait()
				s.grpcExternalServer.Stop()
			} else {
				utils.GracefulStopGRPCServer(s.grpcExternalServer)
			}
		}

		if !portShareMode && s.httpServer != nil {
			logger.Info(s.ctx, "Proxy stop http server...")
			s.httpServer.Close()
		}

		if s.grpcInternalServer != nil {
			logger.Info(s.ctx, "Proxy stop internal grpc server")
			utils.GracefulStopGRPCServer(s.grpcInternalServer)
		}

		if s.listenerManager != nil {
			s.listenerManager.Close()
		}
	}()
	gracefulWg.Wait()

	s.wg.Wait()

	logger.Info(s.ctx, "internal server[proxy] start to stop")
	err = s.proxy.Stop()
	if err != nil {
		logger.Error(s.ctx, "failed to close proxy", mlog.Err(err))
		return err
	}

	return nil
}

// GetComponentStates get the component states
func (s *Server) GetComponentStates(ctx context.Context, request *milvuspb.GetComponentStatesRequest) (*milvuspb.ComponentStates, error) {
	return s.proxy.GetComponentStates(ctx, request)
}

// GetStatisticsChannel get the statistics channel
func (s *Server) GetStatisticsChannel(ctx context.Context, request *internalpb.GetStatisticsChannelRequest) (*milvuspb.StringResponse, error) {
	return s.proxy.GetStatisticsChannel(ctx, request)
}

// InvalidateCollectionMetaCache notifies Proxy to clear all the meta cache of specific collection.
func (s *Server) InvalidateCollectionMetaCache(ctx context.Context, request *proxypb.InvalidateCollMetaCacheRequest) (*commonpb.Status, error) {
	return s.proxy.InvalidateCollectionMetaCache(ctx, request)
}

// CreateCollection notifies Proxy to create a collection
func (s *Server) CreateCollection(ctx context.Context, request *milvuspb.CreateCollectionRequest) (*commonpb.Status, error) {
	return s.proxy.CreateCollection(ctx, request)
}

// DropCollection notifies Proxy to drop a collection
func (s *Server) DropCollection(ctx context.Context, request *milvuspb.DropCollectionRequest) (*commonpb.Status, error) {
	return s.proxy.DropCollection(ctx, request)
}

// TruncateCollection notifies Proxy to truncate a collection
func (s *Server) TruncateCollection(ctx context.Context, request *milvuspb.TruncateCollectionRequest) (*milvuspb.TruncateCollectionResponse, error) {
	return s.proxy.TruncateCollection(ctx, request)
}

// HasCollection notifies Proxy to check a collection's existence at specified timestamp
func (s *Server) HasCollection(ctx context.Context, request *milvuspb.HasCollectionRequest) (*milvuspb.BoolResponse, error) {
	return s.proxy.HasCollection(ctx, request)
}

// LoadCollection notifies Proxy to load a collection's data
func (s *Server) LoadCollection(ctx context.Context, request *milvuspb.LoadCollectionRequest) (*commonpb.Status, error) {
	return s.proxy.LoadCollection(ctx, request)
}

// ReleaseCollection notifies Proxy to release a collection's data
func (s *Server) ReleaseCollection(ctx context.Context, request *milvuspb.ReleaseCollectionRequest) (*commonpb.Status, error) {
	return s.proxy.ReleaseCollection(ctx, request)
}

// DescribeCollection notifies Proxy to describe a collection
func (s *Server) DescribeCollection(ctx context.Context, request *milvuspb.DescribeCollectionRequest) (*milvuspb.DescribeCollectionResponse, error) {
	return s.proxy.DescribeCollection(ctx, request)
}

// BatchDescribeCollection notifies Proxy to describe a collection
func (s *Server) BatchDescribeCollection(ctx context.Context, request *milvuspb.BatchDescribeCollectionRequest) (*milvuspb.BatchDescribeCollectionResponse, error) {
	return s.proxy.BatchDescribeCollection(ctx, request)
}

// AddCollectionField add a field to collection
func (s *Server) AddCollectionField(ctx context.Context, request *milvuspb.AddCollectionFieldRequest) (*commonpb.Status, error) {
	return s.proxy.AddCollectionField(ctx, request)
}

// AddCollectionStructField add a struct field to collection
func (s *Server) AddCollectionStructField(ctx context.Context, request *milvuspb.AddCollectionStructFieldRequest) (*commonpb.Status, error) {
	return s.proxy.AddCollectionStructField(ctx, request)
}

// AlterCollectionSchema alters the collection schema (add/drop fields)
func (s *Server) AlterCollectionSchema(ctx context.Context, request *milvuspb.AlterCollectionSchemaRequest) (*milvuspb.AlterCollectionSchemaResponse, error) {
	return s.proxy.AlterCollectionSchema(ctx, request)
}

// GetCollectionStatistics notifies Proxy to get a collection's Statistics
func (s *Server) GetCollectionStatistics(ctx context.Context, request *milvuspb.GetCollectionStatisticsRequest) (*milvuspb.GetCollectionStatisticsResponse, error) {
	return s.proxy.GetCollectionStatistics(ctx, request)
}

func (s *Server) ShowCollections(ctx context.Context, request *milvuspb.ShowCollectionsRequest) (*milvuspb.ShowCollectionsResponse, error) {
	return s.proxy.ShowCollections(ctx, request)
}

func (s *Server) AlterCollection(ctx context.Context, request *milvuspb.AlterCollectionRequest) (*commonpb.Status, error) {
	return s.proxy.AlterCollection(ctx, request)
}

func (s *Server) AlterCollectionField(ctx context.Context, request *milvuspb.AlterCollectionFieldRequest) (*commonpb.Status, error) {
	return s.proxy.AlterCollectionField(ctx, request)
}

func (s *Server) AddCollectionFunction(ctx context.Context, request *milvuspb.AddCollectionFunctionRequest) (*commonpb.Status, error) {
	return s.proxy.AddCollectionFunction(ctx, request)
}

func (s *Server) AlterCollectionFunction(ctx context.Context, request *milvuspb.AlterCollectionFunctionRequest) (*commonpb.Status, error) {
	return s.proxy.AlterCollectionFunction(ctx, request)
}

func (s *Server) DropCollectionFunction(ctx context.Context, request *milvuspb.DropCollectionFunctionRequest) (*commonpb.Status, error) {
	return s.proxy.DropCollectionFunction(ctx, request)
}

// CreatePartition notifies Proxy to create a partition
func (s *Server) CreatePartition(ctx context.Context, request *milvuspb.CreatePartitionRequest) (*commonpb.Status, error) {
	return s.proxy.CreatePartition(ctx, request)
}

// DropPartition notifies Proxy to drop a partition
func (s *Server) DropPartition(ctx context.Context, request *milvuspb.DropPartitionRequest) (*commonpb.Status, error) {
	return s.proxy.DropPartition(ctx, request)
}

// HasPartition notifies Proxy to check a partition's existence
func (s *Server) HasPartition(ctx context.Context, request *milvuspb.HasPartitionRequest) (*milvuspb.BoolResponse, error) {
	return s.proxy.HasPartition(ctx, request)
}

// LoadPartitions notifies Proxy to load the partitions data
func (s *Server) LoadPartitions(ctx context.Context, request *milvuspb.LoadPartitionsRequest) (*commonpb.Status, error) {
	return s.proxy.LoadPartitions(ctx, request)
}

// ReleasePartitions notifies Proxy to release the partitions data
func (s *Server) ReleasePartitions(ctx context.Context, request *milvuspb.ReleasePartitionsRequest) (*commonpb.Status, error) {
	return s.proxy.ReleasePartitions(ctx, request)
}

// GetPartitionStatistics notifies Proxy to get the partitions Statistics info.
func (s *Server) GetPartitionStatistics(ctx context.Context, request *milvuspb.GetPartitionStatisticsRequest) (*milvuspb.GetPartitionStatisticsResponse, error) {
	return s.proxy.GetPartitionStatistics(ctx, request)
}

// ShowPartitions notifies Proxy to show the partitions
func (s *Server) ShowPartitions(ctx context.Context, request *milvuspb.ShowPartitionsRequest) (*milvuspb.ShowPartitionsResponse, error) {
	return s.proxy.ShowPartitions(ctx, request)
}

func (s *Server) GetLoadingProgress(ctx context.Context, request *milvuspb.GetLoadingProgressRequest) (*milvuspb.GetLoadingProgressResponse, error) {
	return s.proxy.GetLoadingProgress(ctx, request)
}

func (s *Server) GetLoadState(ctx context.Context, request *milvuspb.GetLoadStateRequest) (*milvuspb.GetLoadStateResponse, error) {
	return s.proxy.GetLoadState(ctx, request)
}

// CreateIndex notifies Proxy to create index
func (s *Server) CreateIndex(ctx context.Context, request *milvuspb.CreateIndexRequest) (*commonpb.Status, error) {
	return s.proxy.CreateIndex(ctx, request)
}

// AlterIndex notifies Proxy to alter index
func (s *Server) AlterIndex(ctx context.Context, request *milvuspb.AlterIndexRequest) (*commonpb.Status, error) {
	return s.proxy.AlterIndex(ctx, request)
}

// DropIndex notifies Proxy to drop index
func (s *Server) DropIndex(ctx context.Context, request *milvuspb.DropIndexRequest) (*commonpb.Status, error) {
	return s.proxy.DropIndex(ctx, request)
}

// DescribeIndex notifies Proxy to get index describe
func (s *Server) DescribeIndex(ctx context.Context, request *milvuspb.DescribeIndexRequest) (*milvuspb.DescribeIndexResponse, error) {
	return s.proxy.DescribeIndex(ctx, request)
}

// GetIndexStatistics get the information of index.
func (s *Server) GetIndexStatistics(ctx context.Context, request *milvuspb.GetIndexStatisticsRequest) (*milvuspb.GetIndexStatisticsResponse, error) {
	return s.proxy.GetIndexStatistics(ctx, request)
}

// GetIndexBuildProgress gets index build progress with field_name and index_name.
// IndexRows is the num of indexed rows. And TotalRows is the total number of segment rows.
// Deprecated: use DescribeIndex instead
func (s *Server) GetIndexBuildProgress(ctx context.Context, request *milvuspb.GetIndexBuildProgressRequest) (*milvuspb.GetIndexBuildProgressResponse, error) {
	return s.proxy.GetIndexBuildProgress(ctx, request)
}

// GetIndexState gets the index states from proxy.
// Deprecated: use DescribeIndex instead
func (s *Server) GetIndexState(ctx context.Context, request *milvuspb.GetIndexStateRequest) (*milvuspb.GetIndexStateResponse, error) {
	return s.proxy.GetIndexState(ctx, request)
}

func (s *Server) Insert(ctx context.Context, request *milvuspb.InsertRequest) (*milvuspb.MutationResult, error) {
	return s.proxy.Insert(ctx, request)
}

func (s *Server) Delete(ctx context.Context, request *milvuspb.DeleteRequest) (*milvuspb.MutationResult, error) {
	return s.proxy.Delete(ctx, request)
}

func (s *Server) Upsert(ctx context.Context, request *milvuspb.UpsertRequest) (*milvuspb.MutationResult, error) {
	return s.proxy.Upsert(ctx, request)
}

func (s *Server) Search(ctx context.Context, request *milvuspb.SearchRequest) (*milvuspb.SearchResults, error) {
	return s.proxy.Search(ctx, request)
}

func (s *Server) HybridSearch(ctx context.Context, request *milvuspb.HybridSearchRequest) (*milvuspb.SearchResults, error) {
	return s.proxy.HybridSearch(ctx, request)
}

func (s *Server) Flush(ctx context.Context, request *milvuspb.FlushRequest) (*milvuspb.FlushResponse, error) {
	return s.proxy.Flush(ctx, request)
}

func (s *Server) Query(ctx context.Context, request *milvuspb.QueryRequest) (*milvuspb.QueryResults, error) {
	return s.proxy.Query(ctx, request)
}

func (s *Server) CalcDistance(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
	return s.proxy.CalcDistance(ctx, request)
}

func (s *Server) FlushAll(ctx context.Context, request *milvuspb.FlushAllRequest) (*milvuspb.FlushAllResponse, error) {
	return s.proxy.FlushAll(ctx, request)
}

func (s *Server) GetDdChannel(ctx context.Context, request *internalpb.GetDdChannelRequest) (*milvuspb.StringResponse, error) {
	return s.proxy.GetDdChannel(ctx, request)
}

// GetPersistentSegmentInfo notifies Proxy to get persistent segment info.
func (s *Server) GetPersistentSegmentInfo(ctx context.Context, request *milvuspb.GetPersistentSegmentInfoRequest) (*milvuspb.GetPersistentSegmentInfoResponse, error) {
	return s.proxy.GetPersistentSegmentInfo(ctx, request)
}

// GetQuerySegmentInfo notifies Proxy to get query segment info.
func (s *Server) GetQuerySegmentInfo(ctx context.Context, request *milvuspb.GetQuerySegmentInfoRequest) (*milvuspb.GetQuerySegmentInfoResponse, error) {
	return s.proxy.GetQuerySegmentInfo(ctx, request)
}

func (s *Server) Dummy(ctx context.Context, request *milvuspb.DummyRequest) (*milvuspb.DummyResponse, error) {
	return s.proxy.Dummy(ctx, request)
}

func (s *Server) RegisterLink(ctx context.Context, request *milvuspb.RegisterLinkRequest) (*milvuspb.RegisterLinkResponse, error) {
	return s.proxy.RegisterLink(ctx, request)
}

// GetMetrics gets the metrics info of proxy.
func (s *Server) GetMetrics(ctx context.Context, request *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {
	return s.proxy.GetMetrics(ctx, request)
}

func (s *Server) LoadBalance(ctx context.Context, request *milvuspb.LoadBalanceRequest) (*commonpb.Status, error) {
	return s.proxy.LoadBalance(ctx, request)
}

// CreateAlias notifies Proxy to create alias
func (s *Server) CreateAlias(ctx context.Context, request *milvuspb.CreateAliasRequest) (*commonpb.Status, error) {
	return s.proxy.CreateAlias(ctx, request)
}

// DropAlias notifies Proxy to drop an alias
func (s *Server) DropAlias(ctx context.Context, request *milvuspb.DropAliasRequest) (*commonpb.Status, error) {
	return s.proxy.DropAlias(ctx, request)
}

// AlterAlias alters the alias for the specified collection.
func (s *Server) AlterAlias(ctx context.Context, request *milvuspb.AlterAliasRequest) (*commonpb.Status, error) {
	return s.proxy.AlterAlias(ctx, request)
}

// DescribeAlias show the alias-collection relation for the specified alias.
func (s *Server) DescribeAlias(ctx context.Context, request *milvuspb.DescribeAliasRequest) (*milvuspb.DescribeAliasResponse, error) {
	return s.proxy.DescribeAlias(ctx, request)
}

// ListAliases list all the alias for the specified db, collection.
func (s *Server) ListAliases(ctx context.Context, request *milvuspb.ListAliasesRequest) (*milvuspb.ListAliasesResponse, error) {
	return s.proxy.ListAliases(ctx, request)
}

// GetCompactionState gets the state of a compaction
func (s *Server) GetCompactionState(ctx context.Context, req *milvuspb.GetCompactionStateRequest) (*milvuspb.GetCompactionStateResponse, error) {
	return s.proxy.GetCompactionState(ctx, req)
}

func (s *Server) ManualCompaction(ctx context.Context, req *milvuspb.ManualCompactionRequest) (*milvuspb.ManualCompactionResponse, error) {
	return s.proxy.ManualCompaction(ctx, req)
}

// GetCompactionStateWithPlans gets the state of a compaction by plan
func (s *Server) GetCompactionStateWithPlans(ctx context.Context, req *milvuspb.GetCompactionPlansRequest) (*milvuspb.GetCompactionPlansResponse, error) {
	return s.proxy.GetCompactionStateWithPlans(ctx, req)
}

// GetFlushState gets the flush state of the collection based on the provided flush ts and segment IDs.
func (s *Server) GetFlushState(ctx context.Context, req *milvuspb.GetFlushStateRequest) (*milvuspb.GetFlushStateResponse, error) {
	return s.proxy.GetFlushState(ctx, req)
}

// GetFlushAllState checks if all DML messages before `FlushAllTs` have been flushed.
func (s *Server) GetFlushAllState(ctx context.Context, req *milvuspb.GetFlushAllStateRequest) (*milvuspb.GetFlushAllStateResponse, error) {
	return s.proxy.GetFlushAllState(ctx, req)
}

func (s *Server) Import(ctx context.Context, req *milvuspb.ImportRequest) (*milvuspb.ImportResponse, error) {
	return s.proxy.Import(ctx, req)
}

func (s *Server) GetImportState(ctx context.Context, req *milvuspb.GetImportStateRequest) (*milvuspb.GetImportStateResponse, error) {
	return s.proxy.GetImportState(ctx, req)
}

func (s *Server) ListImportTasks(ctx context.Context, req *milvuspb.ListImportTasksRequest) (*milvuspb.ListImportTasksResponse, error) {
	return s.proxy.ListImportTasks(ctx, req)
}

func (s *Server) GetReplicas(ctx context.Context, req *milvuspb.GetReplicasRequest) (*milvuspb.GetReplicasResponse, error) {
	return s.proxy.GetReplicas(ctx, req)
}

// Check is required by gRPC healthy checking
func (s *Server) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
	ret := &grpc_health_v1.HealthCheckResponse{
		Status: grpc_health_v1.HealthCheckResponse_NOT_SERVING,
	}
	state, err := s.proxy.GetComponentStates(ctx, &milvuspb.GetComponentStatesRequest{})
	if err != nil {
		return ret, err
	}
	if state.GetStatus().GetErrorCode() != commonpb.ErrorCode_Success {
		return ret, nil
	}
	if state.State.StateCode != commonpb.StateCode_Healthy {
		return ret, nil
	}
	ret.Status = grpc_health_v1.HealthCheckResponse_SERVING
	return ret, nil
}

// Watch is required by gRPC healthy checking
func (s *Server) Watch(req *grpc_health_v1.HealthCheckRequest, server grpc_health_v1.Health_WatchServer) error {
	ret := &grpc_health_v1.HealthCheckResponse{
		Status: grpc_health_v1.HealthCheckResponse_NOT_SERVING,
	}
	state, err := s.proxy.GetComponentStates(s.ctx, nil)
	if err != nil {
		return server.Send(ret)
	}
	if state.GetStatus().GetErrorCode() != commonpb.ErrorCode_Success {
		return server.Send(ret)
	}
	if state.State.StateCode != commonpb.StateCode_Healthy {
		return server.Send(ret)
	}
	ret.Status = grpc_health_v1.HealthCheckResponse_SERVING
	return server.Send(ret)
}

func (s *Server) InvalidateCredentialCache(ctx context.Context, request *proxypb.InvalidateCredCacheRequest) (*commonpb.Status, error) {
	return s.proxy.InvalidateCredentialCache(ctx, request)
}

func (s *Server) UpdateCredentialCache(ctx context.Context, request *proxypb.UpdateCredCacheRequest) (*commonpb.Status, error) {
	return s.proxy.UpdateCredentialCache(ctx, request)
}

func (s *Server) CreateCredential(ctx context.Context, req *milvuspb.CreateCredentialRequest) (*commonpb.Status, error) {
	return s.proxy.CreateCredential(ctx, req)
}

func (s *Server) UpdateCredential(ctx context.Context, req *milvuspb.UpdateCredentialRequest) (*commonpb.Status, error) {
	return s.proxy.UpdateCredential(ctx, req)
}

func (s *Server) DeleteCredential(ctx context.Context, req *milvuspb.DeleteCredentialRequest) (*commonpb.Status, error) {
	return s.proxy.DeleteCredential(ctx, req)
}

func (s *Server) ListCredUsers(ctx context.Context, req *milvuspb.ListCredUsersRequest) (*milvuspb.ListCredUsersResponse, error) {
	return s.proxy.ListCredUsers(ctx, req)
}

func (s *Server) CreateRole(ctx context.Context, req *milvuspb.CreateRoleRequest) (*commonpb.Status, error) {
	return s.proxy.CreateRole(ctx, req)
}

func (s *Server) AlterRole(ctx context.Context, req *milvuspb.AlterRoleRequest) (*commonpb.Status, error) {
	return s.proxy.AlterRole(ctx, req)
}

func (s *Server) DropRole(ctx context.Context, req *milvuspb.DropRoleRequest) (*commonpb.Status, error) {
	return s.proxy.DropRole(ctx, req)
}

func (s *Server) OperateUserRole(ctx context.Context, req *milvuspb.OperateUserRoleRequest) (*commonpb.Status, error) {
	return s.proxy.OperateUserRole(ctx, req)
}

func (s *Server) SelectRole(ctx context.Context, req *milvuspb.SelectRoleRequest) (*milvuspb.SelectRoleResponse, error) {
	return s.proxy.SelectRole(ctx, req)
}

func (s *Server) SelectUser(ctx context.Context, req *milvuspb.SelectUserRequest) (*milvuspb.SelectUserResponse, error) {
	return s.proxy.SelectUser(ctx, req)
}

func (s *Server) OperatePrivilege(ctx context.Context, req *milvuspb.OperatePrivilegeRequest) (*commonpb.Status, error) {
	return s.proxy.OperatePrivilege(ctx, req)
}

func (s *Server) OperatePrivilegeV2(ctx context.Context, req *milvuspb.OperatePrivilegeV2Request) (*commonpb.Status, error) {
	return s.proxy.OperatePrivilegeV2(ctx, req)
}

func (s *Server) SelectGrant(ctx context.Context, req *milvuspb.SelectGrantRequest) (*milvuspb.SelectGrantResponse, error) {
	return s.proxy.SelectGrant(ctx, req)
}

func (s *Server) BackupRBAC(ctx context.Context, req *milvuspb.BackupRBACMetaRequest) (*milvuspb.BackupRBACMetaResponse, error) {
	return s.proxy.BackupRBAC(ctx, req)
}

func (s *Server) RestoreRBAC(ctx context.Context, req *milvuspb.RestoreRBACMetaRequest) (*commonpb.Status, error) {
	return s.proxy.RestoreRBAC(ctx, req)
}

func (s *Server) CreatePrivilegeGroup(ctx context.Context, req *milvuspb.CreatePrivilegeGroupRequest) (*commonpb.Status, error) {
	return s.proxy.CreatePrivilegeGroup(ctx, req)
}

func (s *Server) DropPrivilegeGroup(ctx context.Context, req *milvuspb.DropPrivilegeGroupRequest) (*commonpb.Status, error) {
	return s.proxy.DropPrivilegeGroup(ctx, req)
}

func (s *Server) ListPrivilegeGroups(ctx context.Context, req *milvuspb.ListPrivilegeGroupsRequest) (*milvuspb.ListPrivilegeGroupsResponse, error) {
	return s.proxy.ListPrivilegeGroups(ctx, req)
}

func (s *Server) OperatePrivilegeGroup(ctx context.Context, req *milvuspb.OperatePrivilegeGroupRequest) (*commonpb.Status, error) {
	return s.proxy.OperatePrivilegeGroup(ctx, req)
}

func (s *Server) RefreshPolicyInfoCache(ctx context.Context, req *proxypb.RefreshPolicyInfoCacheRequest) (*commonpb.Status, error) {
	return s.proxy.RefreshPolicyInfoCache(ctx, req)
}

// SetRates notifies Proxy to limit rates of requests.
func (s *Server) SetRates(ctx context.Context, request *proxypb.SetRatesRequest) (*commonpb.Status, error) {
	return s.proxy.SetRates(ctx, request)
}

// GetProxyMetrics gets the metrics of proxy.
func (s *Server) GetProxyMetrics(ctx context.Context, request *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {
	return s.proxy.GetProxyMetrics(ctx, request)
}

func (s *Server) GetVersion(ctx context.Context, request *milvuspb.GetVersionRequest) (*milvuspb.GetVersionResponse, error) {
	buildTags := os.Getenv(metricsinfo.GitBuildTagsEnvKey)
	return &milvuspb.GetVersionResponse{
		Status:  merr.Success(),
		Version: buildTags,
	}, nil
}

func (s *Server) CheckHealth(ctx context.Context, request *milvuspb.CheckHealthRequest) (*milvuspb.CheckHealthResponse, error) {
	return s.proxy.CheckHealth(ctx, request)
}

func (s *Server) RenameCollection(ctx context.Context, req *milvuspb.RenameCollectionRequest) (*commonpb.Status, error) {
	return s.proxy.RenameCollection(ctx, req)
}

func (s *Server) CreateResourceGroup(ctx context.Context, req *milvuspb.CreateResourceGroupRequest) (*commonpb.Status, error) {
	return s.proxy.CreateResourceGroup(ctx, req)
}

func (s *Server) UpdateResourceGroups(ctx context.Context, req *milvuspb.UpdateResourceGroupsRequest) (*commonpb.Status, error) {
	return s.proxy.UpdateResourceGroups(ctx, req)
}

func (s *Server) DropResourceGroup(ctx context.Context, req *milvuspb.DropResourceGroupRequest) (*commonpb.Status, error) {
	return s.proxy.DropResourceGroup(ctx, req)
}

func (s *Server) DescribeResourceGroup(ctx context.Context, req *milvuspb.DescribeResourceGroupRequest) (*milvuspb.DescribeResourceGroupResponse, error) {
	return s.proxy.DescribeResourceGroup(ctx, req)
}

func (s *Server) TransferNode(ctx context.Context, req *milvuspb.TransferNodeRequest) (*commonpb.Status, error) {
	return s.proxy.TransferNode(ctx, req)
}

func (s *Server) TransferReplica(ctx context.Context, req *milvuspb.TransferReplicaRequest) (*commonpb.Status, error) {
	return s.proxy.TransferReplica(ctx, req)
}

func (s *Server) ListResourceGroups(ctx context.Context, req *milvuspb.ListResourceGroupsRequest) (*milvuspb.ListResourceGroupsResponse, error) {
	return s.proxy.ListResourceGroups(ctx, req)
}

func (s *Server) ListIndexedSegment(ctx context.Context, req *federpb.ListIndexedSegmentRequest) (*federpb.ListIndexedSegmentResponse, error) {
	return &federpb.ListIndexedSegmentResponse{
		Status: merr.Status(merr.WrapErrServiceUnavailable("ListIndexedSegment unimplemented")),
	}, nil
}

func (s *Server) DescribeSegmentIndexData(ctx context.Context, req *federpb.DescribeSegmentIndexDataRequest) (*federpb.DescribeSegmentIndexDataResponse, error) {
	return &federpb.DescribeSegmentIndexDataResponse{
		Status: merr.Status(merr.WrapErrServiceUnavailable("DescribeSegmentIndexData unimplemented")),
	}, nil
}

func (s *Server) Connect(ctx context.Context, req *milvuspb.ConnectRequest) (*milvuspb.ConnectResponse, error) {
	return s.proxy.Connect(ctx, req)
}

func (s *Server) ListClientInfos(ctx context.Context, req *proxypb.ListClientInfosRequest) (*proxypb.ListClientInfosResponse, error) {
	return s.proxy.ListClientInfos(ctx, req)
}

func (s *Server) CreateDatabase(ctx context.Context, request *milvuspb.CreateDatabaseRequest) (*commonpb.Status, error) {
	return s.proxy.CreateDatabase(ctx, request)
}

func (s *Server) DropDatabase(ctx context.Context, request *milvuspb.DropDatabaseRequest) (*commonpb.Status, error) {
	return s.proxy.DropDatabase(ctx, request)
}

func (s *Server) ListDatabases(ctx context.Context, request *milvuspb.ListDatabasesRequest) (*milvuspb.ListDatabasesResponse, error) {
	return s.proxy.ListDatabases(ctx, request)
}

func (s *Server) AllocTimestamp(ctx context.Context, req *milvuspb.AllocTimestampRequest) (*milvuspb.AllocTimestampResponse, error) {
	return s.proxy.AllocTimestamp(ctx, req)
}

func (s *Server) ReplicateMessage(ctx context.Context, req *milvuspb.ReplicateMessageRequest) (*milvuspb.ReplicateMessageResponse, error) {
	return s.proxy.ReplicateMessage(ctx, req)
}

func (s *Server) ImportV2(ctx context.Context, req *internalpb.ImportRequest) (*internalpb.ImportResponse, error) {
	return s.proxy.ImportV2(ctx, req)
}

func (s *Server) GetImportProgress(ctx context.Context, req *internalpb.GetImportProgressRequest) (*internalpb.GetImportProgressResponse, error) {
	return s.proxy.GetImportProgress(ctx, req)
}

func (s *Server) ListImports(ctx context.Context, req *internalpb.ListImportsRequest) (*internalpb.ListImportsResponse, error) {
	return s.proxy.ListImports(ctx, req)
}

func (s *Server) AlterDatabase(ctx context.Context, req *milvuspb.AlterDatabaseRequest) (*commonpb.Status, error) {
	return s.proxy.AlterDatabase(ctx, req)
}

func (s *Server) InvalidateShardLeaderCache(ctx context.Context, req *proxypb.InvalidateShardLeaderCacheRequest) (*commonpb.Status, error) {
	return s.proxy.InvalidateShardLeaderCache(ctx, req)
}

func (s *Server) DescribeDatabase(ctx context.Context, req *milvuspb.DescribeDatabaseRequest) (*milvuspb.DescribeDatabaseResponse, error) {
	return s.proxy.DescribeDatabase(ctx, req)
}

func (s *Server) RunAnalyzer(ctx context.Context, req *milvuspb.RunAnalyzerRequest) (*milvuspb.RunAnalyzerResponse, error) {
	return s.proxy.RunAnalyzer(ctx, req)
}

func (s *Server) GetSegmentsInfo(ctx context.Context, req *internalpb.GetSegmentsInfoRequest) (*internalpb.GetSegmentsInfoResponse, error) {
	return s.proxy.GetSegmentsInfo(ctx, req)
}

func (s *Server) GetQuotaMetrics(ctx context.Context, req *internalpb.GetQuotaMetricsRequest) (*internalpb.GetQuotaMetricsResponse, error) {
	return s.proxy.GetQuotaMetrics(ctx, req)
}

func (s *Server) ClearReadTaskQueue(ctx context.Context, req *internalpb.ClearReadTaskQueueRequest) (*internalpb.ClearReadTaskQueueResponse, error) {
	return s.proxy.ClearReadTaskQueue(ctx, req)
}

// AddFileResource add file resource
func (s *Server) AddFileResource(ctx context.Context, req *milvuspb.AddFileResourceRequest) (*commonpb.Status, error) {
	return s.proxy.AddFileResource(ctx, req)
}

// RemoveFileResource remove file resource
func (s *Server) RemoveFileResource(ctx context.Context, req *milvuspb.RemoveFileResourceRequest) (*commonpb.Status, error) {
	return s.proxy.RemoveFileResource(ctx, req)
}

// ListFileResources list file resources
func (s *Server) ListFileResources(ctx context.Context, req *milvuspb.ListFileResourcesRequest) (*milvuspb.ListFileResourcesResponse, error) {
	return s.proxy.ListFileResources(ctx, req)
}

// UpdateReplicateConfiguration applies a full replacement of the current replication configuration across Milvus clusters.
func (s *Server) UpdateReplicateConfiguration(ctx context.Context, req *milvuspb.UpdateReplicateConfigurationRequest) (*commonpb.Status, error) {
	return s.proxy.UpdateReplicateConfiguration(ctx, req)
}

// GetReplicateConfiguration retrieves the current cross-cluster replication topology.
func (s *Server) GetReplicateConfiguration(ctx context.Context, req *milvuspb.GetReplicateConfigurationRequest) (*milvuspb.GetReplicateConfigurationResponse, error) {
	return s.proxy.GetReplicateConfiguration(ctx, req)
}

// GetReplicateInfo retrieves replication-related metadata from a target Milvus cluster.
func (s *Server) GetReplicateInfo(ctx context.Context, req *milvuspb.GetReplicateInfoRequest) (*milvuspb.GetReplicateInfoResponse, error) {
	return s.proxy.GetReplicateInfo(ctx, req)
}

// CreateReplicateStream establishes a replication stream on the target Milvus cluster.
func (s *Server) CreateReplicateStream(stream milvuspb.MilvusService_CreateReplicateStreamServer) error {
	return s.proxy.CreateReplicateStream(stream)
}

// DumpMessages streams messages from a WAL range for data salvage.
func (s *Server) DumpMessages(req *milvuspb.DumpMessagesRequest, stream milvuspb.MilvusService_DumpMessagesServer) error {
	return s.proxy.DumpMessages(req, stream)
}

// ComputePhraseMatchSlop computes the minimum slop required for phrase matching.
func (s *Server) ComputePhraseMatchSlop(ctx context.Context, req *milvuspb.ComputePhraseMatchSlopRequest) (*milvuspb.ComputePhraseMatchSlopResponse, error) {
	return s.proxy.ComputePhraseMatchSlop(ctx, req)
}

func (s *Server) CreateSnapshot(ctx context.Context, req *milvuspb.CreateSnapshotRequest) (*commonpb.Status, error) {
	return s.proxy.CreateSnapshot(ctx, req)
}

func (s *Server) DropSnapshot(ctx context.Context, req *milvuspb.DropSnapshotRequest) (*commonpb.Status, error) {
	return s.proxy.DropSnapshot(ctx, req)
}

func (s *Server) DescribeSnapshot(ctx context.Context, req *milvuspb.DescribeSnapshotRequest) (*milvuspb.DescribeSnapshotResponse, error) {
	return s.proxy.DescribeSnapshot(ctx, req)
}

func (s *Server) ListSnapshots(ctx context.Context, req *milvuspb.ListSnapshotsRequest) (*milvuspb.ListSnapshotsResponse, error) {
	return s.proxy.ListSnapshots(ctx, req)
}

func (s *Server) RestoreSnapshot(ctx context.Context, req *milvuspb.RestoreSnapshotRequest) (*milvuspb.RestoreSnapshotResponse, error) {
	return s.proxy.RestoreSnapshot(ctx, req)
}

func (s *Server) RestoreExternalSnapshot(ctx context.Context, req *milvuspb.RestoreExternalSnapshotRequest) (*milvuspb.RestoreExternalSnapshotResponse, error) {
	return s.proxy.RestoreExternalSnapshot(ctx, req)
}

func (s *Server) ExportSnapshot(ctx context.Context, req *milvuspb.ExportSnapshotRequest) (*milvuspb.ExportSnapshotResponse, error) {
	return s.proxy.ExportSnapshot(ctx, req)
}

func (s *Server) GetRestoreSnapshotState(ctx context.Context, req *milvuspb.GetRestoreSnapshotStateRequest) (*milvuspb.GetRestoreSnapshotStateResponse, error) {
	return s.proxy.GetRestoreSnapshotState(ctx, req)
}

func (s *Server) ListRestoreSnapshotJobs(ctx context.Context, req *milvuspb.ListRestoreSnapshotJobsRequest) (*milvuspb.ListRestoreSnapshotJobsResponse, error) {
	return s.proxy.ListRestoreSnapshotJobs(ctx, req)
}

func (s *Server) PinSnapshotData(ctx context.Context, req *milvuspb.PinSnapshotDataRequest) (*milvuspb.PinSnapshotDataResponse, error) {
	return s.proxy.PinSnapshotData(ctx, req)
}

func (s *Server) UnpinSnapshotData(ctx context.Context, req *milvuspb.UnpinSnapshotDataRequest) (*commonpb.Status, error) {
	return s.proxy.UnpinSnapshotData(ctx, req)
}

// ClientHeartbeat handles client telemetry heartbeat requests
func (s *Server) ClientHeartbeat(ctx context.Context, req *milvuspb.ClientHeartbeatRequest) (*milvuspb.ClientHeartbeatResponse, error) {
	return s.proxy.ClientHeartbeat(ctx, req)
}

// GetClientTelemetry retrieves client telemetry data
func (s *Server) GetClientTelemetry(ctx context.Context, req *milvuspb.GetClientTelemetryRequest) (*milvuspb.GetClientTelemetryResponse, error) {
	return s.proxy.GetClientTelemetry(ctx, req)
}

// PushClientCommand pushes a command to clients
func (s *Server) PushClientCommand(ctx context.Context, req *milvuspb.PushClientCommandRequest) (*milvuspb.PushClientCommandResponse, error) {
	return s.proxy.PushClientCommand(ctx, req)
}

// DeleteClientCommand deletes a client command
func (s *Server) DeleteClientCommand(ctx context.Context, req *milvuspb.DeleteClientCommandRequest) (*milvuspb.DeleteClientCommandResponse, error) {
	return s.proxy.DeleteClientCommand(ctx, req)
}

func (s *Server) BatchUpdateManifest(ctx context.Context, req *milvuspb.BatchUpdateManifestRequest) (*commonpb.Status, error) {
	return s.proxy.BatchUpdateManifest(ctx, req)
}

func (s *Server) RefreshExternalCollection(ctx context.Context, req *milvuspb.RefreshExternalCollectionRequest) (*milvuspb.RefreshExternalCollectionResponse, error) {
	return s.proxy.RefreshExternalCollection(ctx, req)
}

func (s *Server) GetRefreshExternalCollectionProgress(ctx context.Context, req *milvuspb.GetRefreshExternalCollectionProgressRequest) (*milvuspb.GetRefreshExternalCollectionProgressResponse, error) {
	return s.proxy.GetRefreshExternalCollectionProgress(ctx, req)
}

func (s *Server) ListRefreshExternalCollectionJobs(ctx context.Context, req *milvuspb.ListRefreshExternalCollectionJobsRequest) (*milvuspb.ListRefreshExternalCollectionJobsResponse, error) {
	return s.proxy.ListRefreshExternalCollectionJobs(ctx, req)
}
