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


##########
banyand/metadata/schema/schemaserver/grpc.go:
##########
@@ -252,47 +278,115 @@ func (s *schemaManagementServer) RepairSchema(ctx 
context.Context, req *schemav1
 
 type schemaUpdateServer struct {
        schemav1.UnimplementedSchemaUpdateServiceServer
-       server  *server
-       l       *logger.Logger
-       metrics *serverMetrics
+       server   *server
+       watchers *watcherManager
+       l        *logger.Logger
+       metrics  *serverMetrics
 }
 
-// AggregateSchemaUpdates returns distinct schema names that have been 
modified.
-func (s *schemaUpdateServer) AggregateSchemaUpdates(ctx context.Context,
-       req *schemav1.AggregateSchemaUpdatesRequest,
-) (*schemav1.AggregateSchemaUpdatesResponse, error) {
-       s.metrics.totalStarted.Inc(1, "aggregate")
-       start := time.Now()
-       defer func() {
-               s.metrics.totalFinished.Inc(1, "aggregate")
-               s.metrics.totalLatency.Inc(time.Since(start).Seconds(), 
"aggregate")
+// WatchSchemas implements bi-directional streaming for schema change events.
+// Clients send requests on the stream to trigger replay (with max_revision 
and metadata_only).
+// The server continuously pushes live events and replays historical data on 
request.
+func (s *schemaUpdateServer) WatchSchemas(
+       stream grpc.BidiStreamingServer[schemav1.WatchSchemasRequest, 
schemav1.WatchSchemasResponse],
+) error {
+       id, ch := s.watchers.Subscribe()
+       defer s.watchers.Unsubscribe(id)
+
+       reqCh := make(chan *schemav1.WatchSchemasRequest, 1)
+       reqErrCh := make(chan error, 1)
+       go func() {
+               for {
+                       req, err := stream.Recv()
+                       if err != nil {
+                               reqErrCh <- err
+                               close(reqCh)
+                               return
+                       }
+                       reqCh <- req
+               }
        }()
-       if req.Query == nil {
-               return nil, errInvalidRequest("query is required")
+
+       for {
+               select {
+               case <-stream.Context().Done():
+                       return stream.Context().Err()
+               case err := <-reqErrCh:
+                       return err
+               case req, ok := <-reqCh:
+                       if !ok {
+                               return nil
+                       }
+                       if replayErr := s.replaySchemas(stream, req); replayErr 
!= nil {
+                               return replayErr
+                       }
+                       if doneErr := 
stream.Send(&schemav1.WatchSchemasResponse{
+                               EventType: 
schemav1.SchemaEventType_SCHEMA_EVENT_TYPE_REPLAY_DONE,
+                       }); doneErr != nil {
+                               return doneErr
+                       }
+               case resp, ok := <-ch:
+                       if !ok {
+                               return nil
+                       }
+                       if sendErr := stream.Send(resp); sendErr != nil {
+                               return sendErr
+                       }
+               }
        }
-       req.Query.Groups = []string{schema.SchemaGroup}
-       results, queryErr := s.server.db.Query(ctx, req.Query)
-       if queryErr != nil {
-               s.metrics.totalErr.Inc(1, "aggregate")
-               s.l.Error().Err(queryErr).Msg("failed to aggregate schema 
updates")
-               return nil, queryErr
+}
+
+func (s *schemaUpdateServer) replaySchemas(
+       stream grpc.BidiStreamingServer[schemav1.WatchSchemasRequest, 
schemav1.WatchSchemasResponse],
+       req *schemav1.WatchSchemasRequest,
+) error {
+       metadataOnly := len(req.TagProjection) > 0
+       query := &propertyv1.QueryRequest{
+               Groups:   []string{schema.SchemaGroup},
+               Criteria: req.Criteria,
+       }
+       results, err := s.server.db.Query(stream.Context(), query)
+       if err != nil {
+               return err
        }
-       nameSet := make(map[string]struct{}, len(results))
        for _, result := range results {
                var p propertyv1.Property
                if unmarshalErr := protojson.Unmarshal(result.Source(), &p); 
unmarshalErr != nil {
-                       s.metrics.totalErr.Inc(1, "aggregate")
-                       return nil, unmarshalErr
+                       s.l.Warn().Err(unmarshalErr).Msg("replay: failed to 
unmarshal property")
+                       continue
+               }

Review Comment:
   return error when `Unmarshal` failure. 



##########
banyand/metadata/schema/schemaserver/watcher.go:
##########
@@ -0,0 +1,101 @@
+// 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 schemaserver
+
+import (
+       "sync"
+
+       schemav1 
"github.com/apache/skywalking-banyandb/api/proto/banyandb/schema/v1"
+       "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+const watcherChannelSize = 512
+
+type watcherManager struct {
+       l        *logger.Logger
+       watchers map[uint64]chan *schemav1.WatchSchemasResponse
+       mu       sync.RWMutex
+       nextID   uint64
+}
+
+func newWatcherManager(l *logger.Logger) *watcherManager {
+       return &watcherManager{
+               l:        l,
+               watchers: make(map[uint64]chan *schemav1.WatchSchemasResponse),
+       }
+}
+
+// Subscribe registers a new watcher and returns its ID and event channel.
+func (wm *watcherManager) Subscribe() (uint64, <-chan 
*schemav1.WatchSchemasResponse) {
+       wm.mu.Lock()
+       defer wm.mu.Unlock()
+       wm.nextID++
+       id := wm.nextID
+       ch := make(chan *schemav1.WatchSchemasResponse, watcherChannelSize)
+       wm.watchers[id] = ch
+       wm.l.Debug().Uint64("watcherID", id).Int("totalWatchers", 
len(wm.watchers)).Msg("watcher subscribed")
+       return id, ch
+}
+
+// Unsubscribe removes a watcher and closes its channel.
+func (wm *watcherManager) Unsubscribe(id uint64) {
+       wm.mu.Lock()
+       defer wm.mu.Unlock()
+       if ch, ok := wm.watchers[id]; ok {
+               delete(wm.watchers, id)
+               close(ch)
+               wm.l.Debug().Uint64("watcherID", id).Int("totalWatchers", 
len(wm.watchers)).Msg("watcher unsubscribed")
+       }
+}
+
+// Broadcast sends an event to all watchers without blocking.
+func (wm *watcherManager) Broadcast(resp *schemav1.WatchSchemasResponse) {
+       wm.mu.RLock()
+       defer wm.mu.RUnlock()
+       wm.l.Debug().Stringer("eventType", resp.GetEventType()).
+               Str("propertyID", resp.GetProperty().GetId()).
+               Int("watcherCount", len(wm.watchers)).
+               Msg("broadcasting schema event")
+       for id, ch := range wm.watchers {
+               select {
+               case ch <- resp:
+               default:
+                       wm.l.Warn().Uint64("watcherID", id).
+                               Stringer("eventType", resp.GetEventType()).
+                               Str("propertyID", resp.GetProperty().GetId()).
+                               Msg("watcher channel full, dropping event")
+               }

Review Comment:
   fixed. 



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