agrirouter

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

agrirouter Go SDK

Go SDK for agrirouter is a library that provides a shared interface to access functionality common for agrirouter applications.

🚧🚧🚧 Currently this is ONLY intended to be used internally by agrirouter outbound integrations! 🚧🚧🚧

🚧🚧🚧 External use is NOT SUPPORTED 🚧🚧🚧

Development

Following instructions are for developers working on this SDK.

Prerequisites
  • Go 1.23 or later
  • bash or compatible shell
  • Docker
  • make (optional, for convenience)
Install git hooks

Run this command:

git config core.hooksPath .githooks

This will set up git hooks to run minimal set of checks on commit and push. These would not require make.

Code Generation

Script tools/oapi/generate.sh would generate Go code from the OpenAPI specification files.

It uses oapi-codegen tool using dockerized installation, hence it only requires Docker to be installed and bash to run the script that invokes docker.

Cheatsheet

make will run everything: code generation, tidying, full linting and tests.

make test will run tests only.

make vet will run go vet on the library code.

make vet-test-server will run go vet on the test server code.

make vet-all will run go vet on both above.

make lint will run vet for all library and other linters for recently added changes (against the HEAD).

make lint-all will run vet and linters for all files.

make generate will run code generation.

make tidy will run go mod tidy.

make tidy-test-server will run go mod tidy for the test server code.

make tidy-all will run go mod tidy for both library and test server code.

Documentation

Overview

Package agrirouter provides a client for interacting with the new agrirouter API.

Index

Constants

View Source
const (
	// EndpointNameMinLength is the minimum length, in runes, of a valid endpoint name
	// accepted by the agrirouter API.
	EndpointNameMinLength = 1

	// EndpointNameMaxLength is the maximum length, in runes, of a valid endpoint name
	// accepted by the agrirouter API. Names longer than this will be rejected by the
	// server, so [NormalizeEndpointName] truncates to this length.
	EndpointNameMaxLength = 200
)
View Source
const CapabilityDirectionReceive = internal_models.RECEIVE

CapabilityDirectionReceive indicates capability of endpoint to receive messages.

View Source
const CapabilityDirectionSend = internal_models.SEND

CapabilityDirectionSend indicates capability of endpoint to send messages.

View Source
const CapabilityDirectionSendReceive = internal_models.SENDRECEIVE

CapabilityDirectionSendReceive indicates capability of endpoint to both send and receive messages.

View Source
const CloudSoftware = internal_models.CloudSoftware

CloudSoftware is an endpoint type representing cloud software applications.

Cloud software applications can send and receive agrirouter messages, and they are typically backend applications that could manage data from specific industry (i.e agriculture) and provide users with their own UI.

View Source
const FarmingSoftware = internal_models.FarmingSoftware

FarmingSoftware is an endpoint type representing farming software applications.

Farming software applications can send and receive agrirouter messages, and they are typically cloud deployed applications that manage agricultural data and provide farmers with their own typically web-based user interface. Deprecated: use CloudSoftware instead as industry agnostic term for same thing.

View Source
const VirtualCommunicationUnit = internal_models.VirtualCommunicationUnit

VirtualCommunicationUnit is an endpoint type representing a virtual communication unit.

Virtual communication units like usual communication units represent devices that can send and receive agrirouter messages, but they are doing so indirectly via their own cloud service, which is not installed inside of a vehicle or a machine.

Variables

View Source
var (
	// ErrPutEndpointFailed is returned when an error occurs while trying to put an endpoint.
	ErrPutEndpointFailed = errors.New("failed to put endpoint")

	// ErrDeleteEndpointFailed is returned when an error occurs while trying to delete an endpoint.
	ErrDeleteEndpointFailed = errors.New("failed to delete endpoint")

	// ErrFailedStatusCode is returned when the agrirouter API returns a status code that is not expected.
	ErrFailedStatusCode = errors.New("unexpected status code received from agrirouter API")

	// ErrAPICallFailed is returned when an API call fails due to network or server issues.
	ErrAPICallFailed = errors.New("API call failed")

	// ErrURLIsInvalid is returned when the provided URL is invalid.
	ErrURLIsInvalid = errors.New("provided URL is invalid")
)
View Source
var ErrEndpointNameBlank = errors.New("endpoint name is blank or contains no allowed characters")

