go.uber.org/yarpc@v1.72.1/peer/roundrobin/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 roundrobin
    22  
    23  import (
    24  	"context"
    25  	"time"
    26  
    27  	"go.uber.org/yarpc/api/peer"
    28  	"go.uber.org/yarpc/api/transport"
    29  	"go.uber.org/yarpc/api/x/introspection"
    30  	"go.uber.org/yarpc/peer/abstractlist"
    31  	"go.uber.org/zap"
    32  )
    33  
    34  type listConfig struct {
    35  	capacity             int
    36  	shuffle              bool
    37  	failFast             bool
    38  	defaultChooseTimeout *time.Duration
    39  	seed                 int64
    40  	logger               *zap.Logger
    41  }
    42  
    43  var defaultListConfig = listConfig{
    44  	capacity: 10,
    45  	shuffle:  true,
    46  	seed:     time.Now().UnixNano(),
    47  }
    48  
    49  // ListOption customizes the behavior of a roundrobin list.
    50  type ListOption func(*listConfig)
    51  
    52  // Capacity specifies the default capacity of the underlying
    53  // data structures for this list.
    54  //
    55  // Defaults to 10.
    56  func Capacity(capacity int) ListOption {
    57  	return func(c *listConfig) {
    58  		c.capacity = capacity
    59  	}
    60  }
    61  
    62  // FailFast indicates that the peer list should not wait for a peer to become
    63  // available when choosing a peer.
    64  //
    65  // This option is preferrable when the better failure mode is to retry from the
    66  // origin, since another proxy instance might already have a connection.
    67  func FailFast() ListOption {
    68  	return func(c *listConfig) {
    69  		c.failFast = true
    70  	}
    71  }
    72  
    73  // Logger specifies a logger.
    74  func Logger(logger *zap.Logger) ListOption {
    75  	return func(c *listConfig) {
    76  		c.logger = logger
    77  	}
    78  }
    79  
    80  // DefaultChooseTimeout specifies the default timeout to add to 'Choose' calls
    81  // without context deadlines. This prevents long-lived streams from setting
    82  // calling deadlines.
    83  //
    84  // Defaults to 500ms.
    85  func DefaultChooseTimeout(timeout time.Duration) ListOption {
    86  	return func(c *listConfig) {
    87  		c.defaultChooseTimeout = &timeout
    88  	}
    89  }
    90  
    91  // New creates a new round robin peer list.
    92  func New(transport peer.Transport, opts ...ListOption) *List {
    93  	cfg := defaultListConfig
    94  	for _, o := range opts {
    95  		o(&cfg)
    96  	}
    97  
    98  	plOpts := []abstractlist.Option{
    99  		abstractlist.Capacity(cfg.capacity),
   100  		abstractlist.Seed(cfg.seed),
   101  	}
   102  	if cfg.logger != nil {
   103  		plOpts = append(plOpts, abstractlist.Logger(cfg.logger))
   104  	}
   105  	if !cfg.shuffle {
   106  		plOpts = append(plOpts, abstractlist.NoShuffle())
   107  	}
   108  	if cfg.failFast {
   109  		plOpts = append(plOpts, abstractlist.FailFast())
   110  	}
   111  	if cfg.defaultChooseTimeout != nil {
   112  		plOpts = append(plOpts, abstractlist.DefaultChooseTimeout(*cfg.defaultChooseTimeout))
   113  	}
   114  
   115  	return &List{
   116  		list: abstractlist.New(
   117  			"round-robin",
   118  			transport,
   119  			NewImplementation(),
   120  			plOpts...,
   121  		),
   122  	}
   123  }
   124  
   125  var _ peer.List = (*List)(nil)
   126  var _ peer.Chooser = (*List)(nil)
   127  var _ introspection.IntrospectableChooser = (*List)(nil)
   128  
   129  // List is a PeerList which rotates which peers are to be selected in a circle
   130  type List struct {
   131  	list *abstractlist.List
   132  }
   133  
   134  // Start causes the peer list to start.
   135  //
   136  // Starting will retain all peers that have been added but not removed
   137  // the first time it is called.
   138  //
   139  // Start may be called any number of times and in any order in relation to Stop
   140  // but will only cause the list to start the first time, and only if it has not
   141  // already been stopped.
   142  func (l *List) Start() error {
   143  	return l.list.Start()
   144  }
   145  
   146  // Stop causes the peer list to stop.
   147  //
   148  // Stopping will release all retained peers to the underlying transport.
   149  //
   150  // Stop may be called any number of times and in order in relation to Start but
   151  // will only cause the list to stop the first time, and only if it has
   152  // previously been started.
   153  func (l *List) Stop() error {
   154  	return l.list.Stop()
   155  }
   156  
   157  // IsRunning returns whether the list has started and not yet stopped.
   158  func (l *List) IsRunning() bool {
   159  	return l.list.IsRunning()
   160  }
   161  
   162  // Choose returns a peer, suitable for sending a request.
   163  //
   164  // The peer is not guaranteed to be connected and available, but the peer list
   165  // makes every attempt to ensure this and minimize the probability that a
   166  // chosen peer will fail to carry a request.
   167  func (l *List) Choose(ctx context.Context, req *transport.Request) (peer peer.Peer, onFinish func(error), err error) {
   168  	return l.list.Choose(ctx, req)
   169  }
   170  
   171  // Update may add and remove logical peers in the list.
   172  //
   173  // The peer list uses a transport to obtain a physical peer for each logical
   174  // peer.
   175  // The transport is responsible for informing the peer list whether the peer is
   176  // available or unavailable, but cannot guarantee that the peer will still be
   177  // available after it is chosen.
   178  func (l *List) Update(updates peer.ListUpdates) error {
   179  	return l.list.Update(updates)
   180  }
   181  
   182  // NotifyStatusChanged forwards a status change notification to an individual
   183  // peer in the list.
   184  //
   185  // This satisfies the peer.Subscriber interface and should only be used to
   186  // send notifications in tests.
   187  // The list's RetainPeer and ReleasePeer methods deal with an individual
   188  // peer.Subscriber instance for each peer in the list, avoiding a map lookup.
   189  func (l *List) NotifyStatusChanged(pid peer.Identifier) {
   190  	l.list.NotifyStatusChanged(pid)
   191  }
   192  
   193  // Introspect reveals information about the list to the internal YARPC
   194  // introspection system.
   195  func (l *List) Introspect() introspection.ChooserStatus {
   196  	return l.list.Introspect()
   197  }
   198  
   199  // Peers produces a slice of all retained peers.
   200  func (l *List) Peers() []peer.StatusPeer {
   201  	return l.list.Peers()
   202  }