protobase

package
v0.0.0-...-7aac46a Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2023 License: MIT Imports: 2 Imported by: 0

README

protobase

Provides design protocols for extending, replacing and creating new subsystems that plug into current flow of the program. A contract provides minimal required functionality excluding operating layer ( e.g. threading model ), dependencies and initialization layer.

"One of the best solutions for ensuring plain dealing is the contract. A contract defines your rights and responsibilities, as well as those of the other party. In addition, there is an agreement concerning repercussions if either party fails to abide by the contract." - The Pragmatic Programmer

Documentation

Index

Constants

View Source
const (
	LQOS0 = 0x00
	LQOS1 = 0x01
	LQOS2 = 0x02
)

QoS (Quality of Service) codes

View Source
const (
	NDUP = 0
	YDUP = 1
)

Duplicate option

View Source
const (
	NRET = 0
	YRET = 1
)

Retain option ( N = no, Y = yes . ex. NRET = no retain, YRET = retain)

View Source
const (
	RESULTFAIL = 0x01
	RESULTERR  = 0x02
	RESULTNOP  = 0x03
	RESULTOK   = 0x04
)

Authorization status codes

View Source
const (
	// STATDISCONNECT is the initial state
	STATDISCONNECT   uint32 = 1
	STATCONNECTING   uint32 = 2
	STATONLINE       uint32 = 3
	STATDISCONNECTED uint32 = 4
	STATERR          uint32 = 5
	STATFATAL        uint32 = 6
	STATGODOWN       uint32 = 7
)

Connection status codes

View Source
const (
	TMP_RESPOK = 0x10 // TODO: change this later
	RESNON     = 0x00 // no response code is set yet
	RESPFAIL   = 0x01
	RESPOK     = 0x02
	RESPNOK    = 0x03
	RESPERR    = 0x04
)

Connection response codes

View Source
const (
	// TODO
	// . add the rest
	RHASSESSION = 0x08
	RCLEANSTART = 0x04
)

Connection response header options

View Source
const (
	PNULL        = 0x00
	PCONNECT     = 0x01
	PCONNACK     = 0x02
	PQUEUE       = 0x04
	PQUEUEACK    = 0x05
	PPUBACK      = 0x06
	PSUBSCRIBE   = 0x07
	PSUBACK      = 0x08
	PUNSUBSCRIBE = 0x09
	PUNSUBACK    = 0x0A
	PPUBLISH     = 0x0B
	PPING        = 0x0C
	PPONG        = 0x0D
	PDISCONNECT  = 0x0E
)

Control packet raw codes

View Source
const (
	CCONNECT     byte = byte(0x1 << 4)
	CCONNACK     byte = byte(0x2 << 4)
	CQUEUE       byte = byte(0x4 << 4)
	CQUEUEACK    byte = byte(0x5 << 4)
	CPUBACK      byte = byte(0x6 << 4)
	CSUBSCRIBE   byte = byte(0x7 << 4)
	CSUBACK      byte = byte(0x8 << 4)
	CUNSUBSCRIBE byte = byte(0x9 << 4)
	CUNSUBACK    byte = byte(0xA << 4)
	CPUBLISH     byte = byte(0xB << 4)
	CPING        byte = byte(0xC << 4)
	CPONG        byte = byte(0xD << 4)
	CDISCONNECT  byte = byte(0xE << 4)
)

Control packet codes ( shifted to left, mask : 0xF0 )

View Source
const (
	ServerNone    uint32 = 1
	ServerRunning uint32 = 2
	ServerStopped uint32 = 3
	ServerIdle    uint32 = 4
)

Server status

View Source
const (
	ForceShutdown uint32 = 5
	Restart       uint32 = 6
)

Server command codes

View Source
const (
	IdentWLCD string = "*"  // wildcard identifer
	TOPICWLCD        = "/*" // topic with wildcard identifier
	Sep              = "/"  // seperator literal
	Wlcd             = "*"  // wildcard lietral
)
View Source
const (
	MAXQoS byte = 0x1
)

Maximum supported Quality of Service

View Source
const (
	ProtoVersion = "\x50\x52\x58\x31"
)

