api

package
v0.0.0-...-35f1774 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

package api with http server and TLSClient apis

Index

Constants

View Source
const (
	// CA key for self signed certificates
	DefaultCaKeyFile = "caKey.pem"

	// clients and server need the CA
	DefaultCaCertFile = "caCert.pem"

	// client side certificate
	DefaultCertFileSuffix = "Cert.pem"
	DefaultKeyFileSuffix  = "Key.pem"
)

certificate file names

View Source
const (
	// The http server module type that can be used to retrieve the server instance from the factor.
	HttpServerModuleType = "httpserver"

	// The default health check ping path to register
	DefaultPingPath = "/ping"

	// The default HTTP TLS listening port if none is set
	DefaultHttpsPort = 8444

	// The context ID's for authenticated clientID and connectionID
	ClientIDContextID = "client-id"
	// The client provided connection ID to differentiate different connections from the same clientID
	ClientCIDContextID = "cid"

	// ConnectionIDHeader is intended for linking return channels to requests.
	// intended for separated return channel like sse.
	ConnectionIDHeader = "cid"
	// CorrelationIDHeader is the header to be able to link requests to out of band responses
	// tentative as it isn't part of the wot spec
	CorrelationIDHeader = "correlationID"
)

Standardized http transport definitions for use with HiveOT. These are used by GetRequestParams but usage is optional.

View Source
const (
	BusRecipeType   = "busRecipe"
	ChainRecipeType = "chainRecipe"
	StarRecipeType  = "starRecipe"
)

recipe module types

View Source
const (
	// The server accepted a connection from a client
	ServerConnectEvent = "serverconnect"
	// The server remove a client connection
	ServerDisconnectEvent = "serverdisconnect"
)

notifications sent by transport servers to server side services These are published by TransportServerBase

View Source
const (
	// HiveOT SSE uses a single SSE connection as return channel; payload are RRN messages.
	ProtocolTypeHiveotSsesc   = "hiveot-ssesc"
	ProtocolSchemeHiveotSseSc = "sse"
	SubprotocolHiveotSsesc    = "sse-sc"

	// HiveOT gRPC is intended for local inter-process communication using UDS,
	// and uses the HiveOT RRN messages as the payload.
	// TODO: also support the tcp variant
	ProtocolTypeHiveotGrpc   = "hiveot-grpc"
	ProtocolSchemeHiveotGrpc = "unix"
	SubprotocolHiveotGrpc    = "" // not a subprotocol

	// HiveOT websocket uses RRN messages as the envelope.
	ProtocolTypeHiveotWebsocket   = "hiveot-websocket"
	ProtocolSchemeHiveotWebsocket = "wss"
	SubprotocolHiveotWebsocket    = "hiveot:websocket"

	// Http-basic follows the WoT specification
	ProtocolTypeWotHttpBasic   = "http-basic"
	ProtocolSchemeWotHttpBasic = "https"
	SubprotocolWotHttpBasic    = ""

	// Http long poll is not implemented
	ProtocolTypeWotHttpLongPoll   = "http-longpoll"
	ProtocolSchemeWotHttpLongPoll = "https"
	SubprotocolWotHttpLongPoll    = "longpoll"

	// WoT MQTT is not yet implemented
	ProtocolTypeWotMqtt   = "wot-mqtt"
	ProtocolSchemeWotMqtt = "mqtts"

	// WoT SSE is not implemented
	ProtocolTypeWotSse   = "wot-sse"
	ProtocolSchemeWotSse = "sse"

	// WoT websocket follows the WoT specification
	ProtocolTypeWotWebsocket   = "wot-websocket"
	ProtocolSchemeWotWebsocket = "wss"
	SubprotocolWotWebsocket    = "websocket"
)
View Source
const AppEnvironmentModuleType = "AppEnvironment"

For use in the factory chain

View Source
const (
	// Experimental: Ask the client module to connect with previously set credentials.
	// the action responds with the completed or failed result.
	// If Connect is not supported the request should return with an error.
	ClientConnectAction = "connect"
)

