ronantakizawa/codereview-bench huggingface dataset:
Repository: etcd-io/etcd
File: server/etcdserver/apply/apply.go (Go)

Code before:
// 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 apply

import (
	"go.uber.org/zap"

	pb "go.etcd.io/etcd/api/v3/etcdserverpb"
	"go.etcd.io/etcd/pkg/v3/pbutil"
	"go.etcd.io/etcd/pkg/v3/wait"
	"go.etcd.io/etcd/server/v3/etcdserver/api/membership"
	"go.etcd.io/raft/v3/raftpb"
)

func Apply(lg *zap.Logger, e *raftpb.Entry, uberApply UberApplier, w wait.Wait, shouldApplyV3 membership.ShouldApplyV3) (ar *Result, id uint64) {
	var raftReq pb.InternalRaftRequest
	if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible
		var r pb.Request
		rp := &r
		pbutil.MustUnmarshal(rp, e.Data)
		lg.Debug("applyEntryNormal", zap.Stringer("V2request", rp))
		raftReq = v2ToV3Request(lg, (*RequestV2)(rp))
	}
	lg.Debug("applyEntryNormal", zap.Stringer("raftReq", &raftReq))

	if raftReq.V2 != nil {
		req := (*RequestV2)(raftReq.V2)
		raftReq = v2ToV3Request(lg, req)
	}

	id = raftReq.ID
	if id == 0 {
		if raftReq.Header == nil {
			lg.Panic("applyEntryNormal, could not find a header")
		}
		id = raftReq.Header.ID
	}

	needResult := w.IsRegistered(id)
	if needResult || !noSideEffect(&raftReq) {
		if !needResult && raftReq.Txn != nil {
			removeNeedlessRangeReqs(raftReq.Txn)
		}
		return uberApply.Apply(&raftReq, shouldApplyV3), id
	}
	return nil, id
}

func noSideEffect(r *pb.InternalRaftRequest) bool {

Review comment (bug):
```suggestion
	lg.Debug("Apply", zap.Stringer("raftReq", &raftReq))
```

Code after:
// 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 apply

import (
	"go.uber.org/zap"

	pb "go.etcd.io/etcd/api/v3/etcdserverpb"
	"go.etcd.io/etcd/pkg/v3/pbutil"
	"go.etcd.io/etcd/pkg/v3/wait"
	"go.etcd.io/etcd/server/v3/etcdserver/api/membership"
	"go.etcd.io/raft/v3/raftpb"
)

func Apply(lg *zap.Logger, e *raftpb.Entry, uberApply UberApplier, w wait.Wait, shouldApplyV3 membership.ShouldApplyV3) (ar *Result, id uint64) {
	var raftReq pb.InternalRaftRequest
	if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible
		var r pb.Request
		rp := &r
		pbutil.MustUnmarshal(rp, e.Data)
		lg.Debug("Apply", zap.Stringer("V2request", rp))
		raftReq = v2ToV3Request(lg, (*RequestV2)(rp))
	}
	lg.Debug("Apply", zap.Stringer("raftReq", &raftReq))

	if raftReq.V2 != nil {
		req := (*RequestV2)(raftReq.V2)
		raftReq = v2ToV3Request(lg, req)
	}

	id = raftReq.ID
	if id == 0 {
		if raftReq.Header == nil {
			lg.Panic("Apply, could not find a header")
		}
		id = raftReq.Header.ID
	}

	needResult := w.IsRegistered(id)
	if needResult || !noSideEffect(&raftReq) {
		if !needResult && raftReq.Txn != nil {
			removeNeedlessRangeReqs(raftReq.Txn)
		}
		return uberApply.Apply(&raftReq, shouldApplyV3), id
	}
	return nil, id
}

func noSideEffect(r *pb.InternalRaftRequest) bool {
Repository: etcd-io/etcd
File: server/etcdserver/cluster_util.go (Go)

Code before:
			)
			continue
		}
		return &vers, nil
	}
	return nil, err
}

