plugin

package module
v0.0.0-...-c20434f Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2025 License: AGPL-3.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientTokenResponse

type ClientTokenResponse struct {
	AccessToken      string    `json:"access_token"`
	IDToken          string    `json:"id_token"`
	ExpiresIn        int       `json:"expires_in"`
	Expiry           time.Time `json:"expiry"`
	RefreshExpiresIn int       `json:"refresh_expires_in"`
	RefreshToken     string    `json:"refresh_token"`
	TokenType        string    `json:"token_type"`
	NotBeforePolicy  int       `json:"not_before_policy"`
	SessionState     string    `json:"session_state"`
	Scope            string    `json:"scope"`
}

type Plugin

type Plugin struct {
	Slug           string
	Name           string
	Version        string
	Description    string
	PluginHostPath *url.URL
}

Plugin represents a plugin that can be registered with the plugin host.

Fields: - Slug: A unique identifier for the plugin, used to distinguish it within the plugin host. - Name: The name of the plugin, used for display and identification purposes. - Version: The version of the plugin, typically following semantic versioning (e.g., "1.0.0"). - Description: A brief description of the plugin, detailing its purpose or functionality. - PluginHostPath: The URL path where the plugin can be accessed on the plugin host.

func NewPlugin

func NewPlugin(opts ...PluginOption) Plugin

NewPlugin creates a new Plugin instance with the provided functional options.

If no options are provided, the defaultPlugin is used as the base configuration. Each option is applied sequentially to modify the default settings.

Parameters: - opts: A variadic list of PluginOption functions to customize the Plugin instance.

Returns: - A pointer to the newly created Plugin instance.

Example usage:

plugin := NewPlugin(
	WithName("My Plugin"),
	WithSlug("my-plugin"),
	WithVersion("1.0.0"),
	WithDescription("An example plugin."),
)

type PluginAuth

type PluginAuth struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
}

type PluginOption

type PluginOption func(*Plugin)

PluginOption is a functional option for configuring a Plugin.

Functional options provide a flexible and extensible way to customize Plugin instances during creation without requiring multiple constructors or complex initialization logic.

func WithDescription

func WithDescription(description string) PluginOption

WithDescription sets the description of the plugin.

Example usage:

plugin := NewPlugin(WithDescription("This plugin provides example functionality."))

func WithHostPath

func WithHostPath(hostPath *url.URL) PluginOption

WithHostPath sets the host path of the plugin.

Example usage:

hostPath, _ := url.Parse("https://example.com/plugin")
plugin := NewPlugin(WithHostPath(hostPath))

func WithName

func WithName(name string) PluginOption

WithName sets the name of the plugin.

Example usage:

plugin := NewPlugin(WithName("My Plugin"))

func WithSlug

func WithSlug(slug string) PluginOption

WithSlug sets the slug of the plugin.

Example usage:

plugin := NewPlugin(WithSlug("my-plugin"))

func WithVersion

func WithVersion(version string) PluginOption

WithVersion sets the version of the plugin.

Example usage:

plugin := NewPlugin(WithVersion("1.0.0"))

type PluginRegisterRequest

type PluginRegisterRequest struct {
	Slug        string     `json:"slug"`
	Name        string     `json:"name"`
	Description string     `json:"description"`
	Version     string     `json:"version"`
	Path        string     `json:"path"`
	Auth        PluginAuth `json:"auth"`
}

type PluginWorker

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

PluginWorker is responsible for managing the lifecycle of a plugin.

This includes tasks such as: - Registering the plugin with the host. - Sending periodic heartbeats to indicate the plugin is active. - Maintaining and using an authentication token for secure communication.

func NewPluginWorker

func NewPluginWorker(opts ...PluginWorkerOption) (*PluginWorker, error)

NewPluginWorker creates a new PluginWorker instance with the provided options.

If no options are provided, the worker is created with default values. This function validates the configuration and returns an error if the configuration is invalid.

Parameters: - opts: A variadic list of PluginWorkerOption functions to customize the PluginWorker.

Returns: - A pointer to the PluginWorker instance if successful. - An error if the configuration is invalid.

Example usage:

hostURL, _ := url.Parse("https://example.com")
worker, err := NewPluginWorker(
	WithHost(hostURL),
	WithInterval(1*time.Minute),
)
if err != nil {
	log.Fatalf("Failed to create PluginWorker: %v", err)
}

func (*PluginWorker) Heartbeat

func (w *PluginWorker) Heartbeat(ctx context.Context) error

Heartbeat sends a periodic heartbeat signal to the plugin host to indicate that the plugin is active and operational. The authorisation header will be set to internal hold access token.

This function performs the following steps: 1. Constructs the heartbeat API endpoint URL based on the plugin's slug and configuration settings. 2. Sends an HTTP POST request to the constructed endpoint without a request body. 3. Checks the response status code to confirm the success of the heartbeat operation.

Parameters: - ctx: The context for managing request deadlines and cancellation.

Returns: - nil if the heartbeat is successfully sent and acknowledged by the plugin host. - An error if any of the following issues occur:

  • Constructing the HTTP request fails.
  • Sending the HTTP request fails (e.g., due to network issues).
  • The plugin host responds with a non-200 status code, indicating the heartbeat was not successfully received.

Example usage:

err := pluginWorker.Heartbeat(ctx)
if err != nil {
	log.Printf("Failed to send heartbeat: %v", err)
} else {
	log.Println("Heartbeat sent successfully.")
}

Notes: - The plugin's slug, host, and API version must be correctly configured in the `PluginWorker` instance. - This function assumes that the plugin host's heartbeat API endpoint requires an HTTP POST request.

func (*PluginWorker) RefreshToken

func (w *PluginWorker) RefreshToken(ctx context.Context) (*Token, error)

RefreshToken refreshes the authentication token for the plugin.

func (*PluginWorker) Register

func (w *PluginWorker) Register(ctx context.Context) (*Token, error)

Register registers the plugin with the plugin host and returns an authentication token. Upon successful registration of the plugin, the Authorisation header is set on every protected route to the backend, which already contains this token.

This function performs the following steps:

  1. Constructs a registration request payload containing plugin metadata (such as slug, name, version, and description) and authentication credentials (client ID and client secret).
  2. Sends the registration request as an HTTP POST request to the plugin host's registration API endpoint.
  3. Parses the response from the plugin host to extract and return the authentication tokens.

Parameters: - ctx: The context for managing request deadlines and cancellation.

Returns:

  • A pointer to a Token struct containing the access and refresh tokens if registration is successful.
  • An error if the registration fails, due to either an HTTP request issue, an unexpected status code, or failure in parsing the response body.

Possible errors: - If the request payload cannot be marshaled into JSON, an error is returned. - If creating the HTTP request fails, an error is returned. - If the HTTP request fails (e.g., network error), an error is returned. - If the plugin host returns a non-200 status code, an error is returned with a generic failure message. - If the response body cannot be decoded into the expected format, an error is returned.

Example usage:

token, err := pluginWorker.Register(ctx)
if err != nil {
	log.Fatalf("Failed to register plugin: %v", err)
}
log.Printf("Successfully registered. Access token: %s", token.AccessToken)

func (*PluginWorker) RunHeartbeat

func (w *PluginWorker) RunHeartbeat(ctx context.Context) error

RunHeartbeat starts the heartbeat runner for the PluginWorker.

This function sends periodic heartbeat signals to the plugin host at the configured interval. It uses a ticker to manage timing and stops when the provided context is canceled.

Parameters: - ctx: The context for managing lifecycle and cancellation of the heartbeat runner.

Returns: - nil when the context is canceled. - An error if sending a heartbeat fails.

Example usage:

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

err := worker.RunHeartbeat(ctx)
if err != nil {
	log.Fatalf("Heartbeat failed: %v", err)
}

func (*PluginWorker) Unregister

func (w *PluginWorker) Unregister(ctx context.Context) error

Unregister removes the plugin registration from the plugin host. The authorisation header will be set to internal hold access token.

This function performs the following steps:

  1. Constructs the API endpoint URL for unregistering the plugin based on the plugin's configuration.
  2. Creates an HTTP POST request with the given context to initiate the unregistration process.
  3. Sends the request using the configured HTTP client and handles any potential errors.
  4. Validates the response status code to ensure successful unregistration.

Parameters: - ctx: The context for managing request deadlines and cancellation.