Actions implemented in transport clients

View Source
const ClientConnectionStatusEvent = "connectionStatus"

Experimental: notification that the client connect status has changed. the payload is the new connection status. The notification thingID is the client's module-id. Note that connection status events are never transmitted to and from the server.

Variables

This section is empty.

Functions

func GetFactoryModule

func GetFactoryModule[T interface{}](f IModuleFactory, moduleType string) T

Helper to get a module from the factory with the given interface

Types

type AppEnvironment

type AppEnvironment struct {
	// Directories
	BinDir     string `yaml:"binDir,omitempty"`     // Application binary folder, e.g. launcher, cli, ...
	PluginsDir string `yaml:"pluginsDir,omitempty"` // Plugin folder
	HomeDir    string `yaml:"homeDir,omitempty"`    // Home folder, default this is the parent of bin, config, certs and logs
	ConfigDir  string `yaml:"configDir,omitempty"`  // config folder with application and configuration files
	ConfigFile string `yaml:"configFile,omitempty"` // Application configuration file. Default is clientID.yaml
	CertsDir   string `yaml:"certsDir,omitempty"`   // Certificates and keys location
	LogsDir    string `yaml:"logsDir,omitempty"`    // Logging output
	LogLevel   string `yaml:"logLevel,omitempty"`   // logging level: error, warning, info, debug
	StoresDir  string `yaml:"storesDir,omitempty"`  // Root of the service stores

	// For clients: forced server to connect to: scheme://host/path, or "" for auto.
	// This can be useful to point to a gateway if the directory can't be discovered
	// or runs on a different server.
	ServerURL string `yaml:"serverURL,omitempty"`

	// The provided URL of the directory for a direct connection. This is not the
	// exploration http endpoint but the directory server itself. This endpoint will
	// accept requests for reading the directory using action names from the directory
	// specification. See also the directory.IDirectory api for these method names.
	// This is empty if a directory is not available.
	DirectoryURL string `yaml:"directoryURL,omitempty"`

	// The CA public certificate that signed the server certificate.
	// Intended for clients to validate the connection with the server.
	CaCert *x509.Certificate `yaml:"-"` // default cert if loaded

	// the client certification for transport client modules if applicable
	// Intended for clients that authenticate using a certificate.
	ClientCert *tls.Certificate `yaml:"-"`

	// Override the https port used for the http server instantiation
	HttpsPort int `yaml:"httpsPort"`

	// the server certification for transport server modules if applicable
	// Intended for gateways or hub that runs a server.
	// Also usable for devices that run a server.
	TLSCert *tls.Certificate `yaml:"-"`

	// RpcTimeout is the communication timeout for use by transport client and server modules
	RpcTimeout time.Duration

	// AppID is the application instance ID derived from the binary
	// Used as the default clientID
	AppID string `yaml:"appID"`

	// AuthToken contains the client authentication token for connecting to the server.
	// This can be set manually or loaded with GetAuthToken()
	AuthToken string `yaml:"-"`

	// The clientID used to authenticate, certificate filename and token name.
	// By default the clientID is the same as the appID unless changed.
	ClientID string `yaml:"clientID"`

	// The directory TD for bootstrapping a client.
	// This can be provided by discovery or set manually.
	DirTDD *td.TD `yaml:"-"`

	// KeyFile is the file that holds the private/public keys of the application.
	// Can be used by client applications to authenticate connect to a hub/gateway.
	// Intended for encryption and for client cert authentication when using reverse connections.
	// This is derived from the AppID: {certsDir}/{AppID}.key
	KeyFile string `yaml:"keyFile"` // app's key pair file location

}

AppEnvironment holds the running environment naming conventions. Intended for devices, services, or client applications. This contains folder locations, CA certificate and application clientID

func NewAppEnvironment

func NewAppEnvironment(homeDir string, withFlags bool) *AppEnvironment

NewAppEnvironment returns an application environment including folders for use by modules.

Optionally parse commandline flags:

-home  	      alternative home directory. Default is the parent folder of the app binary
-clientID     alternative clientID. Default is the application binary name (appID).
-config       alternative config directory. Default is home/certs
-loglevel     debug, info, warning (default), error
-serverURL    optional device or gateway server URL or "" for auto-detect
-directoryURL optional directory URL or "" for auto-detect

The default 'user based' structure is:

	home
	  |- bin                Core binaries
      |- plugins            Plugin binaries
	  |- config             Service configuration yaml files
	  |- certs              CA and service certificates
	  |- logs               Logging output
	  |- run                PID files and sockets
	  |- stores
	      |- {service}      Store for service

The system based folder structure is used when launched from a path starting with /usr or /opt:

/opt/hiveot/bin            Application binaries, cli and launcher
/opt/hiveot/plugins        Plugin binaries
/etc/hiveot/conf.d         Service configuration yaml files
/etc/hiveot/certs          CA and service certificates
/var/log/hiveot            Logging output
/run/hiveot                PID files and sockets
/var/lib/hiveot/{service}  Storage of service

This uses os.Args[0] application path to determine the home directory, which is the parent of the application binary. The default appID/clientID is based on the binary name using os.Args[0]. This is used to load client certificate and/or token, if available in the certs directory.

homeDir to override the auto-detected or commandline paths. Use "" for defaults.
withFlags parse the commandline flags for -home and -clientID

func (*AppEnvironment) GetAuthToken

func (env *AppEnvironment) GetAuthToken() (string, error)

GetAuthToken returns the application authentication token. If no auth token is set then this is loaded from {clientID}.token. This returns an error if the token isn't set and the file cant be loaded.

func (*AppEnvironment) GetCACert

func (env *AppEnvironment) GetCACert() (caCert *x509.Certificate, err error)

GetCACert returns the CA public certificate used with the servers using the default CA cert name. If not yet set this will load the certificate on first use.

This returns nil if the CA is not set and cannot be loaded.

func (*AppEnvironment) GetClientID

func (env *AppEnvironment) GetClientID() string

Return the configured clientID This defaults to the appID, unless a different ID was provided via the commandline

func (*AppEnvironment) GetServerURL

func (env *AppEnvironment) GetServerURL() string

Get the server URL when needed - intended for starting clients when using the factory. This returns the preconfigured or commandline provided URL.

This URL can also be set using the discovery client module configured for a specific protocol.

func (*AppEnvironment) GetStorageDir

func (env *AppEnvironment) GetStorageDir(moduleType string) string

Return the directory where a module stores its data. This does not create the directory.

func (*AppEnvironment) GetTLSCert

func (env *AppEnvironment) GetTLSCert() (cert *tls.Certificate, err error)

GetTLSCert return the application TLS cert. If no cert is set yet, an attempt is made to load it from file. For servers this is the server app certificate. For clients this is the client certificate for authentication using certificates. This loads the {certsDir}/{clientID}Cert.Pem and {clientID}Key.pem files

This returns the cert or an error if none is found.

func (*AppEnvironment) LoadConfig

func (env *AppEnvironment) LoadConfig(cfg interface{}) error

LoadConfig loads the application/plugin configuration from {configDir}/{clientID}.yaml

This returns an error if loading or parsing the config file fails. Returns nil if the config file doesn't exist or is loaded successfully.

type ConnectionHandler

type ConnectionHandler func(status ConnectionStatus, c IConnection)

ConnectionHandler handles a change in connection status

status of the connection
c is the connection instance being established or disconnected

type ConnectionInfo

type ConnectionInfo struct {
	// ClientID holds the account ID of the connected client
	ClientID string `json:"clientID"`
	// ConnectionID holds the instance ID of the connected client
	ConnectionID string `json:"cid"`
}

payload of connection events

type ConnectionStatus

type ConnectionStatus string

Connection status values

const (
	// no connection attempt has been made
	StatusNew ConnectionStatus = ""

	// establishing the connection is in progress
	// Calling Connect() returns an error
	StatusConnecting ConnectionStatus = "connecting"

	// the connection was successfully established
	// this is the only status that counts as is-connected.
	// Calling Connect() returns as success without any changes.
	StatusConnected ConnectionStatus = "connected"

	// the connection was been closed by the user
	// Connect can be called to re-establish the connection.
	StatusClosed ConnectionStatus = "closed"

	// the connection was dropped or server not reachable
	// Connect can be called to attempt to re-establish the connection.
	StatusLost ConnectionStatus = "lost"

	// the connection was refused due to incorrect authentication.
	// reauthentication is required.
	// Calling Connect will keep failing until the credentials are valid.
	StatusRefused ConnectionStatus = "refused"
)

connection state machine:

1: new|lost|closed -> connecting -> connected -> closed
2: connecting -> connected -> lost
3: connecting -> refused

type GetCredentials

type GetCredentials func(thingID string) (clientID string, cred string, credType string, err error)

GetCredentials is the handler that provides the credentials for connecting to a transport server.

If the TD has no security info, this returns the scheme auto, which means that the protocol uses its default authentication scheme.

This returns: - clientID is the account on the device to connect to. - cred is the credentials to authenticate with - credType is the type of credentials stored, eg bearer token, digist, etc - error if the destination is unknown.

type GetFormHandler

type GetFormHandler func(op string, thingID string, name string) (f *td.Form, href string)

GetFormHandler is the handler that provides the client with the form needed to invoke an operation This returns the form and a full href for the operation. Relative href's are converted to full hrefs.

type IAuthenticator

type IAuthenticator interface {

	// AddSecurityScheme adds the wot securityscheme to the given TD
	AddSecurityScheme(tdoc *td.TD)

	// ValidateToken verifies the token and client are valid.
	// This returns an error if the token is invalid, the token has expired,
	// or the client is not a valid and enabled client.
	ValidateToken(token string) (clientID string, issuedAt time.Time, validUntil time.Time, err error)
}

type IConnection

type IConnection interface {

	// Close the connection.
	Close()

	// GetClientID returns the clientID used with authentication
	GetClientID() string

	// Deprecated: this is an artifact slated for deprecation
	// GetConnectionID returns the unique connection ID for this client
	// ConnectionIDs on the server use the clientID to differentiate. Eg clclid.
	GetConnectionID() string

	// SendNotification [Thing] sends a notification over the connection to a remote consumer.
	// The connection can decide not to deliver the notification depending on subscriptions or
	// other criteria.
	SendNotification(notif *msg.NotificationMessage)

	// SendRequest [consumer] sends a request over the connection to a Thing.
	//
	// Since not all connections are bidirectional this interface is unidirectional
	// The system MUST always send an asynchronous response carrying the same correlationID
	// as the request.
	// This returns an error if the request cannot be delivered to the remote side. Once delivered
	// it is the responsibility of the other end to properly forward the request and send a response.
	//
	// Use of IConnection directly by consumers is uncommon. The 'Consumer' helper class provides
	// a SendRequest method that can wait until a response is received. It uses the RnR helper
	// to wait for a response with a matching correlationID.
	SendRequest(req *msg.RequestMessage, replyTo msg.ResponseHandler) error

	// SendResponse [Thing] sends an asynchronous response over the connection to a consumer.
	// This returns an error if the response could not be delivered.
	SendResponse(response *msg.ResponseMessage) error

	// Change the default timeout for sending messages
	SetTimeout(timeout time.Duration)
}

IConnection defines the interfaces of a HiveOT server and client connection. Intended for exchanging messages between client and server.

Connections do not differentiate between consumers and devices or services. Both clients and servers can provide a connection for use by consumers, devices and services. In case of connection reversal the server can act as the consumer.

All transport servers provide a callback handler that notifies when a new connection is received. It is up to the application to handle the connection.

type IHiveModule