func promoteMemberHTTP(ctx context.Context, url string, id uint64, peerRt http.RoundTripper) ([]*membership.Member, error) {
	cc := &http.Client{
		Transport: peerRt,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	// TODO: refactor member http handler code
	// cannot import etcdhttp, so manually construct url
	requestURL := url + "/members/promote/" + fmt.Sprintf("%d", id)
	req, err := http.NewRequest(http.MethodPost, requestURL, nil)
	if err != nil {
		return nil, err
	}

	// add the auth token via HTTP header if present in gRPC metadata
	if md, ok := metadata.FromIncomingContext(ctx); ok {
		if ts := md.Get(rpctypes.TokenFieldNameGRPC); len(ts) > 0 {
			req.Header.Set("Authorization", ts[0])
		}
	}

	req = req.WithContext(ctx)
	resp, err := cc.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode == http.StatusRequestTimeout {
		return nil, errors.ErrTimeout
	}
	if resp.StatusCode == http.StatusPreconditionFailed {
		// both ErrMemberNotLearner and ErrLearnerNotReady have same http status code
		if strings.Contains(string(b), errors.ErrLearnerNotReady.Error()) {
			return nil, errors.ErrLearnerNotReady
		}
		if strings.Contains(string(b), membership.ErrMemberNotLearner.Error()) {
			return nil, membership.ErrMemberNotLearner

Review comment (security):
suggest to follow the same way to extract the token,

https://github.com/etcd-io/etcd/blob/48f735d13e83dea5b1901ea627eddd75d05ee8d5/server/auth/store.go#L1066-L1069

Code after:
			)
			continue
		}
		return &vers, nil
	}
	return nil, err
}

func promoteMemberHTTP(ctx context.Context, url string, id uint64, peerRt http.RoundTripper) ([]*membership.Member, error) {
	cc := &http.Client{
		Transport: peerRt,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	// TODO: refactor member http handler code
	// cannot import etcdhttp, so manually construct url
	requestURL := url + "/members/promote/" + fmt.Sprintf("%d", id)
	req, err := http.NewRequest(http.MethodPost, requestURL, nil)
	if err != nil {
		return nil, err
	}

	// add the auth token via HTTP header if present in gRPC metadata
	if md, ok := metadata.FromIncomingContext(ctx); ok {
		ts, ok := md[rpctypes.TokenFieldNameGRPC]
		if !ok {
			ts, ok = md[rpctypes.TokenFieldNameSwagger]
		}

		if ok && len(ts) > 0 {
			token := ts[0]
			req.Header.Set("Authorization", token)
		}
	}

	req = req.WithContext(ctx)
	resp, err := cc.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode == http.StatusRequestTimeout {
		return nil, errors.ErrTimeout
	}
	if resp.StatusCode == http.StatusPreconditionFailed {
Repository: etcd-io/etcd
File: tests/robustness/model/types.go (Go)

Code before:
	Value   ValueOrHash
	LeaseID int64
}

type DeleteOptions struct {
	Key string
}

type TxnRequest struct {
	Conditions          []EtcdCondition
	OperationsOnSuccess []EtcdOperation
	OperationsOnFailure []EtcdOperation
}

type EtcdCondition struct {
	Key              string
	ExpectedRevision int64
	ExpectedVersion  int64
}

type EtcdOperation struct {
	Type    OperationType
	Range   RangeOptions
	Put     PutOptions
	Delete  DeleteOptions
	Compact CompactRequest
}

type OperationType string

const (
	RangeOperation   OperationType = "range-operation"
	PutOperation     OperationType = "put-operation"
	DeleteOperation  OperationType = "delete-operation"
	CompactOperation OperationType = "compact-operation"
)

type LeaseGrantRequest struct {
	LeaseID int64
}
type LeaseRevokeRequest struct {
	LeaseID int64
}
type DefragmentRequest struct{}

// MaybeEtcdResponse extends EtcdResponse to include partial information about responses to a request.
// Possible response state information:
// * Normal response. Client observed response. Only EtcdResponse is set.
// * Persisted. Client didn't observe response, but we know it was persisted by etcd. Only Persisted is set
// * Persisted with Revision. Client didn't observe a response, but we know that it was persisted, and its revision. Both Persisted and PersistedRevision is set.
// * Error response. Client observed error, but we don't know if it was persisted. Only Error is set.

Review comment (suggestion):
EtcdOperation represents operations that can be executed within TXN request, so I don't think we should put a Compaction here. Compaction implementation will be a little different so we can skip it for now.


Code after:
	Value   ValueOrHash
	LeaseID int64
}

type DeleteOptions struct {
	Key string
}

type TxnRequest struct {
	Conditions          []EtcdCondition
	OperationsOnSuccess []EtcdOperation
	OperationsOnFailure []EtcdOperation
}

type EtcdCondition struct {
	Key              string
	ExpectedRevision int64
	ExpectedVersion  int64
}

type EtcdOperation struct {
	Type   OperationType
	Range  RangeOptions
	Put    PutOptions
	Delete DeleteOptions
}

type OperationType string

const (
	RangeOperation  OperationType = "range-operation"
	PutOperation    OperationType = "put-operation"
	DeleteOperation OperationType = "delete-operation"
)

type LeaseGrantRequest struct {
	LeaseID int64
}
type LeaseRevokeRequest struct {
	LeaseID int64
}
type DefragmentRequest struct{}

// MaybeEtcdResponse extends EtcdResponse to include partial information about responses to a request.
// Possible response state information:
// * Normal response. Client observed response. Only EtcdResponse is set.
// * Persisted. Client didn't observe response, but we know it was persisted by etcd. Only Persisted is set
// * Persisted with Revision. Client didn't observe a response, but we know that it was persisted, and its revision. Both Persisted and PersistedRevision is set.
// * Error response. Client observed error, but we don't know if it was persisted. Only Error is set.
type MaybeEtcdResponse struct {
	EtcdResponse
Repository: etcd-io/etcd
File: etcdutl/etcdutl/check_command.go (Go)

Code before:
	}
	cmd.AddCommand(NewCheckV2StoreCommand())
	return cmd
}

