github.com/iron-io/functions@v0.0.0-20180820112432-d59d7d1c40b2/api/runner/protocol/factory.go (about)

     1  package protocol
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"io"
     7  
     8  	"github.com/iron-io/functions/api/models"
     9  	"github.com/iron-io/functions/api/runner/task"
    10  )
    11  
    12  var errInvalidProtocol = errors.New("Invalid Protocol")
    13  
    14  // ContainerIO defines the interface used to talk to a hot function.
    15  // Internally, a protocol must know when to alternate between stdin and stdout.
    16  // It returns any protocol error, if present.
    17  type ContainerIO interface {
    18  	IsStreamable() bool
    19  	Dispatch(ctx context.Context, t task.Request) error
    20  }
    21  
    22  // Protocol defines all protocols that operates a ContainerIO.
    23  type Protocol string
    24  
    25  // hot function protocols
    26  const (
    27  	Default Protocol = models.FormatDefault
    28  	HTTP    Protocol = models.FormatHTTP
    29  	Empty   Protocol = ""
    30  )
    31  
    32  // New creates a valid protocol handler from a I/O pipe representing containers
    33  // stdin/stdout.
    34  func New(p Protocol, in io.Writer, out io.Reader) (ContainerIO, error) {
    35  	switch p {
    36  	case HTTP:
    37  		return &HTTPProtocol{in, out}, nil
    38  	case Default, Empty:
    39  		return &DefaultProtocol{}, nil
    40  	default:
    41  		return nil, errInvalidProtocol
    42  	}
    43  }
    44  
    45  // IsStreamable says whether the given protocol can be used for streaming into
    46  // hot functions.
    47  func IsStreamable(p string) (bool, error) {
    48  	proto, err := New(Protocol(p), nil, nil)
    49  	if err != nil {
    50  		return false, err
    51  	}
    52  	return proto.IsStreamable(), nil
    53  }