type IHiveModule interface {

	// GetThingID returns the module's instance ID.
	// This is used as the sender ThingID when sending notifications.
	GetThingID() string

	// HandleRequest processes or forwards the request.
	//
	// When the request is for this module then the module processes the request and
	// invokes replyTo with the response. ReplyTo is invoked asynchronously before
	// or after returning.
	//
	// When the request is not for this producer then it is forwarded:
	//
	// 1. By default modules forward unhandled requests to their request sink.
	//    Flow: consumer -> module -[rsink]-> producer
	//
	// 2. If the module is a transport client: the request is transported to the server,
	//    and the server passes it to the producer that is registered as its sink.
	//    Flow: consumer -[rsink]-> tp-client -> tp-server -[rsink]-> producer
	//
	// 3. If the module is a transport server or server connection then the request is
	//    transported to the remote client. The client passes it to its registered sink.
	//    This sink should be a producer that can handle the request.
	//    (In this case the consumer is a process running on the server)
	//    Flow: consumer -[rsink]-> tp-server -> tp-client -[rsink]-> producer
	//
	//    Note this is the use-case where a device uses connection reversal to connect
	//         to a server, like a hub or gateway, to serve IoT data. The gateway acts
	//         as a consumer to the producer connected to the client.
	//
	//
	// A middleware module can intercept the response by forwarding the request downstream
	// while providing its own handler as the replyTo. This handler then forwards the response
	// to the original replyTo endpoint.
	//
	// This returns an error if the provided replyTo will not be able to receive a response.
	//
	//  request is the request to process or forward
	//  replyTo is the response callback. This MUST be called if the request has been processed.
	HandleRequest(request *msg.RequestMessage, replyTo msg.ResponseHandler) error

	// Handle the notification received from a producer.
	// The default behavior is to forward it upstream to the handler set with SetNotificationSink.
	HandleNotification(notif *msg.NotificationMessage)

	// Set the handler of notifications emitted by this module.
	// Intended to create a chain of notifications from producer to consumer.
	//
	// Optionally set additional notification handlers for specific ThingIDs.
	// If a handler for a thingID already exists a warning will be logged and the existing
	// handler will be replaced.
	//
	// thingIDs are the things to handle the notifications for, or empty for all things
	//
	// This can be invoked before or after Start()
	SetNotificationSink(consumer IHiveModule, thingIDs ...string)

	// SetRequestSink sets the handler of requests emitted by this module.
	//
	// This can be invoked before or after Start() to allow for live rewiring of the
	// module chain.
	SetRequestSink(sink IHiveModule)

	// Start readies the module for use.
	//
	// Note that during Start modules might not yet be linked, so they must not send
	// any requests until all modules have started.
	//
	// If this is an issue then try to solve it by providing dependencies during
	// instantiation, not during Start. When using the factory, other modules can be
	// retrieved using f.GetModule(type).(interface), where f is the factory instance.
	//
	// If the module cannot be used as intended then return an error.
	Start() error

	// Stop halts module operation and releases resources.
	Stop()
}

The HiveOT module interface Anything that accepts requests can be a module, including clients and servers. This interface is the most basic module interface.

type IHttpServer

type IHttpServer interface {
	// GetAuthenticator returns the authenticator used to authenticate incoming connections
	// Also used by sub-protocols to include security scheme in TD's
	GetAuthenticator() IAuthenticator

	// Returns the connection URL of the http server
	GetConnectURL() string

	// Return the authenticated client ID from the http request context.
	// The clientID are set in the context by the middleware chain.
	GetClientIdFromContext(r *http.Request) (clientID string, err error)

	// GetRequestParams decode the HiveOT standardized request parameters:
	// - clientID from context, provided by 'clientID' context, set by the http server authentication.
	// - connectionID from the 'cid' header
	// - correlationID from the 'correlationID' header
	// - payload from the message body
	// - thingID, operation, name from URI variables
	GetRequestParams(r *http.Request) (RequestParams, error)

	// Return the protected route for adding endpoints.
	// Note that these routes will refuse all requests until an authenticator is configured using
	// SetAuthenticator.
	GetProtectedRoute() chi.Router

	// Return the public route for adding endpoints.
	GetPublicRoute() chi.Router

	// Start the server and open the listening port
	Start() error

	// Stop the server and end listening
	Stop()
}

