capabilities

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2025 License: MIT Imports: 15 Imported by: 42

Documentation

Index

Constants

View Source
const (
	DefaultRegistrationRefresh   = 30 * time.Second
	DefaultRegistrationExpiry    = 2 * time.Minute
	DefaultMessageExpiry         = 2 * time.Minute
	DefaultBatchSize             = 100
	DefaultBatchCollectionPeriod = 100 * time.Millisecond
)

Variables

View Source
var (
	PromExecutionTimeMS = promauto.NewHistogramVec(
		prometheus.HistogramOpts{
			Name: "capability_execution_time_ms",
			Help: "Metric representing the execution time in milliseconds",
		},
		[]string{"keystone_type", "id"},
	)
	PromTaskRunSuccessCount = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "capability_runs_count",
			Help: "Metric representing the number of runs completed successfully",
		},
		[]string{"keystone_type", "id"},
	)
	PromTaskRunFaultCount = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "capability_runs_fault_count",
			Help: "Metric representing the number of runs with an application fault",
		},
		[]string{"keystone_type", "id"},
	)
	PromTaskRunInvalidCount = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "capability_runs_invalid_count",
			Help: "Metric representing the number of runs with an application fault",
		},
		[]string{"keystone_type", "id"},
	)
	PromTaskRunUnauthorizedCount = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "capability_runs_unauthorized_count",
			Help: "Metric representing the number of runs with an application fault",
		},
		[]string{"keystone_type", "id"},
	)
	PromTaskRunNoResourceCount = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "capability_runs_no_resource_count",
			Help: "Metric representing the number of runs with an application fault",
		},
		[]string{"keystone_type", "id"},
	)
)
View Source
var ErrNeitherValueNorAny = errors.New("neither value nor any provided")
View Source
var ErrStopExecution = &errStopExecution{}

Functions

func FromValueOrAny added in v0.7.1

func FromValueOrAny(value values.Value, any *anypb.Any, into proto.Message) (bool, error)

FromValueOrAny extracts the value from either a values.Value or an anypb.Any, returning true if the value was migrated to use pbany.Any.

func IsRemoteReportableErrorMessage added in v0.7.1

func IsRemoteReportableErrorMessage(message string) bool

func PrePendRemoteReportableErrorIdentifier added in v0.7.1

func PrePendRemoteReportableErrorIdentifier(errorMessage string) string

func RegisterTrigger added in v0.7.1

func RegisterTrigger[I, O proto.Message](
	ctx context.Context,
	stop <-chan struct{},
	triggerType string,
	request TriggerRegistrationRequest,
	message I,
	fn func(context.Context, string, RequestMetadata, I) (<-chan TriggerAndId[O], error),
) (<-chan TriggerResponse, error)

RegisterTrigger is a helper function for capabilities that allows them to use their native types for input, config, and response while adhering to the standard capability interface.

func RemoveRemoteReportableErrorIdentifier added in v0.7.1

func RemoveRemoteReportableErrorIdentifier(message string) string

func SetResponse added in v0.7.1

func SetResponse(response *CapabilityResponse, migrated bool, value proto.Message) error

SetResponse sets the response payload based on whether it was migrated to use pbany.Any values.

func UnwrapRequest added in v0.7.1

func UnwrapRequest(request CapabilityRequest, config proto.Message, value proto.Message) (bool, error)

UnwrapRequest extracts the input and config from the request, returning true if they were migrated to use pbany.Any values.

func UnwrapResponse added in v0.7.1

func UnwrapResponse(response CapabilityResponse, value proto.Message) (bool, error)

UnwrapResponse extracts the response, returning true if they were migrated to use pbany.Any values.

Types

type ActionCapability deprecated

type ActionCapability = ExecutableCapability

Deprecated: use ExecutableCapability instead.

type BaseCapability

type BaseCapability interface {
	Info(ctx context.Context) (CapabilityInfo, error)
}

