idefixgo

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2024 License: MIT Imports: 28 Imported by: 1

Documentation

Overview

Idefix-Go is the official client library for accessing Idefix, the backend of Nayar System's products.

This library is designed in Go and facilitates seamless interaction with Idefix using the MQTT protocol. While Idefix can also be accessed via the HTTP Bridge, MQTT is the preferred method due to its advantages in speed and efficiency.

Key features of the Idefix-Go library include:

  • Easy connection to the Idefix backend via MQTT.
  • Comprehensive methods for managing events, schemas, and states.
  • An intuitive interface that simplifies the integration of Idefix into Go applications.

Index

Constants

View Source
const (
	SuffixMenhirCmd              = "cmd"
	SuffixMenhirCmdFrame         = SuffixMenhirCmd + ".frame"
	SuffixMenhirCmdStorageWrite  = SuffixMenhirCmd + ".storage.write"
	SuffixMenhirCmdStorageRead   = SuffixMenhirCmd + ".storage.read"
	SuffixMenhirCmdStorageRemove = SuffixMenhirCmd + ".storage.remove"
	SuffixMenhirCmdStorageStat   = SuffixMenhirCmd + ".storage.stat"
	SuffixMenhirCmdStorageStats  = SuffixMenhirCmd + ".storage.stats"
)

These constants define topic suffixes used for sending various commands trough Idefix to Menhir. Each constant represents a specific command or action.

SuffixMenhirCmd represents the base suffix for general commands, while the others specify commands related to storage operations.

View Source
const (
	MenhirStorageFileTypeRegular   = 1
	MenhirStorageFileTypeDirectory = 2
)

These constants represent file types used in the Menhir storage system. Each constant categorizes a file as either a regular file or a directory.

View Source
const (
	TopicCmd = "os.cmd"

	TopicCmdFile       = TopicCmd + ".file"
	TopicCmdFileRead   = TopicCmdFile + ".read"
	TopicCmdFileWrite  = TopicCmdFile + ".write"
	TopicCmdFileSize   = TopicCmdFile + ".size"
	TopicCmdFileCopy   = TopicCmdFile + ".copy"
	TopicCmdFileSHA256 = TopicCmdFile + ".sha256"
	TopicCmdExec       = TopicCmd + ".exec"
	TopicCmdMkdir      = TopicCmd + ".mkdir"
	TopicCmdPatch      = TopicCmd + ".patch"
	TopicCmdRemove     = TopicCmd + ".remove"
	TopicCmdMove       = TopicCmd + ".move"
	TopicCmdFree       = TopicCmd + ".free"
	TopicCmdListDir    = TopicCmd + ".listdir"
)

The following constants define command topics for inter-system communication regarding file operations and other commands in the operating system context. Each command topic is a string that specifies the type of command being executed, allowing for structured messaging and organization.

TopicCmd serves as the base topic for OS commands, while the other constants extend this base to specify particular file operations, such as reading, writing, copying, and managing files. This organization helps in routing messages correctly within the system.

Variables

This section is empty.

Functions

func BenchmarkBstates

func BenchmarkBstates(blob *BstatesBlob, bstates []*Bstate)

BenchmarkBstates measures and compares the sizes of BstatesBlob against different compression pipelines.

This function takes a BstatesBlob and a list of Bstates, extracts the state data, and calculates the uncompressed size. It then compares this size with the compressed sizes produced by two different pipelines ("gzip" and "transposed + gzip"). The results are printed, including the number of states, the uncompressed size, the raw blob size, and the compressed blob sizes. If there are no states to process, the function returns immediately.

func ExitToUpdate

func ExitToUpdate(ic *Client, address string, updateType int, cause string, stopDelay, waitHaltDelay, tout time.Duration) (resp *m.UpdateResMsg, err error)

ExitToUpdate sends an update command to the given address to initiate a graceful exit and update process. The update command includes the update type, cause, stop delay, and wait halt delay, allowing for customizable control over the update behavior. It sends the command via the client's Call2 method and waits for the response.

