connect

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 6, 2023 License: BSD-2-Clause Imports: 43 Imported by: 39

Documentation

Index

Constants

View Source
const MaxWindowSize = math.MaxInt32

MaxWindowSize 4 MB

View Source
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.

View Source
const TooManyProxyError = "too many proxy failures to target host"

TooManyProxyError is the error returned instead of ProxyError, when it occurs too many times.

Variables

View Source
var KaEnforcement = keepalive.EnforcementPolicy{

	MinTime: 3 * time.Second,

	PermitWithoutStream: true,
}

KaEnforcement are keepalive enforcement options for servers

View Source
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

View Source
var MaxConcurrentStreams = uint32(250000)

MaxConcurrentStreams is the number of server-side streams to allow open

View Source
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.

View Source
var TestingOnlyInsecureTLSVerify = false

Functions

func AuthError

func AuthError(id *id.ID) error

AuthError returns a valid authorization error on the given id

func GetAddressFromContext

func GetAddressFromContext(ctx context.Context) (address string, port string, err error)

GetAddressFromContext obtains address:port from the context of an incoming communication

func IsAuthError

func IsAuthError(err error) bool

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

func StreamingContextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)

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

func NewCircuit(list []*id.ID) *Circuit

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

func (c *Circuit) AddHost(newHost *Host)

SetHosts takes a list of hosts and copies them into the list of hosts in the circuit object

func (*Circuit) GetHostAtIndex

func (c *Circuit) GetHostAtIndex(index int) *Host

GetHostAtIndex: Gets host at requested index. Panics if index is outside of the range of the list

func (*Circuit) GetLastNode

func (c *Circuit) GetLastNode() *id.ID

Get the last node in the circuit, will panic if the circuit has nil as a node

func (*Circuit) GetNextNode

func (c *Circuit) GetNextNode(from *id.ID) *id.ID

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

func (c *Circuit) GetNodeAtIndex(index int) *id.ID

GetNodeAtIndex returns the node at the given index. Panics if the index does not exist within the circuit

func (*Circuit) GetNodeLocation

func (c *Circuit) GetNodeLocation(node *id.ID) int

GetNodeLocation returns the location of the passed node in the list. Returns -1 if the node is not in the list

func (*Circuit) GetOrdering

func (c *Circuit) GetOrdering() []*Circuit

GetOrdering returns a slice of Circuits with each one having a different shifted ordering.

func (*Circuit) GetPrevNode

func (c *Circuit) GetPrevNode(from *id.ID) *id.ID

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

func (c *Circuit) IsFirstNode(node *id.ID) bool

IsFirstNode returns true if the passed node is the first node, false otherwise

func (*Circuit) IsLastNode

func (c *Circuit) IsLastNode(node *id.ID) bool

IsLastNode returns true if the passed node is the last node, false otherwise

func (*Circuit) Len

func (c *Circuit) Len() int

Len returns the number of nodes in the circuit

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 NewHost

func NewHost(id *id.ID, address string, cert []byte,
	params HostParams) (host *Host, err error)

NewHost creates a new host object which will use GRPC.

func (*Host) Connect

func (h *Host) Connect() error

Connect allows manual connection to the host if it does not have a valid connection

func (*Host) Connected

func (h *Host) Connected() (bool, uint64)

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

func (h *Host) GetAddress() string

GetAddress returns the address of the host.

func (*Host) GetId

func (h *Host) GetId() *id.ID

GetId returns the id 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

func (h *Host) GetMetrics() *Metric

GetMetrics returns a deep copy of Host's Metric This resets the state of metrics

func (*Host) GetPubKey

func (h *Host) GetPubKey() *rsa.PublicKey

GetPubKey simple getter for the public key

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

func (h *Host) IsOnline() (time.Duration, bool)

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) IsWeb

func (h *Host) IsWeb() bool

IsWeb returns the connection type of the host

func (*Host) SetMetricsTesting

func (h *Host) SetMetricsTesting(m *Metric, face interface{})

SetMetricsTesting sets the host metrics to an arbitrary value. Used for testing purposes only

func (*Host) SetTestPublicKey

func (h *Host) SetTestPublicKey(key *rsa.PublicKey, t interface{})

func (*Host) SetWindowSize

func (h *Host) SetWindowSize(size int32)

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) String

func (h *Host) String() string

Stringer interface for connection

func (*Host) StringVerbose

func (h *Host) StringVerbose() string

StringVerbose stringer interface for connection

func (*Host) UpdateAddress

func (h *Host) UpdateAddress(address string)

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) GetHost

func (m *Manager) GetHost(hostId *id.ID) (*Host, bool)

Fetch a Host from the internal map

func (*Manager) RemoveHost

func (m *Manager) RemoveHost(hid *id.ID)

Removes a host from the connection manager

func (*Manager) StartConnectionReport

func (m *Manager) StartConnectionReport()

StartConnectionReport begins intermittently printing connection information

func (*Manager) String

func (m *Manager) String() string

Implements Stringer for debug printing

type Metric

type Metric struct {
	// contains filtered or unexported fields
}

func NewMetricTesting

func NewMetricTesting(errCounter uint64, face interface{}) *Metric

Creates a metrics object with specified values. Used for testing purposes only

func (*Metric) GetErrorCounter

func (m *Metric) GetErrorCounter() uint64

Getter for errCounter

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

func (c *ProtoComms) PackAuthenticatedContext(host *Host,
	ctx context.Context) context.Context

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) String

func (c *ProtoComms) String() string

Stringer method

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL