google.golang.org/grpc@v1.74.2/internal/ringhash/ringhash.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 ringhash (internal) contains functions and types that need to be
    20  // shared by the ring hash balancer and other gRPC code (such as xDS)
    21  // without being exported.
    22  package ringhash
    23  
    24  import (
    25  	"context"
    26  
    27  	"google.golang.org/grpc/serviceconfig"
    28  )
    29  
    30  // LBConfig is the balancer config for ring_hash balancer.
    31  type LBConfig struct {
    32  	serviceconfig.LoadBalancingConfig `json:"-"`
    33  
    34  	MinRingSize       uint64 `json:"minRingSize,omitempty"`
    35  	MaxRingSize       uint64 `json:"maxRingSize,omitempty"`
    36  	RequestHashHeader string `json:"requestHashHeader,omitempty"`
    37  }
    38  
    39  // xdsHashKey is the type used as the key to store request hash in the context
    40  // used when combining the Ring Hash load balancing policy with xDS.
    41  type xdsHashKey struct{}
    42  
    43  // XDSRequestHash returns the request hash in the context and true if it was set
    44  // from the xDS config selector. If the xDS config selector has not set the hash,
    45  // it returns 0 and false.
    46  func XDSRequestHash(ctx context.Context) (uint64, bool) {
    47  	requestHash := ctx.Value(xdsHashKey{})
    48  	if requestHash == nil {
    49  		return 0, false
    50  	}
    51  	return requestHash.(uint64), true
    52  }
    53  
    54  // SetXDSRequestHash adds the request hash to the context for use in Ring Hash
    55  // Load Balancing using xDS route hash_policy.
    56  func SetXDSRequestHash(ctx context.Context, requestHash uint64) context.Context {
    57  	return context.WithValue(ctx, xdsHashKey{}, requestHash)
    58  }