google.golang.org/grpc@v1.72.2/internal/balancer/weight/weight.go (about) 1 /* 2 * 3 * Copyright 2025 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 weight contains utilities to manage endpoint weights. Weights are 20 // used by LB policies such as ringhash to distribute load across multiple 21 // endpoints. 22 package weight 23 24 import ( 25 "fmt" 26 27 "google.golang.org/grpc/resolver" 28 ) 29 30 // attributeKey is the type used as the key to store EndpointInfo in the 31 // Attributes field of resolver.Endpoint. 32 type attributeKey struct{} 33 34 // EndpointInfo will be stored in the Attributes field of Endpoints in order to 35 // use the ringhash balancer. 36 type EndpointInfo struct { 37 Weight uint32 38 } 39 40 // Equal allows the values to be compared by Attributes.Equal. 41 func (a EndpointInfo) Equal(o any) bool { 42 oa, ok := o.(EndpointInfo) 43 return ok && oa.Weight == a.Weight 44 } 45 46 // Set returns a copy of endpoint in which the Attributes field is updated with 47 // EndpointInfo. 48 func Set(endpoint resolver.Endpoint, epInfo EndpointInfo) resolver.Endpoint { 49 endpoint.Attributes = endpoint.Attributes.WithValue(attributeKey{}, epInfo) 50 return endpoint 51 } 52 53 // String returns a human-readable representation of EndpointInfo. 54 // This method is intended for logging, testing, and debugging purposes only. 55 // Do not rely on the output format, as it is not guaranteed to remain stable. 56 func (a EndpointInfo) String() string { 57 return fmt.Sprintf("Weight: %d", a.Weight) 58 } 59 60 // FromEndpoint returns the EndpointInfo stored in the Attributes field of an 61 // endpoint. It returns an empty EndpointInfo if attribute is not found. 62 func FromEndpoint(endpoint resolver.Endpoint) EndpointInfo { 63 v := endpoint.Attributes.Value(attributeKey{}) 64 ei, _ := v.(EndpointInfo) 65 return ei 66 }