ErrEndpointNameBlank is returned by NormalizeEndpointName when the input, after normalization, would be empty or consist only of whitespace, which is not accepted as an endpoint name by the agrirouter API.

View Source
var ErrFailedToFetchPayload = errors.New("failed to fetch payload")

ErrFailedToFetchPayload is returned when calling agrirouter to fetch message payload fails.

View Source
var ErrFailedToReadPayload = errors.New("failed to read payload")

ErrFailedToReadPayload is returned when reading the payload from the response fails.

View Source
var ErrMissingPayload = errors.New("missing payload: no embedded payload and no payload URI")

ErrMissingPayload is returned when agrirouter returned no embedded payload with message nor a payload URI.

View Source
var ErrToCloseResponseBody = errors.New("failed to close response body")

ErrToCloseResponseBody is returned when closing the response body fails.

View Source
var ErrUnexpectedStatusCodeWhenFetchingPayload = errors.New("unexpected status code when fetching payload")

ErrUnexpectedStatusCodeWhenFetchingPayload is returned when the agrirouter API returns an unexpected status code when fetching message payload.

Functions

func NormalizeEndpointName added in v0.6.1

func NormalizeEndpointName(name string) (string, error)

NormalizeEndpointName turns an arbitrary string into a value accepted by the agrirouter API as an endpoint name (see the `name` property of the put endpoint request in openapi.yaml).

The agrirouter API limits names to 1-200 characters and requires every character to be either a letter (any script), a digit, a space or one of `-`, `_`, `.`, `,`, `:`. Names that consist only of whitespace are also rejected by the server.

This helper applies the following normalization to the input:

  1. Every disallowed character is replaced with a single underscore (`_`).
  2. Runs of consecutive underscores are collapsed into a single underscore.
  3. The result is truncated (rune-aware) to EndpointNameMaxLength.

If the resulting value is empty or contains only whitespace, the function returns ErrEndpointNameBlank. Otherwise it returns the normalized name.

Types

type Client

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

Client is the structure that allows interaction with the agrirouter API.

func NewClient

func NewClient(serverURL string, opts ...ClientOption) (*Client, error)

NewClient creates a new agrirouter client with the given server URL. The server URL should be the base URL of the agrirouter API, e.g. "https://api.qa.agrirouter.farm".

func (*Client) ConfirmMessages added in v0.4.0

func (c *Client) ConfirmMessages(
	ctx context.Context,
	params *ConfirmMessagesParams,
	req ConfirmMessagesRequest,
) error

ConfirmMessages confirms that messages have been received and processed.

Each confirmation carries a message ID and the endpoint ID that received it. The same message may be received by different endpoints and can be confirmed separately, either in the same request or in different ones.

func (*Client) DeleteEndpoint added in v0.6.0

func (c *Client) DeleteEndpoint(
	ctx context.Context,
	externalID string,
	params *DeleteEndpointParams,
) error

DeleteEndpoint sends a request to the agrirouter API to delete an endpoint identified by its application-defined external ID.

Once deleted, the endpoint will no longer receive messages and cannot be recovered. The caller must be authorized to manage the endpoint, typically by being the application that originally created it.

func (*Client) PutEndpoint

func (c *Client) PutEndpoint(
	ctx context.Context,
	externalID string,
	params *PutEndpointParams,
	req *PutEndpointRequest,
) (*Endpoint, error)

PutEndpoint sends a request to the agrirouter API to create or update an endpoint.

Identifier externalId must uniquely identify created or updated endpoint, if endpoint with the same externalId already exists, it will be updated, but only if client is authorized to change that endpoint, f.e application owns it.

The request body must contain all endpoint capabilities and subscriptions. It is not possible to update only part of endpoint configuration. For example if subscriptions are not provided, they will be removed (set to empty list).

func (*Client) ReceiveEndpointDeletedEvents added in v0.7.0

func (c *Client) ReceiveEndpointDeletedEvents(
	ctx context.Context,
	deletionHandler EndpointDeletionHandler,
	errorHandler func(err error),
) error