IHttpServer is the minimal HTTP server interface as used by various http subprotocols. The subprotocols can work with any http server module that supports this interface. The factory provides a GetHttpServer() method to retrieve the embedded http server.

type IModuleFactory

type IModuleFactory interface {

	// Add security and forms to the TD for all running transport protocols
	// Intended for devices to add forms before exporting a TD.
	// This passes the request to all server instances that have been created using
	// this factory.
	AddTDSecForms(tdoc *td.TD, includeAffordances bool)

	// Provide the means to authenticate incoming connections.
	// Intended for transport server modules.
	// This returns a proxy stub that can be updated with SetAuthenticator.
	// If no authenticator is set the this proxy fails all authentication attempts.
	//
	// SetAuthenticator is called by the authn module when it is created.
	GetAuthenticator() IAuthenticator

	// Get the connection URL of the first loaded server module or "" if none.
	// Primarily intended for testing. It is recommended to use a discovery server/client module
	// in the factory server/client chains to facilitate discovery of server by the client.
	GetConnectURL() string

	// GetEnvironment returns the application environment used by the factory for
	// confuring modules.
	// Note that the environment can be updated by the modules to allow factory modules
	// to update the TDD, location of gateway and other discoverable information.
	GetEnvironment() *AppEnvironment

	// GetModule returns the loaded module of the given module type.
	//
	// If a module hasn't been loaded/started yet then this returns nil.
	GetModule(moduleType string) IHiveModule

	// Return the http server module instance.
	//
	// Used for modules that need to serve http endpoints, e.g. http basic authn, directory, etc.
	//
	// Set the instantiate flag to indicate that the http server module of type TLSServerModuleType
	// should be loaded if it hasn't been loaded yet. If no such module is registered in the factory
	// module definitions then this returns nil and a warning is logged.
	//
	//  instantiate set to true to auto load the http server module
	//
	// This returns nil if no httpserver module is registered.
	GetHttpServer(instantiate bool) IHttpServer

	// Return the list of available transport servers
	GetTransportServers() []ITransportServer

	// RegisterModule adds a module to the factory, making it available for instantiation
	// and for running recipes.
	//
	// If a module is already registered it is replaced. If the given definition
	// doesn't contain a factory constructor but the existing registration does then
	// only the config from the definition is used and merged with the existing registration.
	//
	// Intended to allow pre-registering modules and only include a ordered list of
	// modules in the chain to instantiate and link.
	//
	// moduleDef defines the module attributes and constructor function
	RegisterModule(moduleDef ModuleDefinition)

	// SetAuthenticator sets the authenticator returned by GetAuthenticator.
	// Note that GetAuthenticator returns a proxy to the actual authenticator.
	// Intended for use by the module that offers authentication capabilities,
	// such as the authn module.
	//
	// By default the authenticator proxy blocks all authentication.
	// Setting a nil authenticator disables authentication.
	SetAuthenticator(a IAuthenticator)

	// StartModule creates and starts an instance of a module by its type.
	//
	// If the module is already started, the existing module instance is returned.
	//
	// If the module factory function is nil then this is an empty slot which
	// will be ignored.
	//
	// This does not link the module to other modules. See also RunRecipe for creating a chain.
	//
	//  moduleType identifies the type of the module to get.
	//	instantiate set to true to create an instance if one isnt loaded
	//
	// This returns an error if no module with the given type is found, or when
	// starting the module fails.
	// This returns nil with no error if the module factory is a 'one-shot'
	// initialization function where its factory handler returns nil.
	StartModule(moduleType string, instantiate bool) (IHiveModule, error)

	// Stop all loaded modules in reverse order of loading.
	// Intended for graceful shutdown.
	Stop()

	// WaitForSignal waits until an OS SigTerm signal is received or context is cancelled.
	// Call StopAll() afters this returns for proper cleanup.
	WaitForSignal(ctx context.Context)
}

