mrproliu commented on code in PR #928:
URL: 
https://github.com/apache/skywalking-banyandb/pull/928#discussion_r2671441246


##########
banyand/metadata/discovery/file/file.go:
##########
@@ -0,0 +1,366 @@
+// Licensed to 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. Apache Software Foundation (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 file implements file-based node discovery for distributed metadata 
management.
+package file
+
+import (
+       "context"
+       "errors"
+       "fmt"
+       "os"
+       "sync"
+       "time"
+
+       "gopkg.in/yaml.v3"
+
+       databasev1 
"github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+       "github.com/apache/skywalking-banyandb/banyand/metadata/schema"
+       "github.com/apache/skywalking-banyandb/banyand/observability"
+       "github.com/apache/skywalking-banyandb/pkg/grpchelper"
+       "github.com/apache/skywalking-banyandb/pkg/logger"
+       "github.com/apache/skywalking-banyandb/pkg/run"
+)
+
+// Service implements file-based node discovery.
+type Service struct {
+       nodeCache     map[string]*databasev1.Node
+       closer        *run.Closer
+       log           *logger.Logger
+       metrics       *metrics
+       handlers      map[string]schema.EventHandler
+       filePath      string
+       grpcTimeout   time.Duration
+       fetchInterval time.Duration
+       cacheMutex    sync.RWMutex
+       handlersMutex sync.RWMutex
+}
+
+// Config holds configuration for file discovery service.
+type Config struct {
+       FilePath      string
+       GRPCTimeout   time.Duration
+       FetchInterval time.Duration
+}
+
+// NodeFileConfig represents the YAML configuration file structure.
+type NodeFileConfig struct {
+       Nodes []NodeConfig `yaml:"nodes"`
+}
+
+// NodeConfig represents a single node configuration.
+type NodeConfig struct {
+       Name       string `yaml:"name"`
+       Address    string `yaml:"grpc_address"`
+       CACertPath string `yaml:"ca_cert_path"`
+       TLSEnabled bool   `yaml:"tls_enabled"`
+}
+
+// NewService creates a new file discovery service.
+func NewService(cfg Config) (*Service, error) {
+       if cfg.FilePath == "" {
+               return nil, errors.New("file path cannot be empty")
+       }
+
+       // validate file exists and is readable
+       if _, err := os.Stat(cfg.FilePath); err != nil {
+               return nil, fmt.Errorf("failed to access file path %s: %w", 
cfg.FilePath, err)
+       }
+
+       svc := &Service{
+               filePath:      cfg.FilePath,
+               nodeCache:     make(map[string]*databasev1.Node),
+               handlers:      make(map[string]schema.EventHandler),
+               closer:        run.NewCloser(1),
+               log:           logger.GetLogger("metadata-discovery-file"),
+               grpcTimeout:   cfg.GRPCTimeout,
+               fetchInterval: cfg.FetchInterval,
+       }
+
+       return svc, nil
+}
+
+// Start begins the file discovery background process.
+func (s *Service) Start(ctx context.Context) error {
+       s.log.Debug().Str("file_path", s.filePath).Msg("Starting file-based 
node discovery service")
+
+       // initial load
+       if err := s.loadAndParseFile(ctx); err != nil {
+               return fmt.Errorf("failed to load initial configuration: %w", 
err)
+       }
+
+       // start periodic fetch loop
+       go s.periodicFetch(ctx)
+
+       return nil
+}
+
+func (s *Service) loadAndParseFile(ctx context.Context) error {
+       startTime := time.Now()
+       var parseErr error
+       defer func() {
+               if s.metrics != nil {
+                       duration := time.Since(startTime)
+                       s.metrics.fileLoadCount.Inc(1)
+                       s.metrics.fileLoadDuration.Observe(duration.Seconds())
+                       if parseErr != nil {
+                               s.metrics.fileLoadFailedCount.Inc(1)
+                       }
+               }
+       }()
+
+       data, err := os.ReadFile(s.filePath)
+       if err != nil {
+               parseErr = fmt.Errorf("failed to read file: %w", err)
+               return parseErr
+       }
+
+       var cfg NodeFileConfig
+       if err := yaml.Unmarshal(data, &cfg); err != nil {
+               parseErr = fmt.Errorf("failed to parse YAML: %w", err)
+               return parseErr
+       }
+
+       // validate required fields
+       for idx, node := range cfg.Nodes {
+               if node.Address == "" {
+                       parseErr = fmt.Errorf("node %s at index %d is missing 
required field: grpc_address", node.Name, idx)
+                       return parseErr
+               }
+               if node.TLSEnabled && node.CACertPath == "" {
+                       parseErr = fmt.Errorf("node %s at index %d has TLS 
enabled but missing ca_cert_path", node.Name, idx)
+                       return parseErr
+               }
+       }
+
+       // update cache
+       s.updateNodeCache(ctx, cfg.Nodes)
+
+       s.log.Debug().Int("node_count", len(cfg.Nodes)).Msg("Successfully 
loaded configuration file")
+       return nil
+}
+
+func (s *Service) fetchNodeMetadata(ctx context.Context, nodeConfig 
NodeConfig) (*databasev1.Node, error) {
+       ctxTimeout, cancel := context.WithTimeout(ctx, s.grpcTimeout)
+       defer cancel()
+
+       // prepare TLS options
+       dialOpts, err := grpchelper.SecureOptions(nil, nodeConfig.TLSEnabled, 
false, nodeConfig.CACertPath)
+       if err != nil {
+               return nil, fmt.Errorf("failed to load TLS config for node %s: 
%w", nodeConfig.Name, err)
+       }
+
+       // connect to node
+       // nolint:contextcheck
+       conn, connErr := grpchelper.Conn(nodeConfig.Address, s.grpcTimeout, 
dialOpts...)
+       if connErr != nil {
+               return nil, fmt.Errorf("failed to connect to %s: %w", 
nodeConfig.Address, connErr)
+       }
+       defer conn.Close()

Review Comment:
   The `GetCurrentNode` already uses the timeout context, so it's fine here. 



-- 
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]

Reply via email to