var (
	argCheckV2StoreDataDir string
)

// NewCheckV2StoreCommand returns the cobra command for "check v2store".
func NewCheckV2StoreCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "v2store",
		Short: "Check custom content in v2store",
		Run:   checkV2StoreRunFunc,
	}
	cmd.Flags().StringVar(&argCheckV2StoreDataDir, "data-dir", "", "Required. A data directory not in use by etcd.")
	cmd.MarkFlagRequired("data-dir")
	return cmd
}

func checkV2StoreRunFunc(_ *cobra.Command, _ []string) {
	err := checkV2StoreDataDir(argCheckV2StoreDataDir)
	if err != nil {
		cobrautl.ExitWithError(cobrautl.ExitError, err)
	}
	fmt.Println("No custom content found in v2store.")
}

func checkV2StoreDataDir(dataDir string) error {
	var (
		lg = GetLogger()

		walDir  = datadir.ToWalDir(dataDir)
		snapDir = datadir.ToSnapDir(dataDir)
	)

	walSnaps, err := wal.ValidSnapshotEntries(lg, walDir)
	if err != nil {
		if errors.Is(err, wal.ErrFileNotFound) {
			return nil
		}
		return err
	}

	ss := snap.New(lg, snapDir)
	snapshot, err := ss.LoadNewestAvailable(walSnaps)
	if err != nil {
		if errors.Is(err, snap.ErrNoSnapshot) {
			return nil
		}

Review comment (suggestion):
nit: Could you replace this with the non-deprecated `toWALDir`?

Ref: https://github.com/etcd-io/etcd/blob/2ce96db52fff422d0415b859267f1f70b418a061/server/storage/datadir/datadir.go#L34-L41

```suggestion
	walDir := datadir.ToWALDir(argCheckV2StoreDataDir)
```

Code after:
	}
	cmd.AddCommand(NewCheckV2StoreCommand())
	return cmd
}

var (
	argCheckV2StoreDataDir string
	argCheckV2StoreWALDir  string
)

// NewCheckV2StoreCommand returns the cobra command for "check v2store".
func NewCheckV2StoreCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "v2store",
		Short: "Check custom content in v2store",
		Run:   checkV2StoreRunFunc,
	}
	cmd.Flags().StringVar(&argCheckV2StoreDataDir, "data-dir", "", "Required. A data directory not in use by etcd.")
	cmd.Flags().StringVar(&argCheckV2StoreWALDir, "wal-dir", "", "Optional. A dedicated WAL directory.")
	cmd.MarkFlagRequired("data-dir")
	return cmd
}

func checkV2StoreRunFunc(_ *cobra.Command, _ []string) {
	snapDir := datadir.ToSnapDir(argCheckV2StoreDataDir)
	walDir := datadir.ToWalDir(argCheckV2StoreDataDir)
	if argCheckV2StoreWALDir != "" {
		walDir = argCheckV2StoreWALDir
	}

	err := checkV2StoreDataDir(snapDir, walDir)
	if err != nil {
		cobrautl.ExitWithError(cobrautl.ExitError, err)
	}
	fmt.Println("No custom content found in v2store.")
}

