github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/tunnel/pipe.go (about)

     1  package tunnel
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"time"
     7  )
     8  
     9  // NewPipe creates a pair of Streams connected using two channels.
    10  func NewPipe(id ConnID, sessionID string) (Stream, Stream) {
    11  	out := make(chan Message, 1)
    12  	in := make(chan Message, 1)
    13  	return &channelStream{
    14  			id:     id,
    15  			tag:    "SND",
    16  			sid:    sessionID,
    17  			recvCh: in,
    18  			sendCh: out,
    19  		}, &channelStream{
    20  			id:     id,
    21  			tag:    "RCV",
    22  			sid:    sessionID,
    23  			recvCh: out,
    24  			sendCh: in,
    25  		}
    26  }
    27  
    28  type channelStream struct {
    29  	id     ConnID
    30  	tag    string
    31  	sid    string
    32  	recvCh <-chan Message
    33  	sendCh chan<- Message
    34  }
    35  
    36  func (s channelStream) Tag() string {
    37  	return s.tag
    38  }
    39  
    40  func (s channelStream) ID() ConnID {
    41  	return s.id
    42  }
    43  
    44  func (s channelStream) Receive(ctx context.Context) (Message, error) {
    45  	select {
    46  	case <-ctx.Done():
    47  		return nil, ctx.Err()
    48  	case m, ok := <-s.recvCh:
    49  		if !ok {
    50  			return nil, io.EOF
    51  		}
    52  		return m, nil
    53  	}
    54  }
    55  
    56  func (s channelStream) Send(ctx context.Context, message Message) error {
    57  	select {
    58  	case <-ctx.Done():
    59  	case s.sendCh <- message:
    60  	}
    61  	return nil
    62  }
    63  
    64  func (s channelStream) CloseSend(_ context.Context) error {
    65  	close(s.sendCh)
    66  	return nil
    67  }
    68  
    69  func (s channelStream) PeerVersion() uint16 {
    70  	return 2
    71  }
    72  
    73  func (s channelStream) SessionID() string {
    74  	return s.sid
    75  }
    76  
    77  func (s channelStream) DialTimeout() time.Duration {
    78  	return time.Second
    79  }
    80  
    81  func (s channelStream) RoundtripLatency() time.Duration {
    82  	return time.Millisecond
    83  }