Similarityoung commented on code in PR #849:
URL: https://github.com/apache/dubbo-go-pixiu/pull/849#discussion_r2648949948


##########
pkg/filter/network/grpcproxy/filter/proxy/reflection_manager.go:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) 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 proxy
+
+import (
+       "context"
+       "fmt"
+       "io"
+       "sync"
+       "time"
+)
+
+import (
+       "github.com/pkg/errors"
+
+       "google.golang.org/grpc"
+       rpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
+
+       "google.golang.org/protobuf/proto"
+
+       "google.golang.org/protobuf/reflect/protodesc"
+       "google.golang.org/protobuf/reflect/protoreflect"
+       "google.golang.org/protobuf/reflect/protoregistry"
+
+       "google.golang.org/protobuf/types/descriptorpb"
+)
+
+import (
+       "github.com/apache/dubbo-go-pixiu/pkg/logger"
+)
+
+const (
+       defaultDescCacheTTL = 5 * time.Minute
+       reflectionTimeout   = 10 * time.Second
+)
+
+// ReflectionManager manages gRPC reflection clients and descriptor caching
+// using official google.golang.org/protobuf libraries
+type ReflectionManager struct {
+       cache    *DescriptorCache
+       cacheTTL time.Duration
+       // fileDescCache caches file descriptors per address
+       fileDescCache sync.Map // address -> *protoregistry.Files
+       mu            sync.RWMutex
+}
+
+// NewReflectionManager creates a new reflection manager
+func NewReflectionManager(cacheTTL time.Duration) *ReflectionManager {
+       if cacheTTL <= 0 {
+               cacheTTL = defaultDescCacheTTL
+       }
+       return &ReflectionManager{
+               cache:    NewDescriptorCache(cacheTTL),
+               cacheTTL: cacheTTL,
+       }
+}
+
+// GetMethodDescriptor retrieves a method descriptor using gRPC reflection
+// Results are cached for improved performance
+func (rm *ReflectionManager) GetMethodDescriptor(
+       ctx context.Context,
+       conn *grpc.ClientConn,
+       address string,
+       serviceName string,
+       methodName string,
+) (protoreflect.MethodDescriptor, error) {
+       // Build cache key
+       cacheKey := BuildCacheKey(address, serviceName, methodName)
+
+       // Check cache first
+       if cached := rm.cache.Get(cacheKey); cached != nil {
+               logger.Debugf("Reflection cache hit for %s", cacheKey)
+               return cached, nil
+       }
+
+       logger.Debugf("Reflection cache miss for %s, performing reflection", 
cacheKey)
+
+       // Perform reflection with timeout
+       reflectCtx, cancel := context.WithTimeout(ctx, reflectionTimeout)
+       defer cancel()
+
+       // Get or create file registry for this address
+       files, err := rm.getOrCreateFileRegistry(reflectCtx, conn, address, 
serviceName)
+       if err != nil {
+               return nil, err
+       }
+
+       // Find service descriptor
+       serviceDesc, err := 
files.FindDescriptorByName(protoreflect.FullName(serviceName))
+       if err != nil {
+               return nil, errors.Wrapf(err, "failed to find service %s", 
serviceName)
+       }
+
+       svcDesc, ok := serviceDesc.(protoreflect.ServiceDescriptor)
+       if !ok {
+               return nil, fmt.Errorf("%s is not a service", serviceName)
+       }
+
+       // Find method descriptor
+       methodDesc := svcDesc.Methods().ByName(protoreflect.Name(methodName))
+       if methodDesc == nil {
+               return nil, fmt.Errorf("method %s not found in service %s", 
methodName, serviceName)
+       }
+
+       // Cache the result
+       rm.cache.Set(cacheKey, methodDesc)
+       logger.Debugf("Cached method descriptor for %s", cacheKey)
+
+       return methodDesc, nil
+}
+
+// getOrCreateFileRegistry gets or creates a file registry for the given 
address
+func (rm *ReflectionManager) getOrCreateFileRegistry(
+       ctx context.Context,
+       conn *grpc.ClientConn,
+       address string,
+       serviceName string,
+) (*protoregistry.Files, error) {
+       // Check if we already have a registry for this address
+       if cached, ok := rm.fileDescCache.Load(address); ok {
+               return cached.(*protoregistry.Files), nil
+       }
+
+       rm.mu.Lock()
+       defer rm.mu.Unlock()
+
+       // Double check after acquiring lock
+       if cached, ok := rm.fileDescCache.Load(address); ok {
+               return cached.(*protoregistry.Files), nil
+       }
+
+       // Create reflection client
+       client := rpb.NewServerReflectionClient(conn)
+       stream, err := client.ServerReflectionInfo(ctx)
+       if err != nil {
+               return nil, errors.Wrap(err, "failed to create reflection 
stream")
+       }
+       defer stream.CloseSend()
+
+       // Request file descriptor for the service
+       fileDescs, err := rm.resolveServiceFileDescriptors(stream, serviceName)
+       if err != nil {
+               return nil, err

Review Comment:
   ### AI review
   
   `getOrCreateFileRegistry` 方法使用了 rm.mu 包裹了整个 `getOrCreateFileRegistry` 
逻辑,包括网络调用 `client.ServerReflectionInfo(ctx)`。
   
   ```go
   rm.mu.Lock()
   defer rm.mu.Unlock()
   // ...
   stream, err := client.ServerReflectionInfo(ctx) // 网络 IO
   ```
   
   这是一个全局锁。虽然在 Cache Hit 时不会触发,但在高并发冷启动(大量新服务同时请求)或缓存批量过期时,会导致所有 Reflection 
请求(甚至是对不同服务的请求)串行化,严重影响性能。 
   
   建议: 使用 singleflight 模式针对每个 address 进行通过,或者将锁的粒度细化到 address 级别,避免全局阻塞。
   



##########
pkg/filter/network/grpcproxy/filter/proxy/grpc_proxy_filter.go:
##########
@@ -174,18 +220,74 @@ func (f *Filter) handleStream(ctx *grpcCtx.GrpcContext, 
address string) filter.F
                        md.Set(k, str)
                }
        }
+
+       // Detect protocol type (gRPC vs Triple)
+       contentType := ""
+       if ct, ok := ctx.Attachments["content-type"].(string); ok {
+               contentType = ct
+       }
+       protocol := DetectProtocol(contentType)

Review Comment:
   这里为什么需要检测类型,这里的内容我记得只会从 grpclistener 里过来,triple 
的话应该用的是triplelistener而不是grpclistener;
   
   换句话说,我觉得这里如果是triple的话就不会走这里了。



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to