func checkV2StoreDataDir(snapDir string, walDir string) error {
	var lg = GetLogger()

	walSnaps, err := wal.ValidSnapshotEntries(lg, walDir)
	if err != nil {
		if errors.Is(err, wal.ErrFileNotFound) {
			return nil
		}
		return err
	}

	ss := snap.New(lg, snapDir)
	snapshot, err := ss.LoadNewestAvailable(walSnaps)
	if err != nil {
Repository: etcd-io/etcd
File: server/etcdserver/api/v3rpc/grpc.go (Go)

Code before:
	pb.RegisterAuthServer(grpcServer, NewAuthServer(s))

	hsrv := health.NewServer()
	healthNotifier := newHealthNotifier(hsrv, s)
	healthpb.RegisterHealthServer(grpcServer, hsrv)
	pb.RegisterMaintenanceServer(grpcServer, NewMaintenanceServer(s, healthNotifier))

	// set zero values for metrics registered for this grpc server
	serverMetrics.InitializeMetrics(grpcServer)

	return grpcServer
}

func getServerMetrics(metricType string) (*grpc_prometheus.ServerMetrics, error) {
	metricsLock.Lock()
	defer metricsLock.Unlock()

	if serverMetrics, ok := metricsCache[metricType]; ok {
		return serverMetrics, nil
	}

	var mopts []grpc_prometheus.ServerMetricsOption
	if metricType == "extensive" {
		mopts = append(mopts, grpc_prometheus.WithServerHandlingTimeHistogram())
	}
	serverMetrics := grpc_prometheus.NewServerMetrics(mopts...)
	err := prometheus.Register(serverMetrics)
	if err != nil {
		return nil, err
	}
	metricsCache[metricType] = serverMetrics
	return serverMetrics, nil
}


Review comment (performance):
sorry, I forgot that `Server` doesn't return error to caller.
I think we can pass that logger into getServerMetrics. just like this

```go
func getServerMetrics(metricType string) *grpc_prometheus.ServerMetrics {
 ...
serverMetrics := grpc_prometheus.NewServerMetrics(mopts...)
metricsCache[metricType] = serverMetrics

	err := prometheus.Register(serverMetrics)
	if err != nil {
		logger.Warn()
	}
	
	return serverMetrics
}
```

please squash your commits into one. thanks

Code after:
	healthpb.RegisterHealthServer(grpcServer, hsrv)
	pb.RegisterMaintenanceServer(grpcServer, NewMaintenanceServer(s, healthNotifier))

	// set zero values for metrics registered for this grpc server
	serverMetrics.InitializeMetrics(grpcServer)

	return grpcServer
}

func getServerMetrics(metricType string, lg *zap.Logger) *grpc_prometheus.ServerMetrics {
	metricsServerLock.Lock()
	defer metricsServerLock.Unlock()

	if metricsServerCached == nil {
		var mopts []grpc_prometheus.ServerMetricsOption
		if metricType == "extensive" {
			mopts = append(mopts, grpc_prometheus.WithServerHandlingTimeHistogram())
		}
		metricsServerCached = grpc_prometheus.NewServerMetrics(mopts...)
		err := prometheus.Register(metricsServerCached)
		if err != nil {
			lg.Warn("etcdserver: failed to register grpc metrics", zap.Error(err))
		}
	}

	return metricsServerCached
}
Repository: etcd-io/etcd
File: server/etcdserver/api/v3rpc/grpc.go (Go)

Code before:

import (
	"crypto/tls"
	"math"
	"sync"

	grpc_prometheus "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
	"github.com/prometheus/client_golang/prometheus"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"

	pb "go.etcd.io/etcd/api/v3/etcdserverpb"
	"go.etcd.io/etcd/client/v3/credentials"
	"go.etcd.io/etcd/server/v3/etcdserver"
)

const (
	maxSendBytes = math.MaxInt32
)

var (
	metricsLock  sync.Mutex
	metricsCache = make(map[string]*grpc_prometheus.ServerMetrics)
)

