vitess.io/vitess@v0.16.2/go/vt/srvtopo/watch_srvvschema.go (about) 1 /* 2 Copyright 2021 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package srvtopo 18 19 import ( 20 "context" 21 "time" 22 23 "vitess.io/vitess/go/stats" 24 vschemapb "vitess.io/vitess/go/vt/proto/vschema" 25 "vitess.io/vitess/go/vt/topo" 26 ) 27 28 type SrvVSchemaWatcher struct { 29 rw *resilientWatcher 30 } 31 32 type cellName string 33 34 func (k cellName) String() string { 35 return string(k) 36 } 37 38 func NewSrvVSchemaWatcher(topoServer *topo.Server, counts *stats.CountersWithSingleLabel, cacheRefresh, cacheTTL time.Duration) *SrvVSchemaWatcher { 39 watch := func(entry *watchEntry) { 40 key := entry.key.(cellName) 41 ctx, cancel := context.WithCancel(context.Background()) 42 defer cancel() 43 44 current, changes, err := topoServer.WatchSrvVSchema(ctx, key.String()) 45 if err != nil { 46 entry.update(nil, err, true) 47 return 48 } 49 50 entry.update(current.Value, current.Err, true) 51 if current.Err != nil { 52 return 53 } 54 55 defer cancel() 56 for c := range changes { 57 entry.update(c.Value, c.Err, false) 58 if c.Err != nil { 59 return 60 } 61 } 62 } 63 64 rw := &resilientWatcher{ 65 watcher: watch, 66 counts: counts, 67 cacheRefreshInterval: cacheRefresh, 68 cacheTTL: cacheTTL, 69 entries: make(map[string]*watchEntry), 70 } 71 72 return &SrvVSchemaWatcher{rw} 73 } 74 75 func (w *SrvVSchemaWatcher) GetSrvVSchema(ctx context.Context, cell string) (*vschemapb.SrvVSchema, error) { 76 v, err := w.rw.getValue(ctx, cellName(cell)) 77 vschema, _ := v.(*vschemapb.SrvVSchema) 78 return vschema, err 79 } 80 81 func (w *SrvVSchemaWatcher) WatchSrvVSchema(ctx context.Context, cell string, callback func(*vschemapb.SrvVSchema, error) bool) { 82 entry := w.rw.getEntry(cellName(cell)) 83 entry.addListener(ctx, func(v any, err error) bool { 84 vschema, _ := v.(*vschemapb.SrvVSchema) 85 return callback(vschema, err) 86 }) 87 }