go.uber.org/yarpc@v1.72.1/x/yarpctest/handler_stream.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 yarpctest
    22  
    23  import (
    24  	"context"
    25  	"errors"
    26  	"sync"
    27  	"testing"
    28  
    29  	"github.com/stretchr/testify/require"
    30  	"go.uber.org/atomic"
    31  	"go.uber.org/multierr"
    32  	"go.uber.org/yarpc/api/transport"
    33  	"go.uber.org/yarpc/x/yarpctest/api"
    34  )
    35  
    36  // EchoStreamHandler is a Bidirectional Stream Handler that will echo any
    37  // request that is sent to it.
    38  func EchoStreamHandler() api.ProcOption {
    39  	return &echoStreamHandler{}
    40  }
    41  
    42  type echoStreamHandler struct {
    43  	api.SafeTestingTBOnStart
    44  
    45  	wg      sync.WaitGroup
    46  	stopped atomic.Bool
    47  }
    48  
    49  func (h *echoStreamHandler) ApplyProc(opts *api.ProcOpts) {
    50  	opts.HandlerSpec = transport.NewStreamHandlerSpec(h)
    51  }
    52  
    53  func (h *echoStreamHandler) Stop(testing.TB) error {
    54  	h.stopped.Store(true)
    55  	h.wg.Wait()
    56  	return nil
    57  }
    58  
    59  func (h *echoStreamHandler) HandleStream(s *transport.ServerStream) error {
    60  	if h.stopped.Load() {
    61  		return errors.New("closed")
    62  	}
    63  	h.wg.Add(1)
    64  	defer h.wg.Done()
    65  	for {
    66  		msg, err := s.ReceiveMessage(context.Background())
    67  		if err != nil {
    68  			return err
    69  		}
    70  		err = s.SendMessage(context.Background(), msg)
    71  		if err != nil {
    72  			return err
    73  		}
    74  	}
    75  }
    76  
    77  // OrderedStreamHandler is a bidirectional stream handler that can apply stream
    78  // actions in a specified order.
    79  func OrderedStreamHandler(actions ...api.ServerStreamAction) api.ProcOption {
    80  	return &orderedStreamHandler{
    81  		actions: actions,
    82  	}
    83  }
    84  
    85  type orderedStreamHandler struct {
    86  	actions []api.ServerStreamAction
    87  
    88  	wg      sync.WaitGroup
    89  	stopped atomic.Bool
    90  	t       testing.TB
    91  }
    92  
    93  // ApplyProc implements ProcOption.
    94  func (o *orderedStreamHandler) ApplyProc(opts *api.ProcOpts) {
    95  	opts.HandlerSpec = transport.NewStreamHandlerSpec(o)
    96  }
    97  
    98  // Start sets the TestingT to use for assertions.
    99  func (o *orderedStreamHandler) Start(t testing.TB) error {
   100  	o.t = t
   101  
   102  	var err error
   103  	for _, action := range o.actions {
   104  		err = multierr.Append(err, action.Start(t))
   105  	}
   106  	return err
   107  }
   108  
   109  // Stop cleans up the handler, waiting until all streams have ended.
   110  func (o *orderedStreamHandler) Stop(t testing.TB) error {
   111  	var err error
   112  	for _, action := range o.actions {
   113  		err = multierr.Append(err, action.Stop(t))
   114  	}
   115  	o.stopped.Store(true)
   116  	o.wg.Wait()
   117  	return err
   118  }
   119  
   120  // HandleStream handles a stream request.
   121  func (o *orderedStreamHandler) HandleStream(s *transport.ServerStream) error {
   122  	if o.stopped.Load() {
   123  		return errors.New("closed")
   124  	}
   125  	o.wg.Add(1)
   126  	defer o.wg.Done()
   127  
   128  	for i, action := range o.actions {
   129  		if err := action.ApplyServerStream(s); err != nil {
   130  			require.Equal(o.t, i+1, len(o.actions), "exited before all actions were run.")
   131  			return err
   132  		}
   133  	}
   134  	return nil
   135  }
   136  
   137  // SERVER-ONLY ACTIONS
   138  
   139  // StreamHandlerError is an action to return an error from a ServerStream
   140  // handler.
   141  func StreamHandlerError(err error) api.ServerStreamAction {
   142  	return api.ServerStreamActionFunc(func(c *transport.ServerStream) error {
   143  		return err
   144  	})
   145  }
   146  
   147  // StreamSendHeaders is an action to send stream headers.
   148  func StreamSendHeaders(headers map[string]string) api.ServerStreamAction {
   149  	return api.ServerStreamActionFunc(func(c *transport.ServerStream) error {
   150  		return c.SendHeaders(transport.HeadersFromMap(headers))
   151  	})
   152  }