go.uber.org/yarpc@v1.72.1/peer/pendingheap/list.go (about)

     1  // Copyright (c) 2022 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package pendingheap
    22  
    23  import (
    24  	"context"
    25  	"math/rand"
    26  	"time"
    27  
    28  	"go.uber.org/yarpc/api/peer"
    29  	"go.uber.org/yarpc/api/transport"
    30  	"go.uber.org/yarpc/api/x/introspection"
    31  	"go.uber.org/yarpc/peer/abstractlist"
    32  	"go.uber.org/zap"
    33  )
    34  
    35  type listConfig struct {
    36  	capacity int
    37  	shuffle  bool
    38  	failFast bool
    39  	seed     int64
    40  	nextRand func(int) int
    41  	logger   *zap.Logger
    42  }
    43  
    44  var defaultListConfig = listConfig{
    45  	capacity: 10,
    46  	shuffle:  true,
    47  	seed:     time.Now().UnixNano(),
    48  }
    49  
    50  // ListOption customizes the behavior of a pending requests peer heap.
    51  type ListOption func(*listConfig)
    52  
    53  // Capacity specifies the default capacity of the underlying
    54  // data structures for this list.
    55  //
    56  // Defaults to 10.
    57  func Capacity(capacity int) ListOption {
    58  	return func(c *listConfig) {
    59  		c.capacity = capacity
    60  	}
    61  }
    62  
    63  // Seed specifies the random seed to use for shuffling peers.
    64  //
    65  // Defaults to time in nanoseconds.
    66  func Seed(seed int64) ListOption {
    67  	return func(c *listConfig) {
    68  		c.seed = seed
    69  	}
    70  }
    71  
    72  // Logger provides an optional logger for the list.
    73  func Logger(logger *zap.Logger) ListOption {
    74  	return func(c *listConfig) {
    75  		c.logger = logger
    76  	}
    77  }
    78  
    79  // FailFast indicates that the peer list should not wait for a peer to become
    80  // available when choosing a peer.
    81  //
    82  // This option is preferrable when the better failure mode is to retry from the
    83  // origin, since another proxy instance might already have a connection.
    84  func FailFast() ListOption {
    85  	return func(c *listConfig) {
    86  		c.failFast = true
    87  	}
    88  }
    89  
    90  // New creates a new pending heap.
    91  func New(transport peer.Transport, opts ...ListOption) *List {
    92  	cfg := defaultListConfig
    93  	for _, o := range opts {
    94  		o(&cfg)
    95  	}
    96  
    97  	plOpts := []abstractlist.Option{
    98  		abstractlist.Capacity(cfg.capacity),
    99  		abstractlist.Logger(cfg.logger),
   100  	}
   101  	if !cfg.shuffle {
   102  		plOpts = append(plOpts, abstractlist.NoShuffle())
   103  	}
   104  	if cfg.failFast {
   105  		plOpts = append(plOpts, abstractlist.FailFast())
   106  	}
   107  
   108  	nextRandFn := nextRand(cfg.seed)
   109  	if cfg.nextRand != nil {
   110  		// only true in tests
   111  		nextRandFn = cfg.nextRand
   112  	}
   113  
   114  	return &List{
   115  		list: abstractlist.New(
   116  			"fewest-pending-requests",
   117  			transport,
   118  			newHeap(nextRandFn),
   119  			plOpts...,
   120  		),
   121  	}
   122  }
   123  
   124  // List is a peer list which rotates which peers are to be selected in a circle
   125  type List struct {
   126  	list *abstractlist.List
   127  }
   128  
   129  // nextRand is a convenience function for creating a new rand.Rand from a given
   130  // seed.
   131  func nextRand(seed int64) func(int) int {
   132  	r := rand.New(rand.NewSource(seed))
   133  
   134  	return func(numPeers int) int {
   135  		if numPeers == 0 {
   136  			return 0
   137  		}
   138  		return r.Intn(numPeers)
   139  	}
   140  }
   141  
   142  // Start causes the peer list to start.
   143  //
   144  // Starting will retain all peers that have been added but not removed
   145  // the first time it is called.
   146  //
   147  // Start may be called any number of times and in any order in relation to Stop
   148  // but will only cause the list to start the first time, and only if it has not
   149  // already been stopped.
   150  func (l *List) Start() error {
   151  	return l.list.Start()
   152  }
   153  
   154  // Stop causes the peer list to stop.
   155  //
   156  // Stopping will release all retained peers to the underlying transport.
   157  //
   158  // Stop may be called any number of times and in order in relation to Start but
   159  // will only cause the list to stop the first time, and only if it has
   160  // previously been started.
   161  func (l *List) Stop() error {
   162  	return l.list.Stop()
   163  }
   164  
   165  // IsRunning returns whether the list has started and not yet stopped.
   166  func (l *List) IsRunning() bool {
   167  	return l.list.IsRunning()
   168  }
   169  
   170  // Choose returns a peer, suitable for sending a request.
   171  //
   172  // The peer is not guaranteed to be connected and available, but the peer list
   173  // makes every attempt to ensure this and minimize the probability that a
   174  // chosen peer will fail to carry a request.
   175  func (l *List) Choose(ctx context.Context, req *transport.Request) (peer peer.Peer, onFinish func(error), err error) {
   176  	return l.list.Choose(ctx, req)
   177  }
   178  
   179  // Update may add and remove logical peers in the list.
   180  //
   181  // The peer list uses a transport to obtain a physical peer for each logical
   182  // peer.
   183  // The transport is responsible for informing the peer list whether the peer is
   184  // available or unavailable, but cannot guarantee that the peer will still be
   185  // available after it is chosen.
   186  func (l *List) Update(updates peer.ListUpdates) error {
   187  	return l.list.Update(updates)
   188  }
   189  
   190  // NotifyStatusChanged forwards a status change notification to an individual
   191  // peer in the list.
   192  //
   193  // This satisfies the peer.Subscriber interface and should only be used to
   194  // send notifications in tests.
   195  // The list's RetainPeer and ReleasePeer methods deal with an individual
   196  // peer.Subscriber instance for each peer in the list, avoiding a map lookup.
   197  func (l *List) NotifyStatusChanged(pid peer.Identifier) {
   198  	l.list.NotifyStatusChanged(pid)
   199  }
   200  
   201  // Introspect reveals information about the list to the internal YARPC
   202  // introspection system.
   203  func (l *List) Introspect() introspection.ChooserStatus {
   204  	return l.list.Introspect()
   205  }
   206  
   207  // Peers produces a slice of all retained peers.
   208  func (l *List) Peers() []peer.StatusPeer {
   209  	return l.list.Peers()
   210  }