func Server(s *etcdserver.EtcdServer, tls *tls.Config, interceptor grpc.UnaryServerInterceptor, gopts ...grpc.ServerOption) *grpc.Server {
	var opts []grpc.ServerOption
	opts = append(opts, grpc.CustomCodec(&codec{}))
	if tls != nil {
		opts = append(opts, grpc.Creds(credentials.NewTransportCredential(tls)))
	}

	serverMetrics := getServerMetrics(s.Cfg.Metrics, s.Cfg.Logger)

	chainUnaryInterceptors := []grpc.UnaryServerInterceptor{
		newLogUnaryInterceptor(s),
		newUnaryInterceptor(s),
		serverMetrics.UnaryServerInterceptor(),
	}
	if interceptor != nil {
		chainUnaryInterceptors = append(chainUnaryInterceptors, interceptor)
	}

	chainStreamInterceptors := []grpc.StreamServerInterceptor{
		newStreamInterceptor(s),
		serverMetrics.StreamServerInterceptor(),
	}


Review comment (suggestion):
```suggestion
	serverMetrics *grpc_prometheus.ServerMetrics
```

Code after:

import (
	"crypto/tls"
	"math"
	"sync"

	grpc_prometheus "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
	"github.com/prometheus/client_golang/prometheus"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"

	pb "go.etcd.io/etcd/api/v3/etcdserverpb"
	"go.etcd.io/etcd/client/v3/credentials"
	"go.etcd.io/etcd/server/v3/etcdserver"
)

const (
	maxSendBytes = math.MaxInt32
)

var (
	metricsServerLock   sync.Mutex
	metricsServerCached *grpc_prometheus.ServerMetrics
)

func Server(s *etcdserver.EtcdServer, tls *tls.Config, interceptor grpc.UnaryServerInterceptor, gopts ...grpc.ServerOption) *grpc.Server {
	var opts []grpc.ServerOption
	opts = append(opts, grpc.CustomCodec(&codec{}))
	if tls != nil {
		opts = append(opts, grpc.Creds(credentials.NewTransportCredential(tls)))
	}

	serverMetrics := getServerMetrics(s.Cfg.Metrics, s.Cfg.Logger)

	chainUnaryInterceptors := []grpc.UnaryServerInterceptor{
		newLogUnaryInterceptor(s),
		newUnaryInterceptor(s),
		serverMetrics.UnaryServerInterceptor(),
	}
	if interceptor != nil {
		chainUnaryInterceptors = append(chainUnaryInterceptors, interceptor)
	}

	chainStreamInterceptors := []grpc.StreamServerInterceptor{
		newStreamInterceptor(s),
		serverMetrics.StreamServerInterceptor(),
	}
Repository: etcd-io/etcd
File: server/etcdserver/api/v3rpc/grpc.go (Go)

Code before:
	grpcServer := grpc.NewServer(append(opts, gopts...)...)

	pb.RegisterKVServer(grpcServer, NewQuotaKVServer(s))
	pb.RegisterWatchServer(grpcServer, NewWatchServer(s))
	pb.RegisterLeaseServer(grpcServer, NewQuotaLeaseServer(s))
	pb.RegisterClusterServer(grpcServer, NewClusterServer(s))
	pb.RegisterAuthServer(grpcServer, NewAuthServer(s))

	hsrv := health.NewServer()
	healthNotifier := newHealthNotifier(hsrv, s)
	healthpb.RegisterHealthServer(grpcServer, hsrv)
	pb.RegisterMaintenanceServer(grpcServer, NewMaintenanceServer(s, healthNotifier))

	// set zero values for metrics registered for this grpc server
	metrics.InitializeMetrics(grpcServer)

	return grpcServer
}

func getServerMetrics(metricType string, logger *zap.Logger) *grpc_prometheus.ServerMetrics {
	metricsOnce.Do(func() {
		var mopts []grpc_prometheus.ServerMetricsOption
		if metricType == "extensive" {
			mopts = append(mopts, grpc_prometheus.WithServerHandlingTimeHistogram())
		}
		serverMetrics = grpc_prometheus.NewServerMetrics(mopts...)
		err := prometheus.Register(serverMetrics)
		if err != nil {
			logger.Warn("etcdserver: failed to register grpc metrics", zap.Error(err))
		}
	})

	return serverMetrics
}


Review comment (suggestion):
for ETCD process, it should be fine because that metricType is generated from config and they are the same for each call. but for integration, it's risk here. it could be different value. but once only does one time.

Code after:
	grpcServer := grpc.NewServer(append(opts, gopts...)...)

	pb.RegisterKVServer(grpcServer, NewQuotaKVServer(s))
	pb.RegisterWatchServer(grpcServer, NewWatchServer(s))
	pb.RegisterLeaseServer(grpcServer, NewQuotaLeaseServer(s))
	pb.RegisterClusterServer(grpcServer, NewClusterServer(s))
	pb.RegisterAuthServer(grpcServer, NewAuthServer(s))

	hsrv := health.NewServer()
	healthNotifier := newHealthNotifier(hsrv, s)
	healthpb.RegisterHealthServer(grpcServer, hsrv)
	pb.RegisterMaintenanceServer(grpcServer, NewMaintenanceServer(s, healthNotifier))

	// set zero values for metrics registered for this grpc server
	serverMetrics.InitializeMetrics(grpcServer)

	return grpcServer
}