BaseCapability interface needs to be implemented by all capability types. Capability interfaces are intentionally duplicated to allow for an easy change or extension in the future.

type CapabilityConfiguration added in v0.2.2

type CapabilityConfiguration struct {
	DefaultConfig *values.Map
	// RestrictedKeys is a list of keys that can't be provided by users in their
	// configuration; we'll remove these fields before passing them to the capability.
	RestrictedKeys []string
	// RestrictedConfig is configuration that can only be set by us; this
	// takes precedence over any user-provided config.
	RestrictedConfig       *values.Map
	RemoteTriggerConfig    *RemoteTriggerConfig
	RemoteTargetConfig     *RemoteTargetConfig
	RemoteExecutableConfig *RemoteExecutableConfig
}

type CapabilityInfo

type CapabilityInfo struct {
	// The capability ID is a fully qualified identifier for the capability.
	//
	// It takes the form of `{name}:{label1_key}_{labe1_value}:{label2_key}_{label2_value}@{version}`
	//
	// The labels within the ID are ordered alphanumerically.
	ID             string
	CapabilityType CapabilityType
	Description    string
	DON            *DON
	IsLocal        bool
	// SpendTypes denotes the spend types a capability expects to use during an invocation.
	SpendTypes []CapabilitySpendType
}

CapabilityInfo is a struct for the info of a capability.

func MustNewCapabilityInfo

func MustNewCapabilityInfo(
	id string,
	capabilityType CapabilityType,
	description string,
	spendTypes ...CapabilitySpendType,
) CapabilityInfo

MustNewCapabilityInfo returns a new CapabilityInfo, `panic`ing if we could not instantiate a CapabilityInfo.

func MustNewRemoteCapabilityInfo

func MustNewRemoteCapabilityInfo(
	id string,
	capabilityType CapabilityType,
	description string,
	don *DON,
	spendTypes ...CapabilitySpendType,
) CapabilityInfo

MustNewRemoteCapabilityInfo returns a new CapabilityInfo, `panic`ing if we could not instantiate a CapabilityInfo.

func NewCapabilityInfo

func NewCapabilityInfo(
	id string,
	capabilityType CapabilityType,
	description string,
	spendTypes ...CapabilitySpendType,
) (CapabilityInfo, error)

NewCapabilityInfo returns a new CapabilityInfo.

func NewRemoteCapabilityInfo

func NewRemoteCapabilityInfo(
	id string,
	capabilityType CapabilityType,
	description string,
	don *DON,
	spendTypes ...CapabilitySpendType,
) (CapabilityInfo, error)

NewRemoteCapabilityInfo returns a new CapabilityInfo for remote capabilities. This is largely intended for internal use by the registry syncer. Capability developers should use `NewCapabilityInfo` instead as this omits the requirement to pass in the DON Info.

func (CapabilityInfo) Info

Info returns the info of the capability.

func (CapabilityInfo) Version

func (c CapabilityInfo) Version() string

Parse out the version from the ID.

type CapabilityRequest

type CapabilityRequest struct {
	Metadata RequestMetadata

	// Config is used for DAG workflows
	Config *values.Map

	// Inputs is used for DAG workflows
	Inputs *values.Map

	// Payload is used for no DAG workflows
	Payload *anypb.Any

	// ConfigPayload is used for no DAG workflows
	ConfigPayload *anypb.Any

	// The method to call for no DAG workflows
	Method       string
	CapabilityId string
}

CapabilityRequest is a struct for the Execute request of a capability.

type CapabilityResponse

type CapabilityResponse struct {
	// Value is used for DAG workflows
	Value    *values.Map
	Metadata ResponseMetadata

	// Payload is used for no DAG workflows
	Payload *anypb.Any
}

CapabilityResponse is a struct for the Execute response of a capability.

func Execute added in v0.7.1

func Execute[I, C, O proto.Message](
	ctx context.Context,
	request CapabilityRequest,
	input I,
	config C,
	exec func(context.Context, RequestMetadata, I, C) (O, error)) (CapabilityResponse, error)