Version

Variables

This section is empty.

Functions

This section is empty.

Types

type ACLInterface

type ACLInterface interface {
	MakeRole(string) (ACLPermInterface, error)
	GetRole(string) ACLPermInterface
	HasRole(string) bool
	GetOrCreate(string) (ACLPermInterface, bool)
}

ACLInterface is the interface used to implement access control list.

type ACLMode

type ACLMode byte

ACLMode is the type for Access Control List modes.

const (
	ACLModeNormal ACLMode = iota
	ACLModeInclusive
	ACLModeExclusive
)

Access Control List mode flags

type ACLNodeInterface

type ACLNodeInterface interface {
	CanDo(bool, ...string) bool
	Add(...string) error
	Unset(...string) (bool, error)
	HasIdentifier(string) bool
	HasWildIdentifier(string) bool
	MakeChild(int, string) ACLNodeInterface
	GetIdentifier(string) ACLNodeInterface
	SetValue(string, ACLNodeInterface) bool
	RemoveValue(string) bool
	Len() int
	IsResource(string) bool
}

ACLNodeInterface is the interface used to implement access control list layered levels.

type ACLPermInterface

type ACLPermInterface interface {
	HasPerm(string, string, string) bool
	HasExactPerm(string, string, string) bool
	SetPerm(string, string, string) error
	UnsetPerm(string, string, string) error
	SetMode(ACLMode) bool
}

ACLPermInterface is the interface for individual access rules associated with a single entity.

type AuthInterface

type AuthInterface interface {
	HasSession(clientId string) bool
	CanAuthenticate(creds CredentialsInterface) (bool, error)
	TryAuthenticate(creds CredentialsInterface) bool
	TryUnAuthenticate(string) bool
	HasClient(string) bool
	MakeCreds(string, string, string, ...interface{}) (CredentialsInterface, error)
	Authenticate(creds CredentialsInterface) bool
	Register(creds CredentialsInterface) (result bool)
	RemoveWithIdentifier(identifier *string) (bool, error) //NOTE change this
	SetMode(AuthMode)
	GetMode() AuthMode
	GetACL() ACLInterface
	GetUserType(string) (AuthUserType, error)
}

AuthInterface is the interface for authenication facilities.

type AuthMode

type AuthMode byte

AuthMode is the type for Authenication subsystem.

const (
	AUTHModeNone AuthMode = iota
	AUTHModeDynamic
	// AUTHModeStrict is defined as follow:
	// - A set of predefined permissions for user groups
	//   which 'Auth' authorizes by validating a route or
	//   action.
	AUTHModeStrict
	AUTHModeRouter
)

Authorization mode flags

type AuthUserType

type AuthUserType string

AuthUserType is the type to identify user groups in a Authentication implementor.

const (
	AuthUserNormal AuthUserType = "User"
	AuthUserRouter AuthUserType = "Router"
)

TODO: . update user types to a singleton User Types

type BaseControlInterface

type BaseControlInterface interface {
	Shutdown()
}

BaseControlInterface is the interface to conform to fulfilling requirements of internal management console.

type BrokerInterface

type BrokerInterface interface {
	Status() byte
}

BrokerInterface is the interface for broker implementors.

type CLBUserInterface

type CLBUserInterface interface {
	IsRunning() bool
	IsConnected() bool
	GetExitCh() chan struct{}
	SetRunning(bool)
	SetConnected(bool)
	Setup() error
	Connect() error
	Disconnect() error
}

CLBUserInterface is the requirement for implementing Client-to-Broker user.

type CLStoreInterface

type CLStoreInterface interface {
	Add(string, ClientInterface)
	Get(string) ClientInterface
}

CLStoreInterface is a interface `ClientInterface` containers.

type ClientDelegate

type ClientDelegate func(net.Conn) ClientInterface

ClientDelegate is the signature for passing a new `ClientInterface` delegate.

type ClientInterface

