resource

package
v0.41.0-rc0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2024 License: AGPL-3.0 Imports: 29 Imported by: 100

Documentation

Overview

Package resource contains types that help identify and classify resources (components/services) of a robot. The three most important types in this package are: API (which represents an API for a resource), Model (which represents a specific implementation of an API), and Name (which represents a specific instantiation of a resource.)

Both API and Model have a "triplet" format that begins with a namespace. API has "namespace:type:subtype" with "type" in this case being either "service" or "component." Model has "namespace:modelfamily:modelname" with "modelfamily" being somewhat arbitrary and useful mostly for organization/grouping. Note that each "tier" contains the tier to the left it. Such that ModelFamily contains Namespace, and Model itself contains ModelFamily.

An example resource (say, a motor) may use the motor API and thus have the API "rdk:component:motor" and have a model such as "rdk:builtin:gpio". Each instance of that motor will have an arbitrary name (defined in the robot's configuration) represented by a Name type, which also includes the API and (optionally) the remote it belongs to. Thus, the Name contains everything (API, remote info, and unique name) to locate and cast a resource to the correct interface when requested by a client. Model on the other hand is typically only needed during resource instantiation.

Index

Constants

View Source
const (
	// APINamespaceRDK is the namespace to use for APIs defined by the standard robot API.
	APINamespaceRDK = APINamespace("rdk")

	// APINamespaceRDKInternal is the namespace to use for internal services.
	APINamespaceRDKInternal = APINamespace("rdk-internal")

	// APITypeServiceName is for any service in any namespace.
	APITypeServiceName = "service"

	// APITypeComponentName is for any component in any namespace.
	APITypeComponentName = "component"
)
View Source
const (
	DefaultServiceName = "builtin"
	DefaultMaxInstance = 1
)

Placeholder definitions for a few known constants.

View Source
const ModelNamespaceRDK = ModelNamespace("rdk")

ModelNamespaceRDK is the namespace to use for models implemented by the rdk.

Variables

View Source
var (
	// DefaultModelFamily is the rdk:builtin model family for built-in resources.
	DefaultModelFamily = ModelNamespaceRDK.WithFamily("builtin")
	// DefaultServiceModel is used for builtin services.
	DefaultServiceModel = DefaultModelFamily.WithModel("builtin")
)
View Source
var ErrDoUnimplemented = errors.New("DoCommand unimplemented")

ErrDoUnimplemented is returned if the DoCommand methods is not implemented.

Functions

func AsType added in v0.2.36

func AsType[T Resource](from Resource) (T, error)

AsType attempts to get a more specific interface from the resource.

func ContainsReservedCharacter added in v0.0.6

func ContainsReservedCharacter(val string) error

ContainsReservedCharacter returns error if string contains a reserved character.

func DependencyNotFoundError added in v0.2.36

func DependencyNotFoundError(name Name) error

DependencyNotFoundError is used when a resource is not found in a dependencies.

func DependencyTypeError added in v0.2.36

func DependencyTypeError[T Resource](name Name, actual interface{}) error

DependencyTypeError is used when a resource doesn't implement the expected interface.

func Deregister added in v0.2.36

func Deregister(api API, model Model)

Deregister removes a previously registered resource.

func DeregisterAPI added in v0.2.36

func DeregisterAPI(api API)

DeregisterAPI removes a previously registered api.

func FromDependencies added in v0.2.36

func FromDependencies[T Resource](resources Dependencies, name Name) (T, error)

FromDependencies returns a named component from a collection of dependencies.

func GetFieldFromFieldRequiredError added in v0.15.0

func GetFieldFromFieldRequiredError(err error) string

GetFieldFromFieldRequiredError returns the `Field` object from a `FieldRequiredError`.

func IsDependencyNotReadyError added in v0.2.36

func IsDependencyNotReadyError(err error) bool

IsDependencyNotReadyError returns if the given error is any kind of dependency not found error.

func IsMustRebuildError added in v0.2.36

func IsMustRebuildError(err error) bool

IsMustRebuildError returns whether or not the given error is a MustRebuildError.

func IsNotAvailableError added in v0.2.36

func IsNotAvailableError(err error) bool

IsNotAvailableError returns if the given error is any kind of not available error.

func IsNotFoundError added in v0.2.50

func IsNotFoundError(err error) bool

IsNotFoundError returns if the given error is any kind of not found error.

func NativeConfig added in v0.2.36

func NativeConfig[T any](conf Config) (T, error)

NativeConfig returns the native config from the given config via its converted attributes. When generics are better in go to support a mapping of Models -> T's (cannot right now because of type instantiation rules), then this should be a method on the type and hide away both Attributes and ConvertedAttributes.

func NewConfigValidationError added in v0.15.0

func NewConfigValidationError(path string, err error) error

NewConfigValidationError returns a config validation error occurring at a given path.

func NewConfigValidationFieldRequiredError added in v0.15.0

func NewConfigValidationFieldRequiredError(path, field string) error

NewConfigValidationFieldRequiredError returns a config validation error for a field missing at a given path.

func NewMustRebuildError added in v0.2.36

func NewMustRebuildError(name Name) error

NewMustRebuildError is returned when a resource cannot be reconfigured in place and instead must be rebuilt. Almost all models/drivers should be able to reconfigure in place to support the best user experience.

func NewNotAvailableError added in v0.2.36

func NewNotAvailableError(name Name, err error) error

NewNotAvailableError is used when a resource is not available because of some error.

func NewNotFoundError added in v0.2.36

func NewNotFoundError(name Name) error

NewNotFoundError is used when a resource is not found.

func Register added in v0.2.36

func Register[ResourceT Resource, ConfigT ConfigValidator](
	api API,
	model Model,
	reg Registration[ResourceT, ConfigT],
)

Register registers a model for a resource (component/service) with and its construction info.

func RegisterAPI added in v0.2.36

func RegisterAPI[ResourceT Resource](api API, creator APIRegistration[ResourceT])

RegisterAPI register a ResourceAPI to its corresponding resource api.

func RegisterAPIWithAssociation added in v0.2.36

func RegisterAPIWithAssociation[ResourceT Resource, AssocT AssociatedConfig](
	api API,
	creator APIRegistration[ResourceT],
	association AssociatedConfigRegistration[AssocT],
)

RegisterAPIWithAssociation register a ResourceAPI to its corresponding resource api along with a way to allow other resources to associate into its config.

func RegisterComponent added in v0.2.36

func RegisterComponent[ResourceT Resource, ConfigT ConfigValidator](
	api API,
	model Model,
	reg Registration[ResourceT, ConfigT],
)

RegisterComponent registers a model for a component and its construction info. It's a helper for Register.

func RegisterDefaultService added in v0.2.36

func RegisterDefaultService[ResourceT Resource, ConfigT ConfigValidator](
	api API,
	model Model,
	reg Registration[ResourceT, ConfigT],
)

RegisterDefaultService registers a default model for a service and its construction info. It's a helper for RegisterService.

func RegisterService added in v0.2.36

func RegisterService[ResourceT Resource, ConfigT ConfigValidator](api API, model Model, reg Registration[ResourceT, ConfigT])

RegisterService registers a model for a service and its construction info. It's a helper for Register.

func RegisteredAPIs added in v0.2.36

func RegisteredAPIs() map[API]APIRegistration[Resource]

RegisteredAPIs returns a copy of the registered resource apis.

func RegisteredResources added in v0.2.36

func RegisteredResources() map[APIModel]Registration[Resource, ConfigValidator]

RegisteredResources returns a copy of the registered resources.

func SDPTrackNameToShortName added in v0.30.0

func SDPTrackNameToShortName(name string) string

SDPTrackNameToShortName takes the output of SDPTrackName() and returns the resource ShortName.

func StatusFunc added in v0.2.36

func StatusFunc[ResourceT Resource, StatusU proto.Message](
	f func(ctx context.Context, res ResourceT) (StatusU, error),
) func(ctx context.Context, res ResourceT) (any, error)

StatusFunc adapts the given typed status function to an untyped value.

func TransformAttributeMap added in v0.2.36

func TransformAttributeMap[T any](attributes utils.AttributeMap) (T, error)

TransformAttributeMap uses an attribute map to transform attributes to the prescribed format.

func TypeError added in v0.2.36

func TypeError[T Resource](actual Resource) error

TypeError is used when a resource is an unexpected type.

Types

type API added in v0.2.36

type API struct {
	Type        APIType
	SubtypeName string `json:"subtype"`
}

API represents a known component/service (resource) API. It consists of a Namespace, Type, and API.

func NewAPI added in v0.2.36

func NewAPI(namespace, typeName, subtypeName string) API

NewAPI return a new API from a triplet like acme:component:gizmo.

func NewAPIFromString added in v0.2.36

func NewAPIFromString(apiStr string) (API, error)

NewAPIFromString creates a new API from a fully qualified string in the format namespace:type:subtype.

func NewPossibleRDKServiceAPIFromString added in v0.2.36

func NewPossibleRDKServiceAPIFromString(apiStr string) (API, error)

NewPossibleRDKServiceAPIFromString returns an API from a string that if is a singular name, will be interpreted as an RDK service.

func (API) IsComponent added in v0.2.36

func (a API) IsComponent() bool

IsComponent returns if this API is for a component.

func (API) IsService added in v0.2.36

func (a API) IsService() bool

IsService returns if this API is for a service.

func (API) MarshalJSON added in v0.2.36

func (a API) MarshalJSON() ([]byte, error)

MarshalJSON marshals the API name in its triplet form.

func (API) String added in v0.2.36

func (a API) String() string

String returns the triplet form of the API name.

func (*API) UnmarshalJSON added in v0.2.36

func (a *API) UnmarshalJSON(data []byte) error

UnmarshalJSON parses either a string of the form namespace:type:subtype or a json object into an API object.

func (API) Validate added in v0.2.36

func (a API) Validate() error

Validate ensures that important fields exist and are valid.

type APIModel added in v0.2.36

type APIModel struct {
	API   API
	Model Model
}

An APIModel is the tuple that identifies a model implementing an API.

type APINamespace added in v0.2.36

type APINamespace string

APINamespace identifies the namespaces robot resources can live in.

func (APINamespace) WithComponentType added in v0.2.36

func (n APINamespace) WithComponentType(subtypeName string) API

WithComponentType returns an API with the given component name.

func (APINamespace) WithServiceType added in v0.2.36

func (n APINamespace) WithServiceType(subtypeName string) API

WithServiceType returns an API with the given service name.

func (APINamespace) WithType added in v0.2.36

func (n APINamespace) WithType(name string) APIType

WithType returns an API Type with the given name.

type APIRegistration added in v0.2.36

type APIRegistration[ResourceT Resource] struct {
	Status                      CreateStatus[ResourceT]
	RPCServiceServerConstructor func(apiColl APIResourceCollection[ResourceT]) interface{}
	RPCServiceHandler           rpc.RegisterServiceHandlerFromEndpointFunc
	RPCServiceDesc              *grpc.ServiceDesc
	ReflectRPCServiceDesc       *desc.ServiceDescriptor
	RPCClient                   CreateRPCClient[ResourceT]

	// MaxInstance sets a limit on the number of this api allowed on a robot.
	// If MaxInstance is not set then it will default to 0 and there will be no limit.
	MaxInstance int

	MakeEmptyCollection func() APIResourceCollection[Resource]
	// contains filtered or unexported fields
}

APIRegistration stores api-specific functions and clients.

func LookupAPIRegistration added in v0.2.36

func LookupAPIRegistration[ResourceT Resource](api API) (APIRegistration[ResourceT], bool, error)

LookupAPIRegistration looks up a ResourceAPI by the given api. false is returned if there is none or error if an error occurs.

func LookupGenericAPIRegistration added in v0.2.36

func LookupGenericAPIRegistration(api API) (APIRegistration[Resource], bool)

LookupGenericAPIRegistration looks up a ResourceAPI by the given api. false is returned if there is none.

func (APIRegistration[ResourceT]) RegisterRPCService added in v0.2.36

func (rs APIRegistration[ResourceT]) RegisterRPCService(
	ctx context.Context,
	rpcServer rpc.Server,
	apiColl APIResourceCollection[ResourceT],
) error

RegisterRPCService registers this api into the given RPC server.

type APIResourceCollection added in v0.2.36

type APIResourceCollection[T Resource] interface {
	Resource(name string) (T, error)
	ReplaceAll(resources map[Name]T) error
	Add(resName Name, res T) error
	Remove(name Name) error
	ReplaceOne(resName Name, res T) error
}

APIResourceCollection defines a collection of typed resources.

func NewAPIResourceCollection added in v0.2.36

func NewAPIResourceCollection[T Resource](api API, r map[Name]T) (APIResourceCollection[T], error)

NewAPIResourceCollection creates a new API resource collection, which holds and replaces resources belonging to that api.

func NewEmptyAPIResourceCollection added in v0.2.36

func NewEmptyAPIResourceCollection[T Resource](api API) APIResourceCollection[T]

NewEmptyAPIResourceCollection creates a new API resource collection, which holds and replaces resources belonging to that api.

type APIType added in v0.2.36

type APIType struct {
	Namespace APINamespace `json:"namespace"`
	Name      string       `json:"type"`
}

APIType represents a known component/service type of a robot.

func (APIType) String added in v0.2.36

func (t APIType) String() string

String returns the resource type string for the component.

func (APIType) Validate added in v0.2.36

func (t APIType) Validate() error

Validate ensures that important fields exist and are valid.

func (APIType) WithSubtype added in v0.2.36

func (t APIType) WithSubtype(subtypeName string) API

WithSubtype returns an API with the given subtype name.

type Actuator added in v0.2.36

type Actuator interface {
	// IsMoving returns whether the resource is moving or not.
	IsMoving(context.Context) (bool, error)

	// Stop stops all movement for the resource.
	Stop(context.Context, map[string]interface{}) error
}

Actuator is any resource that can move.

IsMoving example:

// This example shows using IsMoving with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")

// Stop all motion of the arm. It is assumed that the arm stops immediately.
myArm.Stop(context.Background(), nil)

// Log if the arm is currently moving.
is_moving, err := myArm.IsMoving(context.Background())
logger.Info(is_moving)

Stop example:

// This example shows using Stop with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")

// Stop all motion of the arm. It is assumed that the arm stops immediately.
err = myArm.Stop(context.Background(), nil)

type AlwaysRebuild added in v0.2.36

type AlwaysRebuild struct{}

AlwaysRebuild is to be embedded by any resource that must always rebuild and not reconfigure.

func (AlwaysRebuild) Reconfigure added in v0.2.36

func (a AlwaysRebuild) Reconfigure(ctx context.Context, deps Dependencies, conf Config) error

Reconfigure always returns a must rebuild error.

type AssociatedConfig added in v0.24.0

type AssociatedConfig interface {
	// Equals is a function that describes if an AssociatedConfig is the same as another
	Equals(AssociatedConfig) bool

	// UpdateResourceNames allows an AssociatedConfig to have its names updated externally.
	UpdateResourceNames(func(n Name) Name)

	// Link associates an AssociatedConfig to a specific resource model (e.g. builtin data capture).
	Link(conf *Config)
}

AssociatedConfig defines the contract for a config that is associated with another config.

type AssociatedConfigRegistration added in v0.2.36

type AssociatedConfigRegistration[AssocT AssociatedConfig] struct {
	// AttributeMapConverter is used to convert raw attributes to the resource's native associated config.
	AttributeMapConverter AttributeMapConverter[AssocT]
	// contains filtered or unexported fields
}

An AssociatedConfigRegistration describes how to convert all attributes for a type of resource associated with another resource (e.g. data capture on a resource).

func LookupAssociatedConfigRegistration added in v0.2.36

func LookupAssociatedConfigRegistration(api API) (AssociatedConfigRegistration[AssociatedConfig], bool)

LookupAssociatedConfigRegistration finds the resource association config registration for the given api.

type AssociatedResourceConfig added in v0.2.36

type AssociatedResourceConfig struct {
	API                 API
	Attributes          utils.AttributeMap
	ConvertedAttributes interface{}
	RemoteName          string
}

An AssociatedResourceConfig describes configuration of a resource for an associated resource.

func (AssociatedResourceConfig) MarshalJSON added in v0.2.36

func (assoc AssociatedResourceConfig) MarshalJSON() ([]byte, error)

MarshalJSON marshals JSON from the config.

func (*AssociatedResourceConfig) UnmarshalJSON added in v0.2.36

func (assoc *AssociatedResourceConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals JSON into the config.

type AttributeMapConverter added in v0.2.36

type AttributeMapConverter[ConfigT any] func(attributes utils.AttributeMap) (ConfigT, error)

An AttributeMapConverter converts an attribute map into a native config type for a resource.

type Config added in v0.2.36

type Config struct {
	Name             string
	API              API
	Model            Model
	Frame            *referenceframe.LinkConfig
	DependsOn        []string
	LogConfiguration LogConfig
	Attributes       utils.AttributeMap

	AssociatedResourceConfigs []AssociatedResourceConfig
	AssociatedAttributes      map[Name]AssociatedConfig
	ConvertedAttributes       ConfigValidator
	ImplicitDependsOn         []string
	// contains filtered or unexported fields
}

A Config describes the configuration of a resource.

func NewEmptyConfig added in v0.2.36

func NewEmptyConfig(name Name, model Model) Config

NewEmptyConfig returns a new, empty config for the given name and model.

func (*Config) AdjustPartialNames added in v0.2.36

func (conf *Config) AdjustPartialNames(defaultAPIType string)

AdjustPartialNames assumes this config comes from a place where the resource name, API names, Model names, and associated config type names are partially stored (JSON/Proto/Database) and will fix them up to the builtin values they are intended for.

func (*Config) Dependencies added in v0.2.36

func (conf *Config) Dependencies() []string

Dependencies returns the deduplicated union of user-defined and implicit dependencies.

func (Config) Equals added in v0.2.36

func (conf Config) Equals(other Config) bool

Equals checks if the two configs are deeply equal to each other. Validation related fields and implicit dependencies will be ignored.

func (Config) MarshalJSON added in v0.2.36

func (conf Config) MarshalJSON() ([]byte, error)

MarshalJSON marshals JSON from the config.

func (*Config) ResourceName added in v0.2.36

func (conf *Config) ResourceName() Name

ResourceName returns the ResourceName for the component.

func (*Config) String added in v0.2.36

func (conf *Config) String() string

String returns a verbose representation of the config.

func (*Config) UnmarshalJSON added in v0.2.36

func (conf *Config) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals JSON into the config.

func (*Config) Validate added in v0.2.36

func (conf *Config) Validate(path, defaultAPIType string) ([]string, error)

Validate ensures all parts of the config are valid and returns dependencies.

type ConfigValidator added in v0.2.36

type ConfigValidator interface {
	Validate(path string) ([]string, error)
}

A ConfigValidator validates a configuration and also returns dependencies that were implicitly discovered.

type Create added in v0.2.36

type Create[ResourceT Resource] func(
	ctx context.Context,
	deps Dependencies,
	conf Config,
	logger logging.Logger,
) (ResourceT, error)

A Create creates a resource (component/service) from a collection of dependencies and a given config.

type CreateRPCClient added in v0.2.36

type CreateRPCClient[ResourceT Resource] func(
	ctx context.Context,
	conn rpc.ClientConn,
	remoteName string,
	name Name,
	logger logging.Logger,
) (ResourceT, error)

A CreateRPCClient will create the client for the resource.

type CreateStatus added in v0.2.36

type CreateStatus[ResourceT Resource] func(ctx context.Context, res ResourceT) (interface{}, error)

CreateStatus creates a status from a given resource. The return type is expected to be comprised of string keys (or it should be possible to decompose it into string keys) and values comprised of primitives, list of primitives, maps with string keys (or at least can be decomposed into one), or lists of the aforementioned type of maps. Results with other types of data are not guaranteed.

type Dependencies added in v0.2.36

type Dependencies map[Name]Resource

Dependencies are a set of resources that a resource requires for reconfiguration.

func (Dependencies) Lookup added in v0.2.36

func (d Dependencies) Lookup(name Name) (Resource, error)

Lookup searches for a given dependency by name.

type DependencyNotReadyError added in v0.2.36

type DependencyNotReadyError struct {
	Name   string
	Reason error
}

A DependencyNotReadyError is used whenever we reference a dependency that has not been constructed and registered yet.

func (*DependencyNotReadyError) Error added in v0.2.36

func (e *DependencyNotReadyError) Error() string

func (*DependencyNotReadyError) PrettyPrint added in v0.6.0

func (e *DependencyNotReadyError) PrettyPrint() string

PrettyPrint returns a formatted string representing a `DependencyNotReadyError` error. This can be useful as a `DependencyNotReadyError` often wraps a series of lower level `DependencyNotReadyError` errors.

type DeprecatedCreateWithRobot added in v0.2.36

type DeprecatedCreateWithRobot[ResourceT Resource] func(
	ctx context.Context,

	r any,
	conf Config,
	logger logging.Logger,
) (ResourceT, error)

A DeprecatedCreateWithRobot creates a resource from a robot and a given config.

type DiscoverError added in v0.2.36

type DiscoverError struct {
	Query DiscoveryQuery
}

DiscoverError indicates that a Discover function has returned an error.

func (*DiscoverError) Error added in v0.2.36

func (e *DiscoverError) Error() string

type Discovery added in v0.2.36

type Discovery struct {
	Query   DiscoveryQuery
	Results interface{}
}

Discovery holds a Query and a corresponding discovered component configuration. A discovered component configuration can be comprised of primitives, a list of primitives, maps with string keys (or at least can be decomposed into one), or lists of the forementioned type of maps. Results with other types of data are not guaranteed.

type DiscoveryFunc added in v0.2.36

type DiscoveryFunc func(ctx context.Context, logger logging.Logger) (interface{}, error)

DiscoveryFunc is a function that discovers component configurations.

type DiscoveryQuery added in v0.2.36

type DiscoveryQuery struct {
	API   API
	Model Model
}

DiscoveryQuery is a tuple of API and model used to lookup discovery functions.

func NewDiscoveryQuery added in v0.2.36

func NewDiscoveryQuery(api API, model Model) DiscoveryQuery

NewDiscoveryQuery returns a discovery query for a given API and model.

type FieldRequiredError added in v0.15.0

type FieldRequiredError struct {
	Path  string
	Field string
}

FieldRequiredError describes a missing field on a config object.

func (FieldRequiredError) Error added in v0.15.0

func (fre FieldRequiredError) Error() string

func (FieldRequiredError) String added in v0.15.0

func (fre FieldRequiredError) String() string

type GetSnapshotInfo added in v0.23.0

type GetSnapshotInfo struct {
	Snapshot Snapshot
	Index    int
	Count    int
}

GetSnapshotInfo contains a Snapshot string along with metadata about the snapshot collection.

type Graph

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

Graph The Graph maintains a collection of resources and their dependencies between each other.

func NewGraph

func NewGraph() *Graph

NewGraph creates a new resource graph.

func (*Graph) AddChild added in v0.2.36

func (g *Graph) AddChild(child, parent Name) error

AddChild add a dependency to a parent, create the parent if it doesn't exists yet.

func (*Graph) AddNode

func (g *Graph) AddNode(node Name, nodeVal *GraphNode) error

AddNode adds a node to the graph. Once added, the graph owns the node and to access it further, use Node.

func (*Graph) Clone

func (g *Graph) Clone() *Graph

Clone deep copy of the resource graph.

func (*Graph) CopyNodeAndChildren

func (g *Graph) CopyNodeAndChildren(node Name, origin *Graph) error

CopyNodeAndChildren adds a Node and it's children from another graph.

func (*Graph) CurrLogicalClockValue added in v0.12.0

func (g *Graph) CurrLogicalClockValue() int64

CurrLogicalClockValue returns current the logical clock value.

func (*Graph) ExportDot added in v0.20.0

func (g *Graph) ExportDot() (string, error)

ExportDot exports the resource graph as a DOT representation for visualization. DOT reference: https://graphviz.org/doc/info/lang.html. This function will output the exact same string given the same input resource graph. If not called inside a resourceGraphLock, there is a chance of the graph changing as the snapshot is being taken.

func (*Graph) FindNodesByAPI added in v0.2.36

func (g *Graph) FindNodesByAPI(api API) []Name

FindNodesByAPI finds nodes with the given API.

func (*Graph) FindNodesByShortNameAndAPI added in v0.2.36

func (g *Graph) FindNodesByShortNameAndAPI(name Name) []Name

FindNodesByShortNameAndAPI will look for resources matching both the API and the name.

func (*Graph) GetAllChildrenOf

func (g *Graph) GetAllChildrenOf(node Name) []Name

GetAllChildrenOf returns all direct children of a node.

func (*Graph) GetAllParentsOf

func (g *Graph) GetAllParentsOf(node Name) []Name

GetAllParentsOf returns all parents of a given node.

func (*Graph) IsNodeDependingOn

func (g *Graph) IsNodeDependingOn(node, child Name) bool

IsNodeDependingOn returns true if child is depending on node.

func (*Graph) MarkForRemoval added in v0.2.36

func (g *Graph) MarkForRemoval(toMark *Graph)

MarkForRemoval marks the given graph for removal at a later point by RemoveMarked.

func (*Graph) MergeAdd

func (g *Graph) MergeAdd(toAdd *Graph) error

MergeAdd merges two Graphs, if a node exists in both graphs, then it is silently replaced.

func (*Graph) Names

func (g *Graph) Names() []Name

Names returns the all resource graph names.

func (*Graph) Node

func (g *Graph) Node(node Name) (*GraphNode, bool)

Node returns the node named name.

func (*Graph) RemoveChild added in v0.2.36

func (g *Graph) RemoveChild(child, parent Name)

RemoveChild unlink a child from its parent.

func (*Graph) RemoveMarked added in v0.2.36

func (g *Graph) RemoveMarked() []Resource

RemoveMarked removes previously marked nodes from the graph and returns all the resources removed that should now be closed by the caller.

func (*Graph) ReplaceNodesParents

func (g *Graph) ReplaceNodesParents(node Name, other *Graph) error

ReplaceNodesParents replaces all parent of a given node with the parents of the other graph.

func (*Graph) ResolveDependencies added in v0.2.36

func (g *Graph) ResolveDependencies(logger logging.Logger) error

ResolveDependencies attempts to link up unresolved dependencies after new changes to the graph.

func (*Graph) ReverseTopologicalSort

func (g *Graph) ReverseTopologicalSort() []Name

ReverseTopologicalSort returns an array of nodes' Name ordered by most edges first. This can also be seen as being ordered where each name has no prior name depending on it.

func (*Graph) ReverseTopologicalSortInLevels added in v0.28.0

func (g *Graph) ReverseTopologicalSortInLevels() [][]Name

ReverseTopologicalSortInLevels returns a slice of node Name groups, ordered such that all node names only depend on node names in a prior group.

func (*Graph) Status added in v0.35.0

func (g *Graph) Status() []Status

Status returns a slice of all graph node statuses.

func (*Graph) SubGraphFrom

func (g *Graph) SubGraphFrom(node Name) (*Graph, error)

SubGraphFrom returns a Sub-Graph containing all linked dependencies starting with node Name.

func (*Graph) TopologicalSort

func (g *Graph) TopologicalSort() []Name

TopologicalSort returns an array of nodes' Name ordered by fewest edges first. This can also be seen as being ordered where each name has no subsequent name depending on it.

func (*Graph) TopologicalSortInLevels added in v0.2.36

func (g *Graph) TopologicalSortInLevels() [][]Name

TopologicalSortInLevels returns an array of array of nodes' Name ordered by fewest edges first. This can also be seen as being ordered where each name has no subsequent name depending on it.

type GraphNode added in v0.2.36

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

A GraphNode contains the current state of a resource. Based on these states, the underlying Resource may or may not be available. Additionally, the node can be informed that the resource either needs to be updated or eventually removed. During its life, errors may be set on the node to indicate that the resource is no longer available to external users.

func NewConfiguredGraphNode added in v0.2.36

func NewConfiguredGraphNode(config Config, res Resource, resModel Model) *GraphNode

NewConfiguredGraphNode returns a node that is already configured with the supplied config and resource.

func NewUnconfiguredGraphNode added in v0.2.36

func NewUnconfiguredGraphNode(config Config, dependencies []string) *GraphNode

NewUnconfiguredGraphNode returns a node that contains enough information to construct the underlying resource.

func NewUninitializedNode added in v0.2.36

func NewUninitializedNode() *GraphNode

NewUninitializedNode returns a node that is brand new and not yet initialized.

func (*GraphNode) Close added in v0.2.36

func (w *GraphNode) Close(ctx context.Context) error

Close closes the underlying resource of this node.

func (*GraphNode) Config added in v0.2.36

func (w *GraphNode) Config() Config

Config returns the current config that this resource is using. This value should only be assumed to be associated with the current resource.

func (*GraphNode) HasResource added in v0.2.36

func (w *GraphNode) HasResource() bool

HasResource returns if calling Resource would result in no error.

func (*GraphNode) InitializeLogger added in v0.20.0

func (w *GraphNode) InitializeLogger(parent logging.Logger, subname string, level logging.Level)

InitializeLogger initializes the logger object associated with this resource node.

func (*GraphNode) IsUninitialized added in v0.2.36

func (w *GraphNode) IsUninitialized() bool

IsUninitialized returns if this resource is in an uninitialized state.

func (*GraphNode) LastReconfigured added in v0.12.0

func (w *GraphNode) LastReconfigured() *time.Time

LastReconfigured returns a pointer to the time at which the resource within this GraphNode was constructed or last reconfigured. It returns nil if the GraphNode is unconfigured.

func (*GraphNode) LogAndSetLastError added in v0.15.0

func (w *GraphNode) LogAndSetLastError(err error, args ...any)

LogAndSetLastError logs and sets the latest error on this node. This will cause the resource to become unavailable to external users of the graph. The resource manager may still access the underlying resource via UnsafeResource.

The additional `args` should come in key/value pairs for structured logging.

func (*GraphNode) Logger added in v0.20.0

func (w *GraphNode) Logger() logging.Logger

Logger returns the logger object associated with this resource node. This is expected to be the logger passed into the `Constructor` when registering resources.

func (*GraphNode) MarkForRemoval added in v0.2.36

func (w *GraphNode) MarkForRemoval()

MarkForRemoval marks this node for removal at a later time.

func (*GraphNode) MarkedForRemoval added in v0.2.36

func (w *GraphNode) MarkedForRemoval() bool

MarkedForRemoval returns if this node is marked for removal.

func (*GraphNode) NeedsReconfigure added in v0.2.36

func (w *GraphNode) NeedsReconfigure() bool

NeedsReconfigure returns whether or not this node needs reconfiguration performed on its underlying resource.

func (*GraphNode) Resource added in v0.2.36

func (w *GraphNode) Resource() (Resource, error)

Resource returns the underlying resource if it is not pending removal, has no error on it, and is initialized.

func (*GraphNode) ResourceModel added in v0.2.36

func (w *GraphNode) ResourceModel() Model

ResourceModel returns the current model that this resource is. This value should only be assumed to be associated with the current resource.

func (*GraphNode) ResourceStatus added in v0.35.0

func (w *GraphNode) ResourceStatus() Status

ResourceStatus returns the current Status.

func (*GraphNode) SetLogLevel added in v0.15.0

func (w *GraphNode) SetLogLevel(level logging.Level)

SetLogLevel changes the log level of the logger (if available). Processing configs is the main entry point for changing log levels. Which will affect whether models making log calls are suppressed or not.

func (*GraphNode) SetNeedsUpdate added in v0.2.36

func (w *GraphNode) SetNeedsUpdate()

SetNeedsUpdate is used to inform the node that it should reconfigure itself with the same config in order to process dependency updates. If the node was previously marked for removal, this makes no changes.

func (*GraphNode) SetNewConfig added in v0.2.36

func (w *GraphNode) SetNewConfig(newConfig Config, dependencies []string)

SetNewConfig is used to inform the node that it has been modified and requires a reconfiguration. If the node was previously marked for removal, this unmarks it.

func (*GraphNode) State added in v0.30.0

func (w *GraphNode) State() NodeState

State return the current lifecycle state for a resource node.

func (*GraphNode) SwapResource added in v0.2.36

func (w *GraphNode) SwapResource(newRes Resource, newModel Model)

SwapResource emplaces the new resource. It may be the same as before and expects the caller to close the old one. This is considered to be a working resource and as such we unmark it for removal and indicate it no longer needs reconfiguration. SwapResource also increments the graphLogicalClock and sets updatedAt for this GraphNode to the new value.

func (*GraphNode) TransitionedAt added in v0.30.0

func (w *GraphNode) TransitionedAt() time.Time

TransitionedAt return the timestamp of when resource entered its current lifecycle state.

func (*GraphNode) UnresolvedDependencies added in v0.2.36

func (w *GraphNode) UnresolvedDependencies() []string

UnresolvedDependencies returns the set of names that are yet to be resolved as dependencies for the node.

func (*GraphNode) UnsafeResource added in v0.2.36

func (w *GraphNode) UnsafeResource() (Resource, error)

UnsafeResource always returns the underlying resource, if initialized, even if it is in an error state. This should only be called during reconfiguration.

func (*GraphNode) UnsetResource added in v0.10.0

func (w *GraphNode) UnsetResource()

UnsetResource unsets the current resource. This function does not clean up or close the resource and should be used carefully.

func (*GraphNode) UpdatePendingRevision added in v0.36.0

func (w *GraphNode) UpdatePendingRevision(revision string)

UpdatePendingRevision sets the next revision to be applied once the node is in a NodeStateReady state.

func (*GraphNode) UpdateRevision added in v0.36.0

func (w *GraphNode) UpdateRevision(revision string)

UpdateRevision updates the node config revision if the node is in a NodeStateReady state.

func (*GraphNode) UpdatedAt added in v0.2.36

func (w *GraphNode) UpdatedAt() int64

UpdatedAt returns the value of the logical clock when SwapResource was last called on this GraphNode (the resource was last updated). It's only used for tests.

type InterfaceMatcher added in v0.15.0

type InterfaceMatcher struct {
	Interface interface{}
}

InterfaceMatcher matches resources that fulfill the given interface.

func (InterfaceMatcher) IsMatch added in v0.15.0

func (im InterfaceMatcher) IsMatch(r Resource) bool

IsMatch returns true if the given resource fulfills the InterfaceMatcher's Interface.

type LogConfig added in v0.11.0

type LogConfig struct {
	Level logging.Level `json:"level"`
}

A LogConfig describes the LogConfig config object.

type Matcher added in v0.15.0

type Matcher interface {
	IsMatch(Resource) bool
}

Matcher describes whether a given resource matches its specified criteria.

type Model added in v0.2.8

type Model struct {
	Family ModelFamily `json:""`
	Name   string      `json:"name"`
}

Model represents an individual model within a family. It consists of a Namespace, Family, and Name.

func NewModel added in v0.2.8

func NewModel(namespace, family, modelName string) Model

NewModel return a new model from a triplet like acme:demo:mygizmo.

func NewModelFromString added in v0.2.8

func NewModelFromString(modelStr string) (Model, error)

NewModelFromString creates a new Name based on a fully qualified resource name string passed in.

func (Model) MarshalJSON added in v0.2.36

func (m Model) MarshalJSON() ([]byte, error)

MarshalJSON marshals the model name in its triplet form.

func (Model) String added in v0.2.8

func (m Model) String() string

String returns the resource model name in its triplet form.

func (*Model) UnmarshalJSON added in v0.2.8

func (m *Model) UnmarshalJSON(data []byte) error

UnmarshalJSON parses namespace:family:modelname strings to the full Model{} struct.

func (Model) Validate added in v0.2.8

func (m Model) Validate() error

Validate ensures that important fields exist and are valid.

type ModelFamily added in v0.2.8

type ModelFamily struct {
	Namespace ModelNamespace `json:"namespace"`
	Name      string         `json:"model_family"`
}

ModelFamily is a family of related models.

func NewModelFamily added in v0.2.8

func NewModelFamily(namespace, family string) ModelFamily

NewModelFamily returns a new family from the given namespace and family.

func (ModelFamily) String added in v0.2.8

func (f ModelFamily) String() string

String returns the model family string for the resource.

func (ModelFamily) Validate added in v0.2.8

func (f ModelFamily) Validate() error

Validate ensures that important fields exist and are valid.

func (ModelFamily) WithModel added in v0.2.36

func (f ModelFamily) WithModel(name string) Model

WithModel returns a new model with the given name.

type ModelNamespace added in v0.2.36

type ModelNamespace string

ModelNamespace identifies the namespaces resource models can live in.

func (ModelNamespace) WithFamily added in v0.2.36

func (n ModelNamespace) WithFamily(name string) ModelFamily

WithFamily returns a new model family with the given name.

type Name

type Name struct {
	API    API
	Remote string
	Name   string
}

Name represents a known component/service representation of a robot.

func DefaultServices

func DefaultServices() []Name

DefaultServices returns all servies that will be constructed by default if not specified in a config.

func NewFromString

func NewFromString(resourceName string) (Name, error)

NewFromString creates a new Name based on a fully qualified resource name string passed in.

func NewName

func NewName(api API, name string) Name

NewName creates a new resource Name.

func RemoveRemoteName added in v0.1.0

func RemoveRemoteName(n Name) Name

RemoveRemoteName returns a new name with remote removed.

func (Name) AsNamed added in v0.2.36

func (n Name) AsNamed() Named

AsNamed is a helper to let this name return itself as a basic resource that does nothing.

func (Name) ContainsRemoteNames

func (n Name) ContainsRemoteNames() bool

ContainsRemoteNames return true if the resource is a remote resource.

func (Name) PopRemote

func (n Name) PopRemote() Name

PopRemote pop the first remote from a Name (if any) and returns the new Name.

func (Name) PrependRemote

func (n Name) PrependRemote(remoteName string) Name

PrependRemote returns a Name with a remote prepended.

func (Name) SDPTrackName added in v0.30.0

func (n Name) SDPTrackName() string

SDPTrackName returns a valid SDP video/audio track name as defined in RFC 4566 (https://www.rfc-editor.org/rfc/rfc4566) where track names should not include colons.

func (Name) ShortName

func (n Name) ShortName() string

ShortName returns the short name on Name n in the form of <remote>:<name>.

func (Name) String

func (n Name) String() string

String returns the fully qualified name for the resource.

func (*Name) UnmarshalJSON added in v0.2.36

func (n *Name) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals a resource name from a string.

func (Name) Validate

func (n Name) Validate() error

Validate ensures that important fields exist and are valid.

type Named added in v0.2.36

type Named interface {
	Name() Name
	DoCommand(ctx context.Context, cmd map[string]interface{}) (map[string]interface{}, error)
}

Named is to be embedded by any resource that just needs to return a name.

type NoNativeConfig added in v0.2.36

type NoNativeConfig struct {
	TriviallyValidateConfig
}

NoNativeConfig is used by types that have no significant native config.

type NodeState added in v0.30.0

type NodeState uint8

NodeState captures the configuration lifecycle state of a resource node.

const (
	// NodeStateUnknown represents an unknown state.
	NodeStateUnknown NodeState = iota

	// NodeStateUnconfigured denotes a newly created resource.
	NodeStateUnconfigured

	// NodeStateConfiguring denotes a resource is being configured.
	NodeStateConfiguring

	// NodeStateReady denotes a resource that has been configured and is healthy.
	NodeStateReady

	// NodeStateRemoving denotes a resource is being removed from the resource graph.
	NodeStateRemoving

	// NodeStateUnhealthy denotes a resource is unhealthy.
	NodeStateUnhealthy
)

func (NodeState) String added in v0.30.0

func (i NodeState) String() string

type RPCAPI added in v0.2.36

type RPCAPI struct {
	API          API
	ProtoSvcName string
	Desc         *desc.ServiceDescriptor
}

An RPCAPI provides RPC information about a particular API.

type Registration added in v0.2.36

type Registration[ResourceT Resource, ConfigT any] struct {
	Constructor Create[ResourceT]

	// AttributeMapConverter is used to convert raw attributes to the resource's native config.
	AttributeMapConverter AttributeMapConverter[ConfigT]

	// TODO(RSDK-418): remove this legacy constructor once all resources that use it no longer need to receive the entire robot.
	DeprecatedRobotConstructor DeprecatedCreateWithRobot[ResourceT]

	// WeakDependencies is a list of Matchers that find resources on the robot that fit the criteria they are looking for
	// and register them as dependencies on the resource being registered.
	// NOTE: This is currently an experimental feature and subject to change.
	WeakDependencies []Matcher

	// Discover looks around for information about this specific model.
	Discover DiscoveryFunc
	// contains filtered or unexported fields
}

A Registration stores construction info for a resource (component/service). A single constructor is mandatory.

func LookupRegistration added in v0.2.36

func LookupRegistration(api API, model Model) (Registration[Resource, ConfigValidator], bool)

LookupRegistration looks up a creator by the given api and model. nil is returned if there is no creator registered.

func (Registration[ResourceT, ConfigT]) ConfigReflectType added in v0.2.36

func (r Registration[ResourceT, ConfigT]) ConfigReflectType() reflect.Type

ConfigReflectType returns the reflective resource config type.

type Resource added in v0.2.36

type Resource interface {
	// Get the Name of the resource.
	Name() Name

	// Reconfigure must reconfigure the resource atomically and in place. If this
	// cannot be guaranteed, then usage of AlwaysRebuild or TriviallyReconfigurable
	// is permissible.
	Reconfigure(ctx context.Context, deps Dependencies, conf Config) error

	// DoCommand sends/receives arbitrary data
	DoCommand(ctx context.Context, cmd map[string]interface{}) (map[string]interface{}, error)

	// Close must safely shut down the resource and prevent further use.
	// Close must be idempotent.
	// Later reconfiguration may allow a resource to be "open" again.
	Close(ctx context.Context) error
}

A Resource is the fundamental building block of a robot; it is either a component or a service that is accessible through robot. In general, some other specific type that is the component or service implements this interface. All resources must know their own name and be able to reconfigure themselves (or signal that they must be rebuilt). Resources that fail to reconfigure or rebuild may be closed and must return errors when in a closed state for all non Close methods.

Name example:

// Get the Name of an arm component.
myArmName := myArm.Name()

DoCommand example:

// This example shows using DoCommand with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")

command := map[string]interface{}{"cmd": "test", "data1": 500}
result, err := myArm.DoCommand(context.Background(), command)

Close example:

// This example shows using Close with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")

err = myArm.Close(ctx)

func NewCloseOnlyResource added in v0.2.36

func NewCloseOnlyResource(name Name, closeFunc func(ctx context.Context) error) Resource

NewCloseOnlyResource makes a new resource that needs to be closed and does not need the actual resource exposed but only its close function.

type ResponseMetadata added in v0.7.3

type ResponseMetadata struct {
	CapturedAt time.Time
}

ResponseMetadata contains extra info associated with a Resource's standard response.

func ResponseMetadataFromProto added in v0.7.3

func ResponseMetadataFromProto(proto *commonpb.ResponseMetadata) ResponseMetadata

ResponseMetadataFromProto turns the protobuf message into a ResponseMetadata struct.

func (ResponseMetadata) AsProto added in v0.7.3

AsProto turns the ResponseMetadata struct into a protobuf message.

type Sensor added in v0.12.0

type Sensor interface {
	// Readings return data specific to the type of sensor and can be of any type.
	Readings(ctx context.Context, extra map[string]interface{}) (map[string]interface{}, error)
}

A Sensor represents a general purpose sensor that can give arbitrary readings of all readings that it is sensing. For more information, see the sensor component docs.

Readings example:

// Get the readings provided by the sensor.
readings, err := mySensor.Readings(context.Background(), nil)

type Shaped added in v0.2.50

type Shaped interface {
	// Geometries returns the list of geometries associated with the resource, in any order. The poses of the geometries reflect their
	// current location relative to the frame of the resource.
	Geometries(context.Context, map[string]interface{}) ([]spatialmath.Geometry, error)
}

Shaped is any resource that can have geometries.

Geometries example:

// This example shows using Geometries with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")

geometries, err := myArm.Geometries(context.Background(), nil)

if len(geometries) > 0 {
   // Get the center of the first geometry
   elem := geometries[0]
   fmt.Println("Pose of the first geometry's center point:", elem.center)
}

type Snapshot added in v0.23.0

type Snapshot struct {
	Dot       string
	CreatedAt time.Time
}

Snapshot contains a DOT snapshot string along with capture metadata.

type Status added in v0.35.0

type Status struct {
	Name        Name
	State       NodeState
	LastUpdated time.Time
	Revision    string

	// Error contains any errors on the resource if it currently unhealthy.
	// This field will be nil if the resource is not in the [NodeStateUnhealthy] state.
	Error error
}

Status encapsulates a resource name along with state transition metadata.

type SubtypeMatcher added in v0.15.0

type SubtypeMatcher struct {
	Subtype string
}

SubtypeMatcher matches resources that have the given Subtype.

func (SubtypeMatcher) IsMatch added in v0.15.0

func (sm SubtypeMatcher) IsMatch(r Resource) bool

IsMatch returns true if the given resource has a Subtype that matches the SubtypeMatcher's Subtype.

type TriviallyCloseable added in v0.2.36

type TriviallyCloseable struct{}

TriviallyCloseable is to be embedded by any resource that does not care about handling Closes. When is used, it is assumed that the resource does not need to return errors when future non-Close methods are called.

func (TriviallyCloseable) Close added in v0.2.36

func (t TriviallyCloseable) Close(ctx context.Context) error

Close always returns no error.

type TriviallyReconfigurable added in v0.2.36

type TriviallyReconfigurable struct{}

TriviallyReconfigurable is to be embedded by any resource that does not care about changes to its config or dependencies.

func (TriviallyReconfigurable) Reconfigure added in v0.2.36

func (t TriviallyReconfigurable) Reconfigure(ctx context.Context, deps Dependencies, conf Config) error

Reconfigure always succeeds.

type TriviallyValidateConfig added in v0.2.36

type TriviallyValidateConfig struct{}

TriviallyValidateConfig is to be embedded by any resource config that does not care about its validation or implicit dependencies; use this carefully.

func (TriviallyValidateConfig) Validate added in v0.2.36

func (t TriviallyValidateConfig) Validate(path string) ([]string, error)

Validate always succeeds and produces no dependencies.

type TypeMatcher added in v0.15.0

type TypeMatcher struct {
	Type string
}

TypeMatcher matches resources that have the given Type.

func (TypeMatcher) IsMatch added in v0.15.0

func (tm TypeMatcher) IsMatch(r Resource) bool

IsMatch returns true if the given resource has a Type that matches the TypeMatcher's Type.

type Visualizer added in v0.23.0

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

Visualizer stores a history resource graph DOT snapshots.

func (*Visualizer) Count added in v0.23.0

func (viz *Visualizer) Count() int

Count returns the number of snapshots currents stored.

func (*Visualizer) GetSnapshot added in v0.23.0

func (viz *Visualizer) GetSnapshot(index int) (GetSnapshotInfo, error)

GetSnapshot returns a DOT snapshot at a given index, where index 0 is the latest snapshot.

func (*Visualizer) SaveSnapshot added in v0.23.0

func (viz *Visualizer) SaveSnapshot(g *Graph) error

SaveSnapshot takes a DOT snapshot of a resource graph.

Jump to

Keyboard shortcuts

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