Returns: - nil if the unregistration is successful. - An error if the request fails, the HTTP client encounters an issue, or the response status code is not 204 No Content.

Possible errors: - If creating the HTTP request fails, an error is returned. - If the HTTP request fails (e.g., network error), an error is returned. - If the plugin host returns a non-204 status code, an error is returned with a generic failure message.

Example usage:

err := pluginWorker.Unregister(ctx)
if err != nil {
    log.Fatalf("Failed to unregister plugin: %v", err)
}
log.Println("Successfully unregistered plugin")

type PluginWorkerConfig

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

PluginWorkerConfig defines the configuration settings for a PluginWorker.

Fields: - plugin: The plugin being managed by the worker. - host: The URL of the plugin host where the plugin communicates. - hostAPIVersion: The API version used by the plugin host. - interval: The interval for periodic tasks, such as heartbeats. - client: The HTTP client used for making requests to the plugin host. - token: The authentication token used for secure communication. - clientID: The client id from the oidc provider - clientSecret: The client secret from the oidc provider

func (*PluginWorkerConfig) IsValid

func (c *PluginWorkerConfig) IsValid() bool

IsValid checks whether the PluginWorkerConfig is valid.

Returns true if all required fields are properly set (e.g., host, plugin, interval, client), false otherwise.

type PluginWorkerOption

type PluginWorkerOption func(*PluginWorkerConfig)

PluginWorkerOption is a functional option for configuring a PluginWorker.

Functional options provide flexibility by allowing configuration settings to be passed dynamically at runtime.

func WithClient

func WithClient(client *http.Client) PluginWorkerOption

WithClient sets the HTTP client for the PluginWorker.

Example usage:

worker, err := NewPluginWorker(
	WithClient(http.DefaultClient),
)

func WithClientID

func WithClientID(clientID string) PluginWorkerOption

WithClientID sets the client id from oidc provider for the PluginWorker.

func WithClientSecret

func WithClientSecret(clientSecret string) PluginWorkerOption

WithClientSecret sets the client secret from oidc provider for the PluginWorker.

func WithHost

func WithHost(host *url.URL) PluginWorkerOption

WithHost sets the host URL for the PluginWorker.

Example usage:

hostURL, _ := url.Parse("https://example.com")
worker, err := NewPluginWorker(
	WithHost(hostURL),
)

func WithHostAPIVersion

func WithHostAPIVersion(version string) PluginWorkerOption

WithHostAPIVersion sets the API version for the PluginWorker.

Example usage:

worker, err := NewPluginWorker(
	WithHostAPIVersion("v2"),
)

func WithInterval

func WithInterval(interval time.Duration) PluginWorkerOption

WithInterval sets the interval for periodic tasks, such as heartbeats.

Example usage:

worker, err := NewPluginWorker(
	WithInterval(5 * time.Minute),
)

func WithPlugin

func WithPlugin(plugin Plugin) PluginWorkerOption

WithPlugin sets the plugin for the PluginWorker.

Example usage:

plugin := Plugin{Name: "Example Plugin"}
worker, err := NewPluginWorker(
	WithPlugin(plugin),
)

func WithToken

func WithToken(token *Token) PluginWorkerOption

WithToken sets the authentication token for the PluginWorker.

Example usage:

token := &Token{AccessToken: "abc123"}
worker, err := NewPluginWorker(
	WithToken(token),
)

type Token

type Token struct {
	AccessToken  string
	RefreshToken string
	Expiry       time.Time
	ExpiresIn    int64
	TokenType    string
}

Token represents an authentication token used to interact with a plugin host.

Fields: - AccessToken: A short-lived token used for authenticating API requests to the plugin host. - RefreshToken: A long-lived token used to obtain a new access token when the current one expires. - Expiry: The time when the access token expires. - ExpiresIn: The duration until the access token expires.

The `Token` structure is typically used after a plugin registers with the plugin host and is issued authentication credentials.

Example usage:

	token := &Token{
		AccessToken:  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
		RefreshToken: "dGVzdF9yZWZyZXNoX3Rva2VuX3ZhbHVl...",
   Expiry:       time.Now().Add(1 * time.Hour),
   ExpiresIn:    1 * time.Hour,
	}

Jump to

Keyboard shortcuts

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