The updateType defines the type of update being performed, and cause provides a reason for the update. stopDelay and waitHaltDelay specify the durations to wait before stopping and halting operations, respectively. tout sets the timeout for the update request.

func FileCopy

func FileCopy(ic *Client, address, srcPath, dstPath string, tout time.Duration) (err error)

FileCopy sends a request to copy a file from srcPath to dstPath on the remote system. It uses the client's Call2 method to execute the file copy operation at the specified address. The function returns an error if the file copy operation fails.

func FileRead

func FileRead(ic *Client, address, path string, tout time.Duration) (data []byte, err error)

FileRead retrieves the contents of a file located at the specified path on the remote system. It sends a request using the client's Call2 method to read the file data. The function returns the file's content as a byte slice or an error if the read operation fails.

func FileSHA256

func FileSHA256(ic *Client, address, path string, tout time.Duration) (hash []byte, err error)

FileSHA256 computes the SHA256 hash of a file located at the specified path on the remote system. It sends a request using the client's Call2 method to retrieve the hash. The function returns the computed hash as a byte slice or an error if the request fails.

func FileSHA256Hex

func FileSHA256Hex(ic *Client, address, path string, tout time.Duration) (hashHex string, err error)

FileSHA256Hex computes the SHA256 hash of a file located at the specified path on the remote system and returns it as a hex-encoded string. It first calls FileSHA256 to obtain the raw hash bytes. The function returns the hex string representation of the hash or an error if the hash computation fails.

func FileWrite

func FileWrite(ic *Client, address, path string, data []byte, mode os.FileMode, tout time.Duration) (hash string, err error)

FileWrite uploads data to a file at the specified path on the remote system. It sends a request using the client's Call2 method, including the file's path, content, and mode for the file's permissions. Upon successful upload, the function returns the hex representation of the hash (sha256) of the data or an error if the write operation fails.

func GetBstates

func GetBstates(ic *Client, p *GetBstatesParams, stateMap GetBstatesResult) (totalBlobs uint, cid string, err error)

GetBstates retrieves bstates events from cloud based on the provided parameters.

If a UID is specified in the parameters, the function first fetches the event associated with that UID. It then populates the provided state map with the states extracted from the event. If no states are found, an error is returned indicating that the event is not based on bstates.

If no UID is specified, the function retrieves bstates using the provided parameters and populates the state map accordingly.

The function returns the total number of blobs processed, the continuation ID, and any error encountered during the process.

func GetDeltaStates

func GetDeltaStates(in []*Bstate) ([]map[string]interface{}, error)

GetDeltaStates processes a slice of Bstate objects and retrieves the delta states represented as a slice of maps. Each Bstate contains a State that is processed to derive the delta states, which are useful for tracking changes between different states over time.

func GetFree

func GetFree(ic *Client, address, path string, tout time.Duration) (freeSpace uint64, err error)

GetFree requests the available free space for a given path from the remote address. The function sends a request using the client's Call2 method, asking for the free disk space at the specified path. It returns the amount of free space in bytes or an error if the request fails.

func ListDir

func ListDir(ic *Client, address, path string, tout time.Duration) (files []*m.FileInfo, err error)

ListDir sends a request to the specified address to list the contents of the directory at the given path. It uses the client's Call2 method to send the request and retrieve a response containing the file information. The function returns a slice of FileInfo pointers representing the files in the directory or an error if the request fails.

func MenhirStorageRead

func MenhirStorageRead(ic *Client, address, menhirInstance, fname string, tout time.Duration) (data []byte, err error)

MenhirStorageRead retrieves a file's data from the Menhir storage system.

It sends a request to the specified Menhir instance to read the file with the given filename. The function returns the file's data or an error if the read operation fails.

func MenhirStorageRemove

func MenhirStorageRemove(ic *Client, address, menhirInstance, fname string, tout time.Duration) (err error)