type ClientInterface interface {
	Connected(OptionInterface) bool
	Disconnected(OptCode)
	Publish(MsgInterface)
	Subscribe(MsgInterface)
	GetIdentifier() string
	GetTopics() []string
	GetCreds() CredentialsInterface
	GetUser() interface{}
	SetCreds(CredentialsInterface)
	SetUser(interface{})
	Setup() error
}

ClientInterface is the interface that must be implemented by subsystems which handle high level client logics. Each control packet may trigger a corresponding routine on structures implementing this interface. It is important to notice that some control packets do not trigger notifications.

type ClientMode

type ClientMode byte

ClientMode is the type for various client modes such as User, Router, or Agent.

const (
	CClient ClientMode = iota
	CRouter
	CAgent
)

Client mode flags

type ConStateInterface

type ConStateInterface interface {
	ProtoEventInterface
	HandleDefault(packet PacketInterface) (status bool) // dispatch loop
	Handle(packet PacketInterface)                      // bootstrap routine
	Run()                                               // main routine
	SetNextState()                                      // push state handler
	Shutdown()
}

ConStateInterface is the requirement for implementing protox event handler.

type ConnectionState

type ConnectionState interface {
	ConStateInterface
	SetClient(client ClientInterface)
	SetServer(server ServerInterface)
}

ConnectionState is the interface for status of a connection. Each state must implement all of its functionalities, during different stages in the program, data will be passed between states which changes the behavior of its underlying functionalities. For example, during `Genesis` stage, any control packet besides `Connect` results in immediate disconnection from the broker. After `Genesis`, data will be passed to `Online` state which is opposite of `Genesis` state ( `Connect` results in immediate termination ).

type ContNodeInterface

type ContNodeInterface interface {
	SetOpts(opts byte)
	SetValue(value interface{})
	GetValue()
}

ContNodeInterface is a interface for representing data nodes.

type CredentialsInterface

type CredentialsInterface interface {
	GetCredentials() (string, string, string)
	IsValid() bool
	Match(CredentialsInterface) bool
	GetUID() string
	Copy() CredentialsInterface
}

CredentialsInterface is the interface for credential providers. It is used by authenicators.

type EDProtocol

type EDProtocol interface {
	Encode() error
	Decode() error
	DecodeFrom(buff []byte) error
	String() string
	UUID() [16]byte
	MessageId() (bool, uint16)
	CommandCode() byte
	GetPacket() PacketInterface
	GetBytes() []byte
}

EDProtocol is a interface used for PDU ( protocol data units ).

type ILoggable

type ILoggable interface {
	SetLogger(LoggingInterface)
}

ILoggable is a interface for any object accepting an external logging facility.

type LoggerInterface

type LoggerInterface interface {
	Trace(int, ...interface{})
	Tracef(int, string, ...interface{})
	Debug(string, ...interface{})
	Debugf(string, ...interface{})
	Info(string, ...interface{})
	Infof(string, ...interface{})
	Warn(string, ...interface{})
	Warnf(string, ...interface{})
	Error(string, ...interface{})
	Errorf(string, ...interface{})
	Fatal(string, ...interface{})
	Fatalf(string, ...interface{})
	Log(int, string, []interface{})
	IsDebug() bool
}

LoggerInterface is a interface that all logging facilities must conform to.

type LoggingInterface

type LoggingInterface interface {
	LoggerInterface
	FInfo(string, string, ...interface{})
	FInfof(string, string, ...interface{})
	FDebug(string, string, ...interface{})
	FDebugf(string, string, ...interface{})
	FWarn(string, string, ...interface{})
	FWarnf(string, string, ...interface{})
	FError(string, string, ...interface{})
	FErrorf(string, string, ...interface{})
	FFatal(string, string, ...interface{})
	FFatalf(string, string, ...interface{})
	FTrace(int, string, string, ...interface{})
	FTracef(int, string, string, ...interface{})
}

LoggingInterface is the extended logging interface.

type MSGIDInterface

type MSGIDInterface interface {
	GetNewID(uuid.UUID) uint16
	IsOccupied(uint16) bool
	GetUUID(uint16) (uuid.UUID, bool)
	FreeId(uint16)
}

MSGIDInterface provides identifier storage used in inbound/outbound messages for retrieval of packets and identification of messsage sequence.