IModuleFactory is the interface for the module factory, used to create and manage modules by their type.

The module factory can be used stand-alone or together with the ChainRecipe or StarRecipe.

type IRecipe

type IRecipe interface {
	IHiveModule

	// Place the given module definition into the recipe slot
	// Originally intended for placing the application module in the right spot in the chain.
	//
	// This returns an error if the recipe does not contain a slot with the given ID.
	SetSlot(slotID string, modDef ModuleDefinition) error

	// Start all the modules in the recipe.
	Start() error

	// Stop the factory used by this recipe
	Stop()
}

Interface of a module recipe. Recipe constructors are available for a chain and a star formation.

The recipes directory contains templates for various application use-cases such as an IoT device running its own server with discover and a IoT device using reverse connections. These templates can be used as-is or be copied and modified as seen fit.

type ITransportClient

type ITransportClient interface {
	IHiveModule
	IConnection

	// AuthenticateWithClientCert sets the authentication credentials to the client certificate.
	//
	// The client certificate common name is the client ID and must be signed by the
	// same CA as the server.
	//
	// This returns an error if the certificate is invalid for the current CA, if
	// certificate authentication is not supported or if an existing connection is not closed.
	AuthenticateWithClientCert(clientCert *tls.Certificate) error

	// AuthenticateWithForm determines authentication credentials using forms
	// and the given getCredentials handler.
	//
	// This determines which auth schema the TD describes, obtains the credentials
	// and injects the authentication credentials according to the TDI schema.
	//
	// Use Connect() to establish a connection.
	//
	// This returns an error if credentials cannot be determined or obtained or if an
	// existing connection is not closed.
	AuthenticateWithForm(tdi *td.TD, getCredentials GetCredentials) error

	// AuthenticateWithToken sets the authentication credentials to the given clientID and
	// token.
	//
	// Use Connect() to establish a connection.
	//
	// This method can be used if it is known that token authentication is supported by
	// the server. The method of obtaining a token depends on the application environment.
	// The authn module can be used for token authentication using LoginWithPassword.
	//
	// If the transport client is started by the module factory, credentials can be
	// provided through the included AppEnvironment using client certificate or token,
	// and used when Start() is called to establish a connection. If the AppEnvironment
	// does not contain credentials then AuthenticateWithToken must be used on the client
	// module obtained using factoryInstance.GetModule(TransportClientType) to establish
	// the connection before the chain can be used.
	//
	//	clientID is the ID to authenticate as, it must match the token
	//	token is the authentication token obtained on login
	//
	// This returns an error if token authentication is not supported or if an existing
	// connection is not closed.
	AuthenticateWithToken(clientID, token string) error

	// Connect using the previously set connection credentials. See AuthenticateWith...
	//
	// If an error is returned then call GetConnectionStatus to determine why and
	// whether to attempt to Connect again. If the status is ConnectRefused then the
	// credentials are invalid.
	//
	// Connect does not restore subscriptions.
	//
	// This returns no error if the connection is established and usable.
	// An error is return if unable to connect for any reason.
	Connect() (err error)

	// Return the connecting status
	GetConnectionStatus() ConnectionStatus

	// SetConnectHandler sets the callback handler that is invoked when the connection
	// status changes.
	// Intended for applications to handle reconnect and resubscription.
	SetConnectHandler(h func(newStatus ConnectionStatus, c ITransportClient))

	// Start calls connect.
	// This is optional as calling AuthenticateWith... and Connect() can be used instead.
	// Start is mainly intended for use by the factory.
	// One of the 'AuthenticateWith...' must be invoked first.
	Start() error
}

ITransportClient defines the interface of a transport client connection. This implements IHiveModule and IConnection interfaces.

Note that transport clients do not retain subscription status. If a connection drops then event subscriptions and property observations have to be re-issued by the application. See the 'Reconnect' module that manages automatic reconnection and restoring of subscriptions.