MenhirStorageRemove removes a file from the Menhir storage system.

The function sends a command to the specified Menhir instance to delete a file identified by its filename. If the operation is successful, the file is removed from storage.

func MenhirStorageWrite

func MenhirStorageWrite(ic *Client, address, menhirInstance, fname string, data []byte, tout time.Duration) (err error)

MenhirStorageWrite uploads a file to the Menhir storage system.

It sends the provided data to the specified Menhir instance to be stored under the given filename. The function constructs a message containing the filename and data, then calls the remote system to execute the storage write command.

func Move

func Move(ic *Client, address, srcPath, dstPath string, tout time.Duration) (err error)

Move sends a request to move a file or directory from srcPath to dstPath on the remote system. It uses the client's Call2 method to perform the move operation at the specified address. The function returns an error if the move operation fails.

func NormalizeAddress

func NormalizeAddress(address string) string

Given an address, this method will return a valid address. If the provided address is valid, the returned address will be the same. Otherwise, if the given address contains characters other than numbers, letters, or dashes, this method will generate the SHA256 hash of that address and return the first 16 characters.

func Remove

func Remove(ic *Client, address, path string, tout time.Duration) (err error)

Remove sends a request to delete a file or directory at the specified path on the remote system. It uses the client's Call2 method to perform the removal operation at the given address. The function returns an error if the removal operation fails.

func UpdateConfig

func UpdateConfig(c *ClientOptions) error

UpdateConfig updates the configuration of the specified client. This function should only be called after the ReadConfig function has been executed successfully.

Upon successful updating of the configuration, the changes are persisted by calling the WriteConfig method on the configuration provider.

Types

type Bstate

type Bstate struct {
	Timestamp time.Time
	State     *be.State
}

Bstate represents a single snapshot of the state of a device at a specific point in time. It consists of a timestamp indicating when the snapshot was recorded and the actual state data. For more information see Bstates documentation: https://github.com/nayarsystems/bstates

type BstatesBlob

type BstatesBlob struct {
	UID       string
	Timestamp time.Time
	States    []*Bstate
	Raw       []byte
}

BstatesBlob represents a collection of Bstates along with associated metadata. It contains information about the unique identifier of the user, the timestamp when the collection was created, the actual states, and the raw byte data representing the compressed queue of states.

type BstatesSource

type BstatesSource struct {
	Meta    map[string]interface{}
	MetaRaw string
	Blobs   []*BstatesBlob
	// contains filtered or unexported fields
}

BstatesSource represents a source of Bstates that includes metadata and a collection of BstatesBlob instances. It provides contextual information for processing the Bstates.

type Client

type Client struct {
	ConnectionStatusHandler ConnectionStatusHandler
	// contains filtered or unexported fields
}

Client represents a connection to Idefix, providing methods to interact with. It encapsulates the context, configuration, and connection details necessary for operation.

func NewClient

func NewClient(pctx context.Context, opts *ClientOptions) *Client

NewClient returns a new Client with the options and the context given

func NewClientFromFile

func NewClientFromFile(pctx context.Context, configFile string) (*Client, error)

NewClientFromFile returns a new Client with the context given and the options readen from a config file given

func (*Client) Answer

func (c *Client) Answer(origmsg *m.Message, msg *m.Message) error

Answer constructs a response message based on the original message and sends it back to the intended recipient.

The original message, 'origmsg', is used to determine the response destination by setting the 'To' field of the response message `msg` to the 'Res' field of the original message. This allows the sender of the original message to receive the response correctly.

It is important to ensure that 'origmsg' contains a valid response destination in its 'Res' field before calling this method. If the response message fails to send, an error will be returned.

func (*Client) Call

func (c *Client) Call(remoteAddress string, msg *m.Message, timeout time.Duration) (*m.Message, error)

Call sends a message to a specified remote address and expects a response. If timeout given is exceed it returns an error.

func (*Client) Call2

