Repository: grpc/grpc-go
File: balancer/randomsubsetting/randomsubsetting.go (Go)

Code before:
			return fmt.Errorf("randomsubsetting: error switching to child of type %q: %v", lbCfg.ChildPolicy.Name, err)
		}
	}
	b.cfg = lbCfg

	return b.Balancer.UpdateClientConnState(balancer.ClientConnState{
		ResolverState:  b.prepareChildResolverState(s),
		BalancerConfig: b.cfg.ChildPolicy.Config,
	})
}

type endpointWithHash struct {
	hash uint64
	ep   resolver.Endpoint
}

// implements the subsetting algorithm,
// as described in A68: https://github.com/grpc/proposal/blob/master/A68-random-subsetting.md
func (b *subsettingBalancer) prepareChildResolverState(s balancer.ClientConnState) resolver.State {
	subsetSize := b.cfg.SubsetSize
	endpoints := s.ResolverState.Endpoints
	if len(endpoints) <= int(subsetSize) || subsetSize < 2 {
		return s.ResolverState
	}

	endpointSet := make([]endpointWithHash, len(endpoints))
	for i, endpoint := range endpoints {
		b.hashf.Write([]byte(endpoint.Addresses[0].String()))
		endpointSet[i] = endpointWithHash{
			hash: b.hashf.Sum64(),
			ep:   endpoint,
		}
	}

	slices.SortFunc(endpointSet, func(a, b endpointWithHash) int {
		if a.hash == b.hash {
			return 0
		}
		if a.hash < b.hash {
			return -1
		}
		return 1
	})

	if b.logger.V(2) {
		b.logger.Infof("Resulting subset: %v", endpointSet[:subsetSize])
	}

	// Convert back to resolver.Endpoints
	endpointSubset := make([]resolver.Endpoint, subsetSize)
	for i, endpoint := range endpointSet[:subsetSize] {

Review comment (suggestion):
The variable name `endpointSet` makes it look as though this is a set, which it is not. So, please rename this to something else. Either `hashedEndpoints` or `endpointsWithHash`.

Code after:
	lbCfg, ok := s.BalancerConfig.(*lbConfig)
	if !ok {
		b.logger.Warningf("Received config with unexpected type %T: %v", s.BalancerConfig, s.BalancerConfig)
		return balancer.ErrBadResolverState
	}

	// Build config for the gracefulswitch balancer. It is safe to ignore
	// JSON marshaling errors here, since the config was already validated
	// as part of ParseConfig().
	cfg := []map[string]any{{lbCfg.ChildPolicy.Name: lbCfg.ChildPolicy.Config}}
	cfgJSON, _ := json.Marshal(cfg)
	parsedCfg, err := gracefulswitch.ParseConfig(cfgJSON)
	if err != nil {
		return fmt.Errorf("randomsubsetting: error switching to child of type %q: %v", lbCfg.ChildPolicy.Name, err)
	}
	b.cfg = lbCfg
	endpoints := resolver.State{
		Endpoints:     b.calculateSubset(s.ResolverState.Endpoints),
		ServiceConfig: s.ResolverState.ServiceConfig,
		Attributes:    s.ResolverState.Attributes,
	}

	return b.Balancer.UpdateClientConnState(balancer.ClientConnState{
		ResolverState:  endpoints,
		BalancerConfig: parsedCfg,
	})
}

// calculateSubset implements the subsetting algorithm, as described in A68:
// https://github.com/grpc/proposal/blob/master/A68-random-subsetting.md#subsetting-algorithm
func (b *subsettingBalancer) calculateSubset(endpoints []resolver.Endpoint) []resolver.Endpoint {
	// A helper struct to hold an endpoint and its hash.
	type endpointWithHash struct {
		hash uint64
		ep   resolver.Endpoint
	}

	subsetSize := b.cfg.SubsetSize
	if len(endpoints) <= int(subsetSize) {
		return endpoints
	}

	hashedEndpoints := make([]endpointWithHash, len(endpoints))
	for i, endpoint := range endpoints {
		// For every endpoint in the list, compute a hash with previously
		// generated seed - A68.
		//
		// The xxhash package's Sum64() function does not allow setting a seed.
		// This means that we need to reset the digest with the seed for every
		// endpoint. Without this, an endpoint will not retain the same hash
		// across resolver updates.