github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/worker/pubsub/messagewriter.go (about)

     1  // Copyright 2017 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package pubsub
     5  
     6  import (
     7  	"time"
     8  
     9  	"github.com/juju/errors"
    10  
    11  	"github.com/juju/juju/api"
    12  	pubsubapi "github.com/juju/juju/api/pubsub"
    13  	"github.com/juju/juju/apiserver/params"
    14  )
    15  
    16  // MessageWriter defines the two methods called for message forwarding.
    17  type MessageWriter interface {
    18  	// ForwardMessage forwards the given message to the server.
    19  	ForwardMessage(*params.PubSubMessage) error
    20  	Close()
    21  }
    22  
    23  var dialOpts = api.DialOpts{
    24  	DialAddressInterval: 20 * time.Millisecond,
    25  	// If for some reason we are getting rate limited, there is a standard
    26  	// five second delay before we get the login response. Ideally we need
    27  	// to wait long enough for this response to get back to us.
    28  	// Ideally the apiserver wouldn't be rate limiting connections from other
    29  	// API servers, see bug #1733256.
    30  	Timeout:    10 * time.Second,
    31  	RetryDelay: 1 * time.Second,
    32  }
    33  
    34  // NewMessageWriter will connect to the remote defined by the info,
    35  // and return a MessageWriter.
    36  func NewMessageWriter(info *api.Info) (MessageWriter, error) {
    37  	conn, err := api.Open(info, dialOpts)
    38  	if err != nil {
    39  		return nil, errors.Trace(err)
    40  	}
    41  	a := pubsubapi.NewAPI(conn)
    42  	writer, err := a.OpenMessageWriter()
    43  	if err != nil {
    44  		conn.Close()
    45  		return nil, errors.Trace(err)
    46  	}
    47  	return &remoteConnection{connection: conn, MessageWriter: writer}, nil
    48  }
    49  
    50  // remoteConnection represents an api connection to another
    51  // API server for the purpose of forwarding pubsub messages.
    52  type remoteConnection struct {
    53  	connection api.Connection
    54  
    55  	pubsubapi.MessageWriter
    56  }
    57  
    58  func (r *remoteConnection) Close() {
    59  	r.MessageWriter.Close()
    60  	r.connection.Close()
    61  }