1 /* 2 * 3 * Copyright 2019 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 // Package weightedroundrobin provides an implementation of the weighted round 20 // robin LB policy, as defined in [gRFC A58]. 21 // 22 // # Experimental 23 // 24 // Notice: This package is EXPERIMENTAL and may be changed or removed in a 25 // later release. 26 // 27 // [gRFC A58]: https://github.com/grpc/proposal/blob/master/A58-client-side-weighted-round-robin-lb-policy.md 28 package weightedroundrobin 29 30 import ( 31 "fmt" 32 33 "google.golang.org/grpc/resolver" 34 ) 35 36 // attributeKey is the type used as the key to store AddrInfo in the 37 // BalancerAttributes field of resolver.Address. 38 type attributeKey struct{} 39 40 // AddrInfo will be stored in the BalancerAttributes field of Address in order 41 // to use weighted roundrobin balancer. 42 type AddrInfo struct { 43 Weight uint32 44 } 45 46 // Equal allows the values to be compared by Attributes.Equal. 47 func (a AddrInfo) Equal(o any) bool { 48 oa, ok := o.(AddrInfo) 49 return ok && oa.Weight == a.Weight 50 } 51 52 // SetAddrInfo returns a copy of addr in which the BalancerAttributes field is 53 // updated with addrInfo. 54 func SetAddrInfo(addr resolver.Address, addrInfo AddrInfo) resolver.Address { 55 addr.BalancerAttributes = addr.BalancerAttributes.WithValue(attributeKey{}, addrInfo) 56 return addr 57 } 58 59 // GetAddrInfo returns the AddrInfo stored in the BalancerAttributes field of 60 // addr. 61 func GetAddrInfo(addr resolver.Address) AddrInfo { 62 v := addr.BalancerAttributes.Value(attributeKey{}) 63 ai, _ := v.(AddrInfo) 64 return ai 65 } 66 67 func (a AddrInfo) String() string { 68 return fmt.Sprintf("Weight: %d", a.Weight) 69 } 70