ReceiveEndpointDeletedEvents listens for endpoint-deletion events from the agrirouter API and calls the provided handler for each deleted endpoint.

This function blocks until the context is canceled or an error occurs. It is recommended to run this function in a separate goroutine.

func (*Client) ReceiveFiles added in v0.3.0

func (c *Client) ReceiveFiles(
	ctx context.Context,
	fileHandler func(
		ctx context.Context,
		file *File,
	),
	errorHandler func(err error),
) error

ReceiveFiles listens for incoming files from the agrirouter API and calls the provided handler for each received file.

This function blocks until the context is canceled or an error occurs. It is recommended to run this function in a separate goroutine.

func (*Client) ReceiveMessages added in v0.2.0

func (c *Client) ReceiveMessages(
	ctx context.Context,
	messageHandler MessageHandler,
	errorHandler func(err error),
) error

ReceiveMessages listens for incoming messages from the agrirouter API and calls the provided handler for each received message.

This function blocks until the context is canceled or an error occurs. It is recommended to run this function in a separate goroutine.

func (*Client) SendMessages added in v0.1.0

func (c *Client) SendMessages(
	ctx context.Context,
	params *SendMessagesParams,
	body io.Reader,
) error

SendMessages sends a message to the agrirouter API.

The body of the request must be a valid payload of agrirouter message.

type ClientOption

type ClientOption = func(*Client) error

ClientOption is a type for options that can be passed to the agrirouter client.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient allows to set a custom HTTP client for the agrirouter client. This client will be used for all API calls, but not for fetching file payloads.

func WithPayloadsHTTPClient added in v0.3.1

func WithPayloadsHTTPClient(httpClient PayloadsHTTPClient) ClientOption

WithPayloadsHTTPClient allows to set a custom HTTP client for fetching payloads.

func WithRequestEditorFn

func WithRequestEditorFn(fn RequestEditorFn) ClientOption

WithRequestEditorFn allows to set a custom request editor function to modify request before sending it. This will not apply to requests when fetching file payloads, only to agrirouter API calls.

type ConfirmMessagesParams added in v0.4.0

type ConfirmMessagesParams = internal_models.ConfirmMessagesParams

ConfirmMessagesParams contains parameters to confirm messages.

type ConfirmMessagesRequest added in v0.4.0

type ConfirmMessagesRequest = internal_models.ConfirmMessagesRequest

ConfirmMessagesRequest is the request structure for confirming received messages.

type DeleteEndpointParams added in v0.6.0

type DeleteEndpointParams = internal_models.DeleteEndpointParams

DeleteEndpointParams contains parameters to delete an endpoint.

type DeletedEndpoint added in v0.7.0

type DeletedEndpoint struct {
	ID         uuid.UUID // ID is the agrirouter endpoint ID of the deleted endpoint
	ExternalID string    // ExternalID is the external ID the endpoint was registered with
}

DeletedEndpoint represents an endpoint that has been deleted in agrirouter, which is received when server sends us ENDPOINT_DELETED event.

type Endpoint

type Endpoint = internal_models.Endpoint

Endpoint is the structure representing an agrirouter endpoint.

type EndpointCapability

type EndpointCapability = internal_models.EndpointCapability

EndpointCapability is the structure representing an endpoint's capability.

It defines what endpoint can do, such as sending or receiving messages of specific types.

type EndpointCapabilityDirection added in v0.2.6

type EndpointCapabilityDirection = internal_models.EndpointCapabilityDirection

EndpointCapabilityDirection represents the direction of an endpoint's capability.

It indicates whether the endpoint can send, receive, or both send and receive messages of a specific type.

type EndpointDeletedEventData added in v0.7.0

type EndpointDeletedEventData = internal_models.EndpointDeletedEventData

EndpointDeletedEventData represents the data received in an EndpointDeleted event.

It contains the agrirouter ID and the external ID of the endpoint that was deleted, either via this API or by other means (e.g. user-initiated deletion from the agrirouter UI).

type EndpointDeletionHandler added in v0.7.0

type EndpointDeletionHandler func(ctx context.Context, deletion *DeletedEndpoint)

EndpointDeletionHandler is a function that handles an endpoint-deletion event.

type EndpointSubscription