func (c *Client) Call2(remoteAddress string, msg *m.Message, resp any, timeout time.Duration) error

Call2 uses Client.Call to send a message to a specified remote address and expects a response. The function converts the 'msg.Data' field into a map (msi) format before sending it using the internal Client.Call method. If a response is expected ('resp' is not nil), it parses the returned data into the provided response structure. The function also handles any errors that occur during the process, either in the message sending or the response.

func (*Client) Connect

func (c *Client) Connect() (err error)

Connect establishes a connection to the MQTT broker. This method must be called when the client is in the Disconnected state. If the client is already connected, an error will be returned.

The Connect method initializes the MQTT client with the provided options, including the broker address, credentials, and optional TLS configuration if a CA certificate is provided. It generates a unique session ID if one is not specified in the options.

Upon successful connection, it subscribes to the client's designated response topic and performs a login operation. The connection state is then updated to Connected.

func (*Client) Context

func (c *Client) Context() context.Context

Returns the client context

func (*Client) Disconnect

func (c *Client) Disconnect()

Disconnect gracefully terminates the connection to the MQTT broker. This method changes the client's state to Disconnected and invokes the cancel function associated with the client's context, which may trigger any pending operations or goroutines related to the client's connection.

func (*Client) GetAddressDomain

func (c *Client) GetAddressDomain(address string, timeout time.Duration) (*m.Domain, error)

Attempts to retrieve the domain assigned to the given address. The operation may timeout if it doesn't complete within the specified duration.

func (*Client) GetEventByUID

func (c *Client) GetEventByUID(uid string, timeout time.Duration) (*m.EventsGetUIDResponseMsg, error)

GetEvents retrieves an event from the specified UID.

The function sends a request to the "events.get" destination using the Idefix service, and returns a response containing the events that match the provided criteria.

The request includes a timeout duration, which is capped at 30 seconds if a larger value is provided. If successful, the function returns the retrieved events encapsulated in an EventsGetUIDResponseMsg. If any error occurs, it returns an error.

func (*Client) GetEvents

func (c *Client) GetEvents(domain, address string, since time.Time, limit uint, cid string, timeout time.Duration) (*m.EventsGetResponseMsg, error)

GetEvents retrieves a list of events from the specified domain and address that occurred after the given time.

The function sends a request to the "events.get" destination using the Idefix service, and returns a response containing the events that match the provided criteria.

The request includes a timeout duration, which is capped at 30 seconds if a larger value is provided. If successful, the function returns the retrieved events encapsulated in an EventsGetResponseMsg. If any error occurs, it returns an error.

func (*Client) GetSchema

func (c *Client) GetSchema(hash string, timeout time.Duration) (*messages.SchemaGetResponseMsg, error)

GetSchema retrieves the schema associated with the provided hash from the Idefix service.

This method sends a request to the Idefix service to fetch the schema by hash. It uses a message structure that specifies the hash and whether to perform a check.

If the request is successful, the function returns the response containing the schema information. If an error occurs during the request, it returns nil along with the error.

func (*Client) NewPublisherStream

func (c *Client) NewPublisherStream(address string, topic string, capacity uint, payloadOnly bool, timeout time.Duration) (*PublisherStream, error)

NewPublisherStream creates a new PublisherStream instance for publishing messages to a specified topic on the remote system. It initializes the necessary context, establishes the publisher connection, and configures the stream based on provided parameters.

This function connects to the specified address, sets up the necessary context, and sends a request to start publishing on the specified topic. It also manages the lifetime of the PublisherStream through context cancellation

func (*Client) NewSubscriber

func (c *Client) NewSubscriber(capacity uint, topic ...string) *minips.Subscriber[*m.Message]

NewSubscriber creates a new message subscriber with the specified capacity and topic(s).

The function initializes a new subscriber using the client's internal publish-subscribe system ('ps'), allowing it to receive messages published on the specified topics. The subscriber is configured with a given buffer capacity to manage the number of messages it can hold before processing.