type MessageBox

type MessageBox interface {
	AddInbound(msg EDProtocol) bool
	AddOutbound(msg EDProtocol) bool
	DeleteIn(msg EDProtocol) bool
	DeleteOut(msg EDProtocol) bool
	GetAllOut() (msgs []EDProtocol)
	GetAllOutStr() (msgs []string)
	GetOutbound(uuid.UUID) (EDProtocol, bool)
	GetInbound(uuid.UUID) (EDProtocol, bool)
	GetIDStoreO() MSGIDInterface
	GetIDStoreI() MSGIDInterface
}

MessageBox is the packet storage interface.

type MessageStorage

type MessageStorage interface {
	AddClient(client string)
	AddInbound(client string, msg EDProtocol) bool
	AddOutbound(client string, msg EDProtocol) bool
	DeleteIn(client string, msg EDProtocol) bool
	DeleteOut(client string, msg EDProtocol) bool
	Exists(client string) bool
	GetAllOut(client string) (msgs []EDProtocol)
	GetAllOutStr(client string) (msgs []string)
	GetOutbound(string, uuid.UUID) (EDProtocol, bool)
	GetInbound(string, uuid.UUID) (EDProtocol, bool)
	GetIDStoreO(client string) MSGIDInterface
	GetIDStoreI(client string) MSGIDInterface
	Close(client string) bool
}

MessageStorage is a interface that must be implemented in order to be passed into `ServerInterface` and `ProtoConnection` implementors.

type MsgDir

type MsgDir byte

MsgDir is message direction. It indicates wether a message is inbound or outbound.

const (
	MDInbound MsgDir = iota
	MDOutbound
	MDNone
)

Message Direction

type MsgEnvelopeInterface

type MsgEnvelopeInterface interface {
	Route() string
	Payload() []byte
}

MsgEnvelopeInterface is the interface for content of a proto packet.

type MsgInterface

type MsgInterface interface {
	QoS() byte
	MessageId() uint16
	Dir() MsgDir
	Envelope() MsgEnvelopeInterface
	SetWishQoS(byte)
	Clone(MsgDir) MsgInterface
}

MsgInterface is the interface that represents a proto packet and its neccessary associated meta data.

type OptCode

type OptCode byte

OptCode is the option type used by `OptionsInterface`.

const (
	PUNone OptCode = iota
	PUSocketError
	PURejected
	PUDisconnect
	PUForceTerminate
	PUAckDeadline
)

Client disconnect flags

type OptionInterface

type OptionInterface interface {
	StateCode() OptCode
	Opts() interface{}
	Match(OptCode) bool
}

OptionInterface is the interface that represents a option.

type PacketInterface

type PacketInterface interface {
	SetData([]byte)
	SetCode(byte)
	SetLength(int)
	GetData() []byte
	GetCode() byte
	GetLength() int
	IsValid() bool
}

PacketInterface is low level interface for accessing and manipulating packet content.

type PermissionInterface

type PermissionInterface interface {
	HasPerm(string, string, string) bool
	HasExactPerm(string, string, string) bool
	SetPerm(string, string, string) error
	UnsetPerm(string, string, string) error
}

PermissionInterface is the interface that implementors must conform to in order to become compatible with ACL modules.

type ProtoClientConnection

type ProtoClientConnection interface {
	Handle(PacketInterface)

	SetMessageStorage(MessageBox)
	SetHeartBeat(int)
	SetNetConnection(net.Conn)
	SetStatus(uint32)
	SetClient(ClientInterface)
	ContinueFlag(bool)

	GetConnection() net.Conn
	GetClient() ClientInterface
	GetStatus() uint32
	GetErrChan() chan struct{}
	GetTermChan() chan struct{}

	SendMessage(MsgInterface) error
	SendRedelivery()

	MakeEnvelope(route string, payload []byte, qos byte, messageId uint16, dir MsgDir) MsgInterface
	Publish(string, []byte, byte, func(OptionInterface, MsgInterface)) error
	Subscribe(string, byte, func(OptionInterface, MsgInterface)) error
	Queue(QAction, string, string, []byte, []byte) error
	Disconnect() error
}