type EndpointSubscription = internal_models.EndpointSubscription

EndpointSubscription is the structure representing an endpoint's subscription.

It defines which message types the endpoint is subscribed to, meaning it can receive messages of those types in case if sending endpoint has published them.

type EndpointType added in v0.2.6

type EndpointType = internal_models.EndpointType

EndpointType represents the type of an agrirouter endpoint.

There are three main types of endpoints: 1. communication_unit: Represents devices installed inside vehicles or machines. 2. virtual_communication_unit: Represents virtual devices communicating via their own cloud services. 3. farming_software: Represents farming software applications, typically cloud-based.

type File added in v0.3.0

type File struct {
	ReceivingEndpointID uuid.UUID   // ReceivingEndpointID is the UUID of the endpoint that received the file
	Payload             io.Reader   // Payload is the file payload as a stream
	Filename            *string     // Filename is optional as sent by sender endpoint
	MessageType         string      // MessageType is the URN type of the message
	Size                int64       // Size of file payload in bytes
	MessageIDs          []uuid.UUID // MessageIDs are the agrirouter message IDs of the messages that carried the file payload chunks
	TenantID            *string     // TenantID is the tenant to which the receiving endpoint belongs
	TeamsetContextID    *string     // TeamsetContextID is the teamset context ID provided by the sending application, if any
}

File represents a file received from agrirouter.

Typically files would have larger payloads than messages, so the payload is provided as an io.Reader to allow streaming.

type Message added in v0.2.0

type Message struct {
	ID                  uuid.UUID // ID is the agrirouter message ID, generated by agrirouter
	MessageType         string    // MessageType is the URN type of the message
	Payload             []byte    // Payload is the raw message payload
	AppMessageID        string    // AppMessageID is the ID assigned by the sending endpoint
	ReceivingEndpointID uuid.UUID // ReceivingEndpointID is the UUID of the endpoint that received the message
	Filename            *string   // Filename is optional as sent by sender endpoint
	TenantID            *string   // TenantID is the tenant to which the receiving endpoint belongs
	TeamsetContextID    *string   // TeamsetContextID is the teamset context ID provided by the sending application, if any
}

Message represents a message received from agrirouter.

type MessageConfirmation added in v0.4.0

type MessageConfirmation = internal_models.MessageConfirmation

MessageConfirmation is a single message confirmation carrying a message ID and endpoint ID.

type MessageHandler added in v0.2.0

type MessageHandler func(ctx context.Context, message *Message)

MessageHandler is a function that handles a received message.

type MessageReceivedEventData added in v0.2.0

type MessageReceivedEventData = internal_models.MessageReceivedEventData

MessageReceivedEventData represents the data received in a MessageReceived event.

It contains information about the received message, including its type and payload URI. This event would typically be followed by fetching the actual message payload from the provided URI and processing it accordingly (e.g. decoding, storing, or acting upon the message content).

type PayloadsHTTPClient added in v0.3.1

type PayloadsHTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

PayloadsHTTPClient is an interface for an HTTP client that can be used to fetch payloads.

type PutEndpointParams

type PutEndpointParams = internal_models.PutEndpointParams

PutEndpointParams contains parameters to create or update an endpoint.

type PutEndpointRequest

type PutEndpointRequest = internal_models.PutEndpointRequest

PutEndpointRequest is the request structure for creating or updating an endpoint.

type RequestEditorFn

type RequestEditorFn = oapi.RequestEditorFn

RequestEditorFn is a function that can modify the request before it is sent.

type SendMessagesParams added in v0.1.0

type SendMessagesParams = internal_models.SendMessagesParams

SendMessagesParams contains parameters to send a message.

Directories

Path Synopsis
internal
oapi
Package oapi provides primitives to interact with the openapi HTTP API.
Package oapi provides primitives to interact with the openapi HTTP API.
oapi/models
Package models provides primitives to interact with the openapi HTTP API.
Package models provides primitives to interact with the openapi HTTP API.
tests/agriroutertestcontainer
Package agriroutertestcontainer is a testcontainers module for the agrirouter service.
Package agriroutertestcontainer is a testcontainers module for the agrirouter service.

Jump to

Keyboard shortcuts

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