Execute is a helper function for capabilities that allows them to use their native types for input, config, and response while adhering to the standard capability interface.

type CapabilitySpendType added in v0.7.1

type CapabilitySpendType string

type CapabilityType

type CapabilityType string

CapabilityType is an enum for the type of capability.

const (
	CapabilityTypeUnknown   CapabilityType = "unknown"
	CapabilityTypeTrigger   CapabilityType = "trigger"
	CapabilityTypeAction    CapabilityType = "action"
	CapabilityTypeConsensus CapabilityType = "consensus"
	CapabilityTypeTarget    CapabilityType = "target"

	// CapabilityTypeCombined allows capabilities to offer both trigger and executable types.
	CapabilityTypeCombined CapabilityType = "combined"
)

CapabilityType enum values.

func (CapabilityType) IsValid

func (c CapabilityType) IsValid() error

IsValid checks if the capability type is valid.

type ConsensusCapability deprecated

type ConsensusCapability = ExecutableCapability

Deprecated: use ExecutableCapability instead.

type DON

type DON struct {
	ID               uint32
	ConfigVersion    uint32
	Members          []p2ptypes.PeerID
	F                uint8
	IsPublic         bool
	AcceptsWorkflows bool
}

DON represents a network of connected nodes.

For an example of an empty DON check, see the following link: https://github.com/smartcontractkit/chainlink/blob/develop/core/capabilities/transmission/local_target_capability.go#L31

type Executable added in v0.2.2

type Executable interface {
	RegisterToWorkflow(ctx context.Context, request RegisterToWorkflowRequest) error
	UnregisterFromWorkflow(ctx context.Context, request UnregisterFromWorkflowRequest) error
	Execute(ctx context.Context, request CapabilityRequest) (CapabilityResponse, error)
}

Executable is an interface for executing a capability.

type ExecutableAndTriggerCapability added in v0.7.1

type ExecutableAndTriggerCapability interface {
	TriggerCapability
	ExecutableCapability
}

type ExecutableCapability added in v0.2.2

type ExecutableCapability interface {
	BaseCapability
	Executable
}

ExecutableCapability is the interface implemented by action, consensus and target capabilities. This interface is useful when trying to capture capabilities of varying types.

type MeteringNodeDetail added in v0.6.0

type MeteringNodeDetail struct {
	Peer2PeerID string
	SpendUnit   string
	SpendValue  string
}

type Node

type Node struct {
	PeerID              *p2ptypes.PeerID
	NodeOperatorID      uint32
	Signer              [32]byte
	EncryptionPublicKey [32]byte
	WorkflowDON         DON
	CapabilityDONs      []DON
}

Node contains the node's peer ID and the DONs it is part of. The signer is the Node's onchain public key used for OCR signing, and the encryption public key is the Node's workflow public key. Note the following relationships between the workflow and capability DONs and this node.

There is a 1:0..1 relationship between this node and a workflow DON. This means that this node can be part at most one workflow DON at a time. As a side note, a workflow DON can have multiple nodes.

There is a 1:N relationship between this node and capability DONs, where N is the number of capability DONs. This means that this node can be part of multiple capability DONs at a time.

Although WorkflowDON is a value rather than a pointer, a node can be part of no workflow DON but 0 or more capability DONs. You can assert this by checking for zero values in the WorkflowDON field. See https://github.com/smartcontractkit/chainlink/blob/develop/core/capabilities/transmission/local_target_capability.go#L31 for an example.

type OCRAttributedOnchainSignature added in v0.6.0

type OCRAttributedOnchainSignature struct {
	Signature []byte
	Signer    uint32 // oracle ID (0,1,...,N-1)
}

type OCRTriggerEvent added in v0.6.0

type OCRTriggerEvent struct {
	ConfigDigest []byte
	SeqNr        uint64
	Report       []byte // marshaled pb.OCRTriggerReport
	Sigs         []OCRAttributedOnchainSignature
}