func (*Client) NewSubscriberStream

func (c *Client) NewSubscriberStream(address string, topic string, capacity uint, payloadOnly bool, timeout time.Duration) (*SubscriberStream, error)

NewSubscriberStream creates a new SubscriberStream for the specified topic. It establishes a connection to the remote address and subscribes to the provided topic.

The SubscriberStream allows the client to receive messages published to the specified topic. It can handle both payload-only messages and full message structures based on the value of the payloadOnly parameter.

func (*Client) Publish

func (c *Client) Publish(remoteAddress string, msg *m.Message) error

Publish sends a message to a specified remote address.

func (*Client) SendEvent

func (c *Client) SendEvent(payload interface{}, hashSchema string, meta map[string]interface{}, uid string, timeout time.Duration) error

SendEvent sends an event message with the specified payload, schema, metadata, and unique identifier (UID).

The event message is constructed using the provided payload, which is an arbitrary interface{} type, and is associated with the schema defined by the hashSchema string. The meta parameter is a map containing additional metadata, and the uid is a string uniquely identifying the event.

The event message is sent using MQTT to the "events.create" destination using the Idefix service. The call is made with a specified timeout, and if any error occurs during the process, the function returns the error.

func (*Client) SetSessionID

func (c *Client) SetSessionID(sessionID string)

SetSessionID sets the sessionID for a client

func (*Client) Status

func (c *Client) Status() ConnectionStatus

Returns the connection status of a given client.

func (*Client) WaitOne

func (c *Client) WaitOne(topic string, timeout time.Duration) (*m.Message, error)

WaitOne waits for a single message on the specified topic within the given timeout duration.

The function subscribes to the specified topic and blocks until a message is received or the timeout occurs. If a message is received within the timeout, it is returned. If the timeout expires before a message arrives, an error is returned.

type ClientOptions

type ClientOptions struct {
	Broker    string                 `json:"broker"`            // The address or URL of the MQTT broker the client will connect to.
	Encoding  string                 `json:"encoding"`          // Specifies the data encoding format to be used.
	CACert    []byte                 `json:"cacert,omitempty"`  // A byte slice containing the Certificate Authority (CA) certificate for secure communication.
	Address   string                 `json:"address"`           // The specific client address or identifier used for communications.
	Token     string                 `json:"token"`             // A security token for authenticating the client to the broker.
	Meta      map[string]interface{} `json:"meta,omitempty"`    // A map containing additional metadata.
	SessionID string                 `json:"session,omitempty"` // A string representing the session ID for the client's connection, useful for session management.
	Groups    []string               `json:"groups,omitempty"`  // A list of group identifiers to which the client belongs, used for access control.
	// contains filtered or unexported fields
}

ClientOptions defines the configuration options for initializing a Client.

These options include connection details, security settings, metadata, and other parameters that influence how the Client interacts with the MQTT broker

func ReadConfig

func ReadConfig(name string) (*ClientOptions, error)

ReadConfig function reads the config from the filename given and returns the ClientOptions struct with the config data added. File to read must be in current directory or in $HOME/.idefix.

type ConnectionStatus

type ConnectionStatus int64

ConnectionStatus represents the current connection state of the Client. It is used to indicate whether the Client is connected to the MQTT broker or not.

const (
	Disconnected ConnectionStatus = iota
	Connected
)

type ConnectionStatusHandler

type ConnectionStatusHandler func(*Client, ConnectionStatus)

ConnectionStatusHandler is a function type that defines a handler for connection status changes in the Client. This handler is called whenever the connection status of the Client changes, allowing users to implement custom behavior based on the new status.

type GetBstatesParams