func getServerMetrics(metricType string, lg *zap.Logger) *grpc_prometheus.ServerMetrics {
	metricsServerLock.Lock()
	defer metricsServerLock.Unlock()

	if metricsServerCached == nil {
		var mopts []grpc_prometheus.ServerMetricsOption
		if metricType == "extensive" {
			mopts = append(mopts, grpc_prometheus.WithServerHandlingTimeHistogram())
		}
		metricsServerCached = grpc_prometheus.NewServerMetrics(mopts...)
		err := prometheus.Register(metricsServerCached)
		if err != nil {
			lg.Warn("etcdserver: failed to register grpc metrics", zap.Error(err))
		}
	}

	return metricsServerCached
}
Repository: etcd-io/etcd
File: server/etcdserver/api/v3rpc/grpc.go (Go)

Code before:
package v3rpc

import (
	"crypto/tls"
	"math"
	"sync"

	grpc_prometheus "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
	"github.com/prometheus/client_golang/prometheus"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"

	pb "go.etcd.io/etcd/api/v3/etcdserverpb"
	"go.etcd.io/etcd/client/v3/credentials"
	"go.etcd.io/etcd/server/v3/etcdserver"
)

const (
	maxSendBytes = math.MaxInt32
)

var (
	metricsCache sync.Map
)

func Server(s *etcdserver.EtcdServer, tls *tls.Config, interceptor grpc.UnaryServerInterceptor, gopts ...grpc.ServerOption) *grpc.Server {
	var opts []grpc.ServerOption
	opts = append(opts, grpc.CustomCodec(&codec{}))
	if tls != nil {
		opts = append(opts, grpc.Creds(credentials.NewTransportCredential(tls)))
	}

	serverMetrics := getServerMetrics(s.Cfg.Metrics, s.Cfg.Logger)

	chainUnaryInterceptors := []grpc.UnaryServerInterceptor{
		newLogUnaryInterceptor(s),
		newUnaryInterceptor(s),
		serverMetrics.UnaryServerInterceptor(),
	}
	if interceptor != nil {
		chainUnaryInterceptors = append(chainUnaryInterceptors, interceptor)
	}

	chainStreamInterceptors := []grpc.StreamServerInterceptor{
		newStreamInterceptor(s),
		serverMetrics.StreamServerInterceptor(),
	}


Review comment (performance):
```suggestion
	metricsCollectorCache sync.Map
```

Code after:
package v3rpc

import (
	"crypto/tls"
	"math"
	"sync"

	grpc_prometheus "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
	"github.com/prometheus/client_golang/prometheus"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"

	pb "go.etcd.io/etcd/api/v3/etcdserverpb"
	"go.etcd.io/etcd/client/v3/credentials"
	"go.etcd.io/etcd/server/v3/etcdserver"
)

const (
	maxSendBytes = math.MaxInt32
)

var (
	metricsServerLock   sync.Mutex
	metricsServerCached *grpc_prometheus.ServerMetrics
)

func Server(s *etcdserver.EtcdServer, tls *tls.Config, interceptor grpc.UnaryServerInterceptor, gopts ...grpc.ServerOption) *grpc.Server {
	var opts []grpc.ServerOption
	opts = append(opts, grpc.CustomCodec(&codec{}))
	if tls != nil {
		opts = append(opts, grpc.Creds(credentials.NewTransportCredential(tls)))
	}

	serverMetrics := getServerMetrics(s.Cfg.Metrics, s.Cfg.Logger)

	chainUnaryInterceptors := []grpc.UnaryServerInterceptor{
		newLogUnaryInterceptor(s),
		newUnaryInterceptor(s),
		serverMetrics.UnaryServerInterceptor(),
	}
	if interceptor != nil {
		chainUnaryInterceptors = append(chainUnaryInterceptors, interceptor)
	}

	chainStreamInterceptors := []grpc.StreamServerInterceptor{
		newStreamInterceptor(s),
		serverMetrics.StreamServerInterceptor(),
	}