func (*OCRTriggerEvent) FromMap added in v0.6.0

func (e *OCRTriggerEvent) FromMap(m *values.Map) error

FromMap converts a map to an OCRTriggerEvent. This is useful deserialization purposes with the TriggerEvent struct.

func (*OCRTriggerEvent) ToMap added in v0.6.0

func (e *OCRTriggerEvent) ToMap() (*values.Map, error)

ToMap converts the OCRTriggerEvent to a map. This is useful serialization purposes with the TriggerEvent struct.

type RegisterToWorkflowRequest

type RegisterToWorkflowRequest struct {
	Metadata RegistrationMetadata
	Config   *values.Map
}

type RegistrationMetadata

type RegistrationMetadata struct {
	WorkflowID    string
	WorkflowOwner string
	// The step reference ID of the workflow
	ReferenceID string
}

type RemoteExecutableConfig added in v0.4.0

type RemoteExecutableConfig struct {
	RequestHashExcludedAttributes []string
	RegistrationRefresh           time.Duration
	RegistrationExpiry            time.Duration
}

func (*RemoteExecutableConfig) ApplyDefaults added in v0.4.1

func (c *RemoteExecutableConfig) ApplyDefaults()

type RemoteReportableError added in v0.7.1

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

RemoteReportableError wraps an error an is used to indicates that the error does contain any node specific information and is safe to report remotely between nodes.

func NewRemoteReportableError added in v0.7.1

func NewRemoteReportableError(err error) *RemoteReportableError

func (*RemoteReportableError) Error added in v0.7.1

func (e *RemoteReportableError) Error() string

func (*RemoteReportableError) Unwrap added in v0.7.1

func (e *RemoteReportableError) Unwrap() error

Unwrap allows errors.Is and errors.As to work with CustomError.

type RemoteTargetConfig added in v0.2.2

type RemoteTargetConfig struct {
	RequestHashExcludedAttributes []string
}

type RemoteTriggerConfig added in v0.2.2

type RemoteTriggerConfig struct {
	RegistrationRefresh     time.Duration
	RegistrationExpiry      time.Duration
	MinResponsesToAggregate uint32
	MessageExpiry           time.Duration
	MaxBatchSize            uint32
	BatchCollectionPeriod   time.Duration
}

func (*RemoteTriggerConfig) ApplyDefaults added in v0.2.2

func (c *RemoteTriggerConfig) ApplyDefaults()

NOTE: consider splitting this config into values stored in Registry (KS-118) and values defined locally by Capability owners.

type RequestMetadata

type RequestMetadata struct {
	WorkflowID               string
	WorkflowOwner            string
	WorkflowExecutionID      string
	WorkflowName             string
	WorkflowDonID            uint32
	WorkflowDonConfigVersion uint32
	// The step reference ID of the workflow
	ReferenceID string
	// Use DecodedWorkflowName if the human readable name needs to be exposed, such as for logging purposes.
	DecodedWorkflowName string
	// SpendLimits is expected to be an array of tuples of spend type and limit. i.e. CONSENSUS -> 100_000
	SpendLimits []SpendLimit
}

type ResponseMetadata added in v0.6.0

type ResponseMetadata struct {
	Metering []MeteringNodeDetail
}

type SpendLimit added in v0.7.1

type SpendLimit struct {
	SpendType CapabilitySpendType
	Limit     string
}

type TargetCapability deprecated

type TargetCapability = ExecutableCapability

Deprecated: use ExecutableCapability instead.

type TriggerAndId added in v0.7.1

type TriggerAndId[T proto.Message] struct {
	Trigger T
	Id      string
}

type TriggerCapability

type TriggerCapability interface {
	BaseCapability
	TriggerExecutable
}

TriggerCapability interface needs to be implemented by all trigger capabilities.

type TriggerEvent