Transport clients issue ClientConnectionStatusEvent notifications when the connection status changes.

type ITransportServer

type ITransportServer interface {
	IHiveModule

	// AddTDSecForms updates the given Thing Description with security and forms for this
	// transport module.
	// The security scheme in the TD is set by the authenticator used by the server.
	AddTDSecForms(tdoc *td.TD, includeAffordances bool)

	// CloseAll closes all client connections. Mainly intended for testing.
	CloseAll()

	// Return the established connection of the given client, if one exists
	// This returns nil if the client does not have an authenticated connection.
	GetConnectionByClientID(clientID string) IConnection

	// GetConnectURL returns connection URL of the server
	GetConnectURL() (uri string)

	// HandleNotification sends the notification to subscribed clients using SendNotification.
	// The remote clients are the notification sink from the server perspective.
	//
	// Notifications received by the server are forwarded to the notification sink
	// This returns an error if the notification is not handled or nil if at least one
	// client subscribes.
	HandleNotification(notif *msg.NotificationMessage)

	// SendNotification [Thing] sends a notification over the connections to
	// remote subscribed consumers.
	// This returns an error if the notification has no subscribers.
	SendNotification(notif *msg.NotificationMessage)

	// SendRequest [consumer] sends a request to a connected Thing.
	//
	// Intended for use by consumers when Things are connected using connection reversal.
	//
	// clientID of the device's that hosts the Thing.
	// responseHandler is the optional callback with the response.
	//
	// This returns an error if the Thing is no longer connected.
	SendRequest(clientID string, req *msg.RequestMessage, replyTo msg.ResponseHandler) error

	// SendResponse [Thing] sends the response message over the transport to a remote
	// consumer with the given client and connection ID.
	//
	// Intended for use by Things
	SendResponse(clientID string, cid string, resp *msg.ResponseMessage) error
}

A transport server module is a server module with hooks for sending messages to remote clients.

type ModuleDefinition

type ModuleDefinition struct {

	// Type of the module, used for registration and lookup.
	// Note that the module type is identical for all instances of a module and is used in the @type
	// field of the module TM, if used. The moduleID is the instance ID of the module and
	// must be unique. Singleton modules use the same ID for module type and moduleID.
	Type string

	// The constructor function to create an instance of the module.
	// The configuration can be used to pass arguments and other configuration to the module.
	//
	// f is the module factory with the app environment and ability to retrieve other modules
	// modDef is the module definition passed to the constructor.
	//
	// This returns an error if the module cannot be created.
	// This returns nil with no error for modules that are used for initialization.
	Constructor func(f IModuleFactory, modDef *ModuleDefinition) (IHiveModule, error)

	// Optional configuration passed to the creation of the module
	Config any
}

ModuleDefinition defines the constructor for a module, used for registration in the module factory This can also be used to add custom modules.

type RequestParams

type RequestParams struct {
	ClientID      string // authenticated client ID
	CorrelationID string // tentative as it isn't in the spec
	ConnectionID  string // connectionID as provided by the client
	Payload       []byte // the raw request payload (body)

	// optional URI parameters
	ThingID string // the thing ID if defined in the URL as {id}
	Name    string // the affordance name if defined in the URL as {name}
	Op      string // the operation if defined in the URL as {op}
}

RequestParams contains the parameters read from the HTTP request

type ValidateTokenHandler

type ValidateTokenHandler func(token string) (clientID string, validUntil time.Time, err error)

ValidateToken verifies the token and client are valid. This returns an error if the token is invalid, the token has expired, or the client is not a valid and enabled client.

Directories

Path Synopsis
Package msg with the response error value
Package msg with the response error value
Package td with Schema type definitions as described here: https://www.w3.org/TR/wot-thing-description/#sec-data-schema-vocabulary-definition
Package td with Schema type definitions as described here: https://www.w3.org/TR/wot-thing-description/#sec-data-schema-vocabulary-definition
Package vocab with HiveOT action names
Package vocab with HiveOT action names

Jump to

Keyboard shortcuts

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