type GetBstatesParams struct {
	UID                  string            // Unique identifier for the event.
	Domain               string            // Specifies the domain from which to retrieve.
	Since                time.Time         // A timestamp indicating the starting point for retrieving Bstates; only Bstates after this time will be returned.
	Limit                uint              // The maximum number of results to return in the response.
	Cid                  string            // ContinuationID lets you get following results after your last request.
	AddressFilter        string            // An optional filter to limit results based on specific addresses.
	MetaFilter           eval.CompiledExpr // A compiled expression used to filter results based on metadata criteria.
	Timeout              time.Duration     // The maximum duration to wait for the request to complete before timing out.
	ForceTsField         string            // Specifies the field used for the timestamp if needed, overriding default behavior.
	RawTsFieldYearOffset uint              // An optional offset to apply to the year field in raw timestamp data.
	RawTsFieldFactor     float32           // A scaling factor applied to the raw timestamp data for accurate representation.
}

GetBstatesParams defines the parameters used to retrieve a list of Bstates from the remote system. Each field corresponds to a specific filter or setting for the request, allowing for flexible querying of Bstates based on various criteria.

type GetBstatesResult

type GetBstatesResult = map[string]map[string]map[string]map[string]*BstatesSource

GetBstatesResult represents the result of retrieving bstate information from the Idefix system. It is structured as a nested map to provide easy access to bstate sources.

type MenhirStorageFSStats

type MenhirStorageFSStats struct {
	BlockSize  uint32
	BlockCount uint32
	BlocksUsed uint32
}

MenhirStorageFSStats contains statistics about the file system in the Menhir storage system, related to block storage usage.

func MenhirStorageStats

func MenhirStorageStats(ic *Client, address, menhirInstance string, tout time.Duration) (stats MenhirStorageFSStats, err error)

MenhirStorageStats retrieves filesystem statistics from the Menhir storage system.

The function fetches details such as the block size, total block count, and the number of blocks used from the specified Menhir instance.

type MenhirStorageFileInfo

type MenhirStorageFileInfo struct {
	Filename string
	Type     uint8
	Size     uint32
}

MenhirStorageFileInfo represents metadata information about a file stored in the Menhir storage system.

func MenhirStorageStat

func MenhirStorageStat(ic *Client, address, menhirInstance, fname string, tout time.Duration) (finfo MenhirStorageFileInfo, err error)

MenhirStorageStat retrieves the metadata of a file from the Menhir storage system.

The function requests file information, such as filename, type, and size, from the specified Menhir instance.

type PublisherStream

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

PublisherStream represents a stream for publishing messages to a specific topic. It manages the context, timeout, and associated client details for effective message publishing.

func (*PublisherStream) Close

func (s *PublisherStream) Close() error

Close terminates the PublisherStream, releasing any associated resources. It cancels the context of the stream and sends a request to the remote system to stop the publisher associated with this stream.

The method sends a message to the specified address with the command to stop the publisher identified by the stream's ID. It waits for a response, timing out after five seconds if no response is received.

func (*PublisherStream) Context

func (s *PublisherStream) Context() context.Context

Context returns the context associated with the PublisherStream. This context can be used to manage the lifecycle of the stream, allowing for cancellation and timeout control.

func (*PublisherStream) Publish

func (s *PublisherStream) Publish(msg any, subtopic string) error

Publish sends a message to a specific subtopic of the PublisherStream's main topic.

The method determines whether to publish only the payload or to wrap it in a StreamMsg structure based on the payloadOnly flag. If payloadOnly is true, the message is sent directly; otherwise, it is encapsulated within a StreamMsg.

type SubscriberStream

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

SubscriberStream manages the state and operations for a subscription to a message stream.

func (*SubscriberStream) Channel

func (s *SubscriberStream) Channel() <-chan *m.Message

Channel returns a read-only channel that streams messages from the subscriber.

func (*SubscriberStream) Close

func (s *SubscriberStream) Close() error

Close terminates the 'SubscriberStream' by canceling the stream and unsubscribing from the remote topic.

func (*SubscriberStream) Context

func (s *SubscriberStream) Context() context.Context

Context returns the context of a given SubscriberStream

Directories

Path Synopsis
minips module
tools
idefix Module

Jump to

Keyboard shortcuts

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