type TriggerEvent struct {
	// The ID of the trigger capability
	TriggerType string
	// The ID of the trigger event
	ID string
	// Trigger-specific payload for DAG workflows
	Outputs *values.Map

	// Trigger-specific payload for no DAG workflows
	Payload *anypb.Any

	// Deprecated: use Outputs instead
	// TODO: remove after core services are updated (pending https://github.com/smartcontractkit/chainlink/pull/16950)
	OCREvent *OCRTriggerEvent
}

type TriggerExecutable

type TriggerExecutable interface {
	RegisterTrigger(ctx context.Context, request TriggerRegistrationRequest) (<-chan TriggerResponse, error)
	UnregisterTrigger(ctx context.Context, request TriggerRegistrationRequest) error
}

type TriggerRegistrationRequest added in v0.2.2

type TriggerRegistrationRequest struct {
	// TriggerID uniquely identifies the trigger by concatenating
	// the workflow ID and the trigger's index in the spec.
	TriggerID string

	Metadata RequestMetadata

	// Config for DAG workflows
	Config *values.Map

	// Request body for no DAG workflows
	Payload *anypb.Any
	// The method to call for no DAG workflows
	Method string
}

type TriggerResponse added in v0.2.2

type TriggerResponse struct {
	Event TriggerEvent
	Err   error
}

type UnregisterFromWorkflowRequest

type UnregisterFromWorkflowRequest struct {
	Metadata RegistrationMetadata
	Config   *values.Map
}

type Validatable

type Validatable interface {
	// ValidateSchema returns the JSON schema for the capability.
	//
	// This schema includes the configuration, input and output schemas.
	Schema() (string, error)
}

type Validator

type Validator[Config any, Inputs any, Outputs any] struct {
	ValidatorArgs
	// contains filtered or unexported fields
}

A Validator can validate the config, inputs, and outputs of a capability.

The library generates a JSON schema for each of these types to both describe the types in a language-agnostic way and to validate the API boundary of the capability.

To see how to annotate your structs with JSON schema tags, take a look at the jsonschema package.

func NewValidator

func NewValidator[Config any, Inputs any, Outputs any](args ValidatorArgs) Validator[Config, Inputs, Outputs]

func (*Validator[Config, Inputs, Outputs]) ConfigSchema

func (v *Validator[Config, Inputs, Outputs]) ConfigSchema() (string, error)

func (*Validator[Config, Inputs, Outputs]) InputsSchema

func (v *Validator[Config, Inputs, Outputs]) InputsSchema() (string, error)

func (*Validator[Config, Inputs, Outputs]) OutputsSchema

func (v *Validator[Config, Inputs, Outputs]) OutputsSchema() (string, error)

func (*Validator[Config, Inputs, Outputs]) Schema

func (v *Validator[Config, Inputs, Outputs]) Schema() (string, error)

Schema returns the a JSON schema that combines the config, inputs, and outputs into a single schema.

This fully describes the capability's API boundary.

func (*Validator[Config, Inputs, Outputs]) ValidateConfig

func (v *Validator[Config, Inputs, Outputs]) ValidateConfig(config *values.Map) (*Config, error)

func (*Validator[Config, Inputs, Outputs]) ValidateInputs

func (v *Validator[Config, Inputs, Outputs]) ValidateInputs(inputs *values.Map) (*Inputs, error)

func (*Validator[Config, Inputs, Outputs]) ValidateOutputs

func (v *Validator[Config, Inputs, Outputs]) ValidateOutputs(outputs *values.Map) (*Outputs, error)

type ValidatorArgs

type ValidatorArgs struct {
	Info CapabilityInfo

	// You can customize each one of the reflectors
	// or leave them nil to use the default reflector.
	//
	// You can also override the default reflector by setting
	// the DefaultReflector field.
	DefaultReflector *jsonschema.Reflector

	SchemaReflector  *jsonschema.Reflector
	ConfigReflector  *jsonschema.Reflector
	InputsReflector  *jsonschema.Reflector
	OutputsReflector *jsonschema.Reflector
}

Jump to

Keyboard shortcuts

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