ProtocolClientConnection is the main interface used by clients. It handles most of the logics neccessary for handling low level details ( such as parsing and crafting control packets, timeouts, send/receive and ... ) and connects a client to the broker.

type ProtoConnection

type ProtoConnection interface {
	Handle() // main procedure, execution routine

	SetServer(sv ServerInterface)                                      // server instance
	SetAuthenticator(auth AuthInterface)                               // auth subsystem
	SetClientDelegate(cl func(string, string, string) ClientInterface) // client constructor
	SetMessageStorage(store MessageStorage)                            // data structure for storing packets and sequencing ids
	SetHeartBeat(heartbeat int)                                        // max idle threshold
	SetInitiateTimeout(timeout int)                                    // initial authorization/validation deadline
	SetStatus(uint32)                                                  // set status on connection struct
	SetNetConnection(net.Conn)                                         // set network connection ( socket )
	SetPermissionDelegate(cl func(AuthInterface, ...string) bool)      // permission subsystem
	SendMessage(MsgInterface, bool) error                              // write message to remote destination
	SendRedelivery(EDProtocol) error                                   // redeliver packet to its destination
	GetConnection() net.Conn                                           // access underlying network connection ( socket )
	GetClient() ClientInterface                                        // access client structure
	GetStatus() uint32                                                 // get connection status
	GetErrChan() chan struct{}                                         // access error channel
	IsClean() bool                                                     // whether connection struct is reused

}

ProtocolConnection is server side protocol connection interface. It provides business layer logic through required methods.

type ProtoEventInterface

type ProtoEventInterface interface {
	OnCONNECT(PacketInterface)
	OnCONNACK(PacketInterface)
	OnPUBLISH(PacketInterface)
	OnPUBACK(PacketInterface)
	OnSUBSCRIBE(PacketInterface)
	OnSUBACK(PacketInterface)
	OnPING(PacketInterface)
	OnPONG(PacketInterface)
	OnDISCONNECT(PacketInterface)
	OnQUEUE(PacketInterface)
}

ProtoEventInterface is the interface for implementing event handler responsible for processing protox packets. It gets invoked from compatible caller conforming to 'protobase.ConnectionState'.

type ProtoPacket

type ProtoPacket interface {
	Data() []byte
}

type QAction

type QAction uint

QAction is the type for identifying Queue commands.

type RetainStorageInterface

type RetainStorageInterface interface {
	Insert([]byte, EDProtocol) error
	Find([]byte) (EDProtocol, error)
	Remove([]byte) error
}

RetainStorageInterface is the interface for retained messages container.

type RouterInterface

type RouterInterface interface {
	Add(string, string, byte)
	Find(string) (map[string]byte, error)
	Remove(string, string) error
}

RouterInterface is high level interface requirement corresponding to the component in charge for purpose of handling hierarchical topics and its relevant mapping.

type ServerInterface

type ServerInterface interface {
	NotifyDisconnected(prc ProtoConnection)
	NotifyConnected(prc ProtoConnection)
	NotifySubscribe(prc ProtoConnection, msg MsgInterface)
	NotifyPublish(prc ProtoConnection, msg MsgInterface)
	NotifyReject(prc ProtoConnection)
	NotifyQueue(prc ProtoConnection, msg MsgInterface)

	RegisterClient(prc ProtoConnection)
	Redeliver(prc ProtoConnection)
	Shutdown() (<-chan struct{}, error)

	GetStatus() uint32
	GetErrChan() <-chan struct{}
	GetStatusChan() <-chan uint32
	// TODO
	// . improve this
	// NotifyPublish(topic string, message string, prc ProtoConnection, dir MsgDir)
	// NotifySubscribe(topic string, prc ProtoConnection)
	Setup()
}

ServerInterface is the interface that must be implemented by subsystems which do the serving. Each control packet will trigger a corresponding routine on structures implementing this interface.

type SubsProviderInterface

type SubsProviderInterface interface {
	// contains filtered or unexported methods
}

SubsProviderInterface is a interface for topic providers.

Jump to

Keyboard shortcuts

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