github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/clusters/registration.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 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 18 package clusters 19 20 import ( 21 "github.com/aacfactory/fns/commons/bytex" 22 "github.com/aacfactory/fns/commons/versions" 23 "github.com/aacfactory/fns/services" 24 "sync" 25 ) 26 27 type Registration struct { 28 values sync.Map 29 } 30 31 func (r *Registration) Add(endpoint *Endpoint) { 32 key := endpoint.Name() 33 var eps *Endpoints 34 exist, has := r.values.Load(key) 35 if has { 36 eps = exist.(*Endpoints) 37 } else { 38 eps = &Endpoints{ 39 values: nil, 40 length: 0, 41 lock: sync.RWMutex{}, 42 } 43 r.values.Store(key, eps) 44 } 45 eps.Add(endpoint) 46 } 47 48 func (r *Registration) Remove(name string, id string) { 49 exist, has := r.values.Load(name) 50 if !has { 51 return 52 } 53 eps := exist.(*Endpoints) 54 eps.Remove(bytex.FromString(id)) 55 } 56 57 func (r *Registration) Get(name []byte, id []byte) *Endpoint { 58 key := bytex.ToString(name) 59 exist, has := r.values.Load(key) 60 if !has { 61 return nil 62 } 63 eps := exist.(*Endpoints) 64 return eps.Get(id) 65 } 66 67 func (r *Registration) Range(name []byte, interval versions.Interval) *Endpoint { 68 key := bytex.ToString(name) 69 exist, has := r.values.Load(key) 70 if !has { 71 return nil 72 } 73 eps := exist.(*Endpoints) 74 return eps.Range(interval) 75 } 76 77 func (r *Registration) MaxOne(name []byte) *Endpoint { 78 key := bytex.ToString(name) 79 exist, has := r.values.Load(key) 80 if !has { 81 return nil 82 } 83 eps := exist.(*Endpoints) 84 return eps.MaxOne() 85 } 86 87 func (r *Registration) Infos() (v services.EndpointInfos) { 88 r.values.Range(func(key, value any) bool { 89 eps := value.(*Endpoints) 90 vv := eps.Infos() 91 if len(vv) > 0 { 92 v = append(v, vv...) 93 } 94 return true 95 }) 96 return 97 }