Documentation
¶
Index ¶
- Constants
- Variables
- func AuthError(id *id.ID) error
- func GetAddressFromContext(ctx context.Context) (address string, port string, err error)
- func IsAuthError(err error) bool
- func StreamingContext() (context.Context, context.CancelFunc)
- func StreamingContextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)
- func UnpackAuthenticatedContext(ctx context.Context) (*pb.AuthenticatedMessage, error)
- type Auth
- type Circuit
- func (c *Circuit) AddHost(newHost *Host)
- func (c *Circuit) GetHostAtIndex(index int) *Host
- func (c *Circuit) GetLastNode() *id.ID
- func (c *Circuit) GetNextNode(from *id.ID) *id.ID
- func (c *Circuit) GetNodeAtIndex(index int) *id.ID
- func (c *Circuit) GetNodeLocation(node *id.ID) int
- func (c *Circuit) GetOrdering() []*Circuit
- func (c *Circuit) GetPrevNode(from *id.ID) *id.ID
- func (c *Circuit) IsFirstNode(node *id.ID) bool
- func (c *Circuit) IsLastNode(node *id.ID) bool
- func (c *Circuit) Len() int
- type Connection
- type ConnectionType
- type Host
- func (h *Host) Connect() error
- func (h *Host) Connected() (bool, uint64)
- func (h *Host) Disconnect()
- func (h *Host) GetAddress() string
- func (h *Host) GetId() *id.ID
- func (h *Host) GetMessagingContext() (context.Context, context.CancelFunc)
- func (h *Host) GetMessagingContextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)
- func (h *Host) GetMetrics() *Metric
- func (h *Host) GetPubKey() *rsa.PublicKey
- func (h *Host) GetRemoteCertificate() (*x509.Certificate, error)
- func (h *Host) IsOnline() (time.Duration, bool)
- func (h *Host) IsWeb() bool
- func (h *Host) SetMetricsTesting(m *Metric, face interface{})
- func (h *Host) SetTestPublicKey(key *rsa.PublicKey, t interface{})
- func (h *Host) SetWindowSize(size int32)
- func (h *Host) String() string
- func (h *Host) StringVerbose() string
- func (h *Host) UpdateAddress(address string)
- type HostParams
- type Manager
- func (m *Manager) AddHost(hid *id.ID, address string, cert []byte, params HostParams) (host *Host, err error)
- func (m *Manager) DisconnectAll()
- func (m *Manager) GetHost(hostId *id.ID) (*Host, bool)
- func (m *Manager) RemoveHost(hid *id.ID)
- func (m *Manager) StartConnectionReport()
- func (m *Manager) String() string
- type Metric
- type ProtoComms
- func (c *ProtoComms) AuthenticatedReceiver(msg *pb.AuthenticatedMessage, ctx context.Context) (*Auth, error)
- func (c *ProtoComms) DisableAuth()
- func (c *ProtoComms) GenerateToken() ([]byte, error)
- func (c *ProtoComms) GetId() *id.ID
- func (c *ProtoComms) GetPrivateKey() *rsa.PrivateKey
- func (c *ProtoComms) GetServer() *grpc.Server
- func (c *ProtoComms) PackAuthenticatedContext(host *Host, ctx context.Context) context.Context
- func (c *ProtoComms) PackAuthenticatedMessage(msg proto.Message, host *Host, enableSignature bool) (*pb.AuthenticatedMessage, error)
- func (c *ProtoComms) Restart() error
- func (c *ProtoComms) Send(host *Host, f func(conn Connection) (*any.Any, error)) (result *any.Any, err error)
- func (c *ProtoComms) Serve()
- func (c *ProtoComms) ServeHttps(keyPair tls.Certificate) error
- func (c *ProtoComms) ServeWithWeb()
- func (c *ProtoComms) Shutdown()
- func (c *ProtoComms) Stream(host *Host, f func(conn Connection) (interface{}, error)) (client interface{}, err error)
- func (c *ProtoComms) String() string
- func (c *ProtoComms) ValidateToken(msg *pb.AuthenticatedMessage) (err error)
- type WebConnParam
Constants ¶
const MaxWindowSize = math.MaxInt32
MaxWindowSize 4 MB
const ProxyError = "unable to connect to target host"
ProxyError is part of the error reported by gateway when host cannot be reached. Its frequency is being tracked so that it can be excluded from the host pool in the layer after a set number of occurrences.
const TooManyProxyError = "too many proxy failures to target host"
TooManyProxyError is the error returned instead of ProxyError, when it occurs too many times.
Variables ¶
var KaEnforcement = keepalive.EnforcementPolicy{ MinTime: 3 * time.Second, PermitWithoutStream: true, }
KaEnforcement are keepalive enforcement options for servers
var KaOpts = keepalive.ServerParameters{ MaxConnectionIdle: 60 * time.Second, MaxConnectionAge: 1 * time.Hour, MaxConnectionAgeGrace: 1 * time.Minute, Time: 5 * time.Second, Timeout: 60 * time.Second, }
KaOpts are Keepalive options for servers TODO: Set these via config
var MaxConcurrentStreams = uint32(250000)
MaxConcurrentStreams is the number of server-side streams to allow open
var TestingOnlyDisableTLS = false
TestingOnlyDisableTLS is the variable set for testing which allows for the disabled TLS code-path. Production code-path will only function with TLS enabled.
var TestingOnlyInsecureTLSVerify = false
Functions ¶
func GetAddressFromContext ¶
GetAddressFromContext obtains address:port from the context of an incoming communication
func IsAuthError ¶
IsAuthError returns true if the passed error is a valid auth error
func StreamingContext ¶
func StreamingContext() (context.Context, context.CancelFunc)
StreamingContext creates a context object with the default context for all client streaming messages. This is primarily used to allow a cancel option for clients and is suitable for unary streaming.
func StreamingContextWithTimeout ¶
StreamingContextWithTimeout creates a context object with the default context given a timout streaming messages. This is primarily used to allow a cancel option for clients and is suitable for unary streaming.
func UnpackAuthenticatedContext ¶
func UnpackAuthenticatedContext(ctx context.Context) (*pb.AuthenticatedMessage, error)
Returns authentication packed into a context
Types ¶
type Auth ¶
type Auth struct { // Indicates whether authentication was successful IsAuthenticated bool // The information about the Host that sent the authenticated communication Sender *Host // reason it isn't authenticated if authentication fails Reason string // The IP Address (excluding port) for the sending host IpAddress string }
Auth represents an authorization state for a message or host
type Circuit ¶
type Circuit struct {
// contains filtered or unexported fields
}
func NewCircuit ¶
New makes a list of node addresses for use. It finds the passed "myId" and denotes it internally for use with utility functions. The nodeID are copied instead of linked to ensure any modification of them does not change the Circuit structure. Will panic if the length of the passed list is zero.
func (*Circuit) AddHost ¶
SetHosts takes a list of hosts and copies them into the list of hosts in the circuit object
func (*Circuit) GetHostAtIndex ¶
GetHostAtIndex: Gets host at requested index. Panics if index is outside of the range of the list
func (*Circuit) GetLastNode ¶
Get the last node in the circuit, will panic if the circuit has nil as a node
func (*Circuit) GetNextNode ¶
GetNextNode gets the node following the passed node in the list. It wraps around to the beginning of the list if the passed node is the last node.
func (*Circuit) GetNodeAtIndex ¶
GetNodeAtIndex returns the node at the given index. Panics if the index does not exist within the circuit
func (*Circuit) GetNodeLocation ¶
GetNodeLocation returns the location of the passed node in the list. Returns -1 if the node is not in the list
func (*Circuit) GetOrdering ¶
GetOrdering returns a slice of Circuits with each one having a different shifted ordering.
func (*Circuit) GetPrevNode ¶
GetNextNode gets the node preceding the passed node in the list. It wraps around to the end of the list if the passed node is the first node.
func (*Circuit) IsFirstNode ¶
IsFirstNode returns true if the passed node is the first node, false otherwise
func (*Circuit) IsLastNode ¶
IsLastNode returns true if the passed node is the last node, false otherwise
type Connection ¶
type Connection interface { // GetWebConn returns the grpcweb ClientConn for use in browsers. // It panics if called on a grpc client. GetWebConn() *grpcweb.ClientConn // GetGrpcConn returns the grpc ClientConn for standard use. // It panics if called on a grpcweb client. GetGrpcConn() *grpc.ClientConn // Connect initiates a connection with the host using connection logic // supplied by the underlying class. Connect() error // IsWeb returns true if the connection uses grpcweb IsWeb() bool // Close closes the underlying connection Close() error IsOnline() (time.Duration, bool) GetRemoteCertificate() (*x509.Certificate, error) // contains filtered or unexported methods }
Connection is an interface designed to sit between hosts and connections to allow use of grpcweb clients.
type ConnectionType ¶
type ConnectionType uint8
ConnectionType is intended to act as an enum for different methods of host connection
const ( Grpc ConnectionType = iota Web )
Enumerate the extant connection methods
func GetDefaultConnectionType ¶
func GetDefaultConnectionType() ConnectionType
GetDefaultConnectionType returns Grpc as the default connection type when compiling for all architectures except WebAssembly.
func (ConnectionType) String ¶
func (ct ConnectionType) String() string
Stringify connection constants
type Host ¶
type Host struct {
// contains filtered or unexported fields
}
Host information used to describe a remote connection
func (*Host) Connect ¶
Connect allows manual connection to the host if it does not have a valid connection
func (*Host) Connected ¶
Connected checks if the given Host's connection is alive the uint is the connection count, it increments every time a reconnect occurs
func (*Host) Disconnect ¶
func (h *Host) Disconnect()
Disconnect closes the Host connection under the write lock Due to asynchronous connection handling, this may result in killing a good connection and could result in an immediate reconnection by a separate thread
func (*Host) GetAddress ¶
GetAddress returns the address of the host.
func (*Host) GetMessagingContext ¶
func (h *Host) GetMessagingContext() (context.Context, context.CancelFunc)
GetMessagingContext returns a context object for message sending configured according to HostParams
func (*Host) GetMessagingContextWithTimeout ¶
func (h *Host) GetMessagingContextWithTimeout( timeout time.Duration) (context.Context, context.CancelFunc)
GetMessagingContextWithTimeout returns a context object for message sending configured according to HostParams
func (*Host) GetMetrics ¶
GetMetrics returns a deep copy of Host's Metric This resets the state of metrics
func (*Host) GetRemoteCertificate ¶
func (h *Host) GetRemoteCertificate() (*x509.Certificate, error)
GetRemoteCertificate returns the tls certificate from the server for web hosts Note that this will return an error when used on grpc hosts, and will not have a certificate ready until something has been sent over the connection.
func (*Host) IsOnline ¶
IsOnline returns whether the Host is able to be contacted before the timeout by attempting to dial a tcp connection Returns how long the ping took, and whether it was successful
func (*Host) SetMetricsTesting ¶
SetMetricsTesting sets the host metrics to an arbitrary value. Used for testing purposes only
func (*Host) SetTestPublicKey ¶
func (*Host) SetWindowSize ¶
SetWindowSize sets the amount of data, when streaming, that a sender can send before receiving an ACK keep at zero to use the default GRPC algorithm to determine
func (*Host) StringVerbose ¶
StringVerbose stringer interface for connection
func (*Host) UpdateAddress ¶
UpdateAddress updates the address of the host
type HostParams ¶
type HostParams struct { // Set maximum number of connection attempts MaxRetries uint32 // Set maximum number of transmission attempts MaxSendRetries uint32 // Toggle authorization for Host AuthEnabled bool // Toggles connection cool off EnableCoolOff bool // Number of leaky bucket sends before it stops NumSendsBeforeCoolOff uint32 // Amount of time after a cool off is triggered before allowed to send again CoolOffTimeout time.Duration // Message send timeout (context deadline) SendTimeout time.Duration // Online ping timeout PingTimeout time.Duration // If set, metric handling will be enabled on this host EnableMetrics bool // If false, a connection will only be established when a comm is sent // else, a connection will be established immediately upon host creation DisableLazyConnection bool // If false, if transmitting to this host and there isnt a connection, // the host will auto connect. If true, when transmitting to a not // connected host, an error will be returned. DisableAutoConnect bool // List of sending errors that are deemed unimportant // Reception of these errors will not update the Metric state ExcludeMetricErrors []string // KeepAlive Options for Host connections KaClientOpts keepalive.ClientParameters // ProxyErrorMetricParams are the parameters used for the proxy error // tracker that uses exponential moving average (exponential.MovingAvg). ProxyErrorMetricParams exponential.MovingAvgParams // ConnectionType describes the method for the underlying host connection ConnectionType ConnectionType WebParams WebConnParam }
HostParams is the configuration object for Host creation
func GetDefaultHostParams ¶
func GetDefaultHostParams() HostParams
GetDefaultHostParams Get default set of host params
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
The Manager object provides thread-safe access to Host objects for top-level libraries
func NewManagerTesting ¶
func NewManagerTesting(i interface{}) *Manager
func (*Manager) AddHost ¶
func (m *Manager) AddHost(hid *id.ID, address string, cert []byte, params HostParams) (host *Host, err error)
Creates and adds a Host object to the Manager using the given id
func (*Manager) DisconnectAll ¶
func (m *Manager) DisconnectAll()
Closes all client connections and removes them from Manager
func (*Manager) RemoveHost ¶
Removes a host from the connection manager
func (*Manager) StartConnectionReport ¶
func (m *Manager) StartConnectionReport()
StartConnectionReport begins intermittently printing connection information
type Metric ¶
type Metric struct {
// contains filtered or unexported fields
}
func NewMetricTesting ¶
Creates a metrics object with specified values. Used for testing purposes only
type ProtoComms ¶
type ProtoComms struct { // Inherit the Manager object *Manager // contains filtered or unexported fields }
ProtoComms is a proto object containing a gRPC server logic.
func CreateCommClient ¶
func CreateCommClient(id *id.ID, pubKeyPem, privKeyPem, salt []byte) (*ProtoComms, error)
CreateCommClient creates a ProtoComms client-type object to be used in various initializers.
func StartCommServer ¶
func StartCommServer(id *id.ID, listeningAddr string, certPEMblock, keyPEMblock []byte, preloadedHosts []*Host) (*ProtoComms, error)
StartCommServer creates a ProtoComms server-type object to be used in various initializers. Opens a net.Listener the local address specified by listeningAddr.
func (*ProtoComms) AuthenticatedReceiver ¶
func (c *ProtoComms) AuthenticatedReceiver(msg *pb.AuthenticatedMessage, ctx context.Context) (*Auth, error)
AuthenticatedReceiver handles reception of an AuthenticatedMessage, checking if the host is authenticated & returning an Auth state
func (*ProtoComms) DisableAuth ¶
func (c *ProtoComms) DisableAuth()
DisableAuth makes the authentication code skip signing and signature verification if the set. Can only be set while in a testing structure. Is not thread safe.
func (*ProtoComms) GenerateToken ¶
func (c *ProtoComms) GenerateToken() ([]byte, error)
Generates a new token and adds it to internal state
func (*ProtoComms) GetId ¶
func (c *ProtoComms) GetId() *id.ID
GetId returns a copy of the ProtoComms networkId
func (*ProtoComms) GetPrivateKey ¶
func (c *ProtoComms) GetPrivateKey() *rsa.PrivateKey
GetPrivateKey is the getter for local server's private key.
func (*ProtoComms) GetServer ¶
func (c *ProtoComms) GetServer() *grpc.Server
GetServer returns the ProtoComms grpc.Server object
func (*ProtoComms) PackAuthenticatedContext ¶
Add authentication fields to a given context and return it
func (*ProtoComms) PackAuthenticatedMessage ¶
func (c *ProtoComms) PackAuthenticatedMessage(msg proto.Message, host *Host, enableSignature bool) (*pb.AuthenticatedMessage, error)
Convert any message type into a authenticated message
func (*ProtoComms) Restart ¶
func (c *ProtoComms) Restart() error
Restart is a public accessor meant to allow for reuse of a host after Shutdown is called. The intended use is for replacing certificates.
func (*ProtoComms) Send ¶
func (c *ProtoComms) Send(host *Host, f func(conn Connection) (*any.Any, error)) (result *any.Any, err error)
Send sets up or recovers the Host's connection, then runs the given transmit function.
func (*ProtoComms) Serve ¶
func (c *ProtoComms) Serve()
Serve is a non-blocking call that begins serving content for GRPC. GRPC endpoints must be registered before making this call.
func (*ProtoComms) ServeHttps ¶
func (c *ProtoComms) ServeHttps(keyPair tls.Certificate) error
ProvisionHttps provides a tls cert and key to the thread which serves the grpcweb endpoints, allowing it to serve with https. Note that https will not be usable until this has been called at least once, unblocking the listenHTTP func in ServeWithWeb. Future calls will be handled by the startUpdateCertificate thread.
func (*ProtoComms) ServeWithWeb ¶
func (c *ProtoComms) ServeWithWeb()
ServeWithWeb is a non-blocking call that begins serving content for grpcWeb (over HTTP) and GRPC on the same port. GRPC endpoints must be registered before making this call.
func (*ProtoComms) Shutdown ¶
func (c *ProtoComms) Shutdown()
Shutdown performs a graceful shutdown of the local server.
func (*ProtoComms) Stream ¶
func (c *ProtoComms) Stream(host *Host, f func(conn Connection) ( interface{}, error)) (client interface{}, err error)
Stream sets up or recovers the Host's connection, then runs the given Stream function.
func (*ProtoComms) ValidateToken ¶
func (c *ProtoComms) ValidateToken(msg *pb.AuthenticatedMessage) (err error)
Validates a signed token using internal state
type WebConnParam ¶
type WebConnParam struct { /* HTTP Transport config options */ // TLSHandshakeTimeout specifies the maximum amount of time waiting to // wait for a TLS handshake. Zero means no timeout. TlsHandshakeTimeout time.Duration // IdleConnTimeout is the maximum amount of time an idle // (keep-alive) connection will remain idle before closing // itself. // Zero means no limit. IdleConnTimeout time.Duration // ExpectContinueTimeout, if non-zero, specifies the amount of // time to wait for a server's first response headers after fully // writing the request headers if the request has an // "Expect: 100-continue" header. Zero means no timeout and // causes the body to be sent immediately, without // waiting for the server to approve. // This time does not include the time to send the request header. ExpectContinueTimeout time.Duration }
WebConnParam struct holds parameters used for establishing a grpc-web connection The params are used when estabilishing the http connection