sdk

package module
v0.0.0-...-6902dc6 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 20 Imported by: 0

README

Environment Manager Go Function SDK

SDK for building Go functions invoked by the Environment Manager workflow engine. It handles HTTP serving, request metadata, and event context so you can focus on your function logic.

Installation

go get github.com/RafaySystems/function-templates/sdk/go

For a working example that uses the SDK, see examples/go/helm/go.mod. Local development can use a replace directive pointing at the SDK path.

Quick start

Implement a handler and run the SDK:

package main

import (
	"context"
	sdk "github.com/RafaySystems/function-templates/sdk/go"
)

func Handle(ctx context.Context, logger sdk.Logger, req sdk.Request) (sdk.Response, error) {
	logger.Info("request received")
	return sdk.Response{"result": "ok"}, nil
}

func main() {
	f, err := sdk.NewFunctionSDK(sdk.WithHandler(Handle))
	if err != nil {
		panic(err)
	}
	_ = f.Run(context.Background())
}

Handler and request/response

Your handler has the signature:

func(ctx context.Context, logger sdk.Logger, req sdk.Request) (sdk.Response, error)
  • Request and Response are map-like types (map[string]any). Use req["key"] or helpers such as req.GetString("key") for typed access. Nested keys are supported (e.g. req.GetString("nested", "field")).
  • Request metadata is filled from incoming headers: activity ID, environment ID/name, organization ID, project ID, state store URL/token, and event source, event source name, and event type. This metadata drives EventDetails below.

EventDetails

Each invocation can carry event metadata (source, source name, and event type). EventDetails is the typed view of that metadata so you can branch or read names without parsing headers yourself.

Obtaining EventDetails
event := sdk.NewEventDetails(req)

NewEventDetails takes the handler’s Request and returns *EventDetails with Source, SourceName, and Type populated from request metadata.

Fields
Field Type Description
Source string Event source (e.g. workload, action).
SourceName string Name of the source resource (e.g action name, workload name).
Type EventType Kind of event (deploy, destroy, etc.).
Event types
Constant String value
sdk.DeployEventType "deploy"
sdk.DestroyEventType "destroy"
sdk.ForceDestroyEventType "force-destroy"
Sources

The engine may send events from these sources (used by the helpers below): "action", "schedules", "workload", "environment".

Convenience helpers

Source checks: return true when the event’s source matches.

Method Source
IsAction() action
IsSchedules() schedules
IsWorkload() workload
(environment) use combined helpers below

Name getters: return (string, bool) — the source name and true only when the event’s source matches.

Method Source
GetActionName() action
GetSchedulesName() schedules
GetWorkloadName() workload
(environment) use combined helpers below

Type checks: IsDeploy(), IsDestroy(), IsForceDestroy(), GetTypeAsString().

Combined (source + type):

Method Condition
IsWorkloadDeploy() source is workload and type deploy
IsWorkloadDestroy() source is workload and type destroy or force-destroy
IsEnvironmentDeploy() source is environment and type deploy
IsEnvironmentDestroy() source is environment and type destroy or force-destroy
Example usage
func Handle(ctx context.Context, logger sdk.Logger, req sdk.Request) (sdk.Response, error) {
	event := sdk.NewEventDetails(req)
	// create a variable called action with default value `deploy`
	action := string(sdk.DeployEventType)
	// if action is the source of this event, then get the action name
	if name, ok := event.GetActionName(); ok {
		action = name
	}
	if event.IsWorkloadDeploy() {
		name, _ := event.GetWorkloadName()
		// deploy workload "name"
	}
	if event.IsEnvironmentDestroy() {
		// teardown environment
	}
	return sdk.Response{}, nil
}

Errors

Return an error from your handler; the SDK encodes it as a structured JSON response with an error code. Use the typed constructors so the engine can retry or handle appropriately:

Constructor Use when
sdk.NewErrFailed(msg) Permanent failure; do not retry.
sdk.NewErrTransient(msg) Temporary failure; engine may retry.
sdk.NewErrExecuteAgain(msg, data) Ask engine to re-invoke (e.g. with updated data).
sdk.NewErrNotFound(msg) Resource not found.
sdk.NewErrConflict(msg) Conflict (e.g. version mismatch).

The response shape is ErrFunction with ErrCode (e.g. ErrCodeFailed, ErrCodeTransient, ErrCodeExecuteAgain). The engine may retry on transient or execute-again errors.

Configuration

Pass options to NewFunctionSDK:

Option Description
WithHandler(handler) Required. Your function handler.
WithPort(port) HTTP port (default if not set).
WithReadTimeout, WithWriteTimeout HTTP timeouts.
WithShutdownTimeout Graceful shutdown timeout.
WithLogLevel(level) Log level (e.g. slog.LevelDebug).
WithListener(listener) Custom listener instead of default bind.
WithLogWriteTimeout, WithLogFlushRate, WithLogUploadRetryCount Log upload behavior.
WithServerSkipTLSVerify(bool) Skip TLS verification for log upload.

See sdk.go for the full list of With* options.

Example

The examples/go/helm directory contains a Helm-based function that uses the SDK: handler signature, request parsing, and typed errors. You can use sdk.NewEventDetails(req) there to branch on event source and type.

Documentation

Overview

Package sdk Adapted from https://github.com/openfaas/templates-sdk/blob/master/go-http/handler.go Original license: MIT

Index

Constants

View Source
const (
	ErrCodeUnspecified errorCode = iota
	ErrCodeExecuteAgain
	ErrCodeFailed
	ErrCodeTransient
	ErrCodeNotFound
	ErrCodeConflict
)
View Source
const (
	ActivityIDHeader         = "X-Activity-ID"
	EnvironmentIDHeader      = "X-Environment-ID"
	EnvironmentNameHeader    = "X-Environment-Name"
	WorkflowTokenHeader      = "X-Workflow-Token"
	EngineAPIEndpointHeader  = "X-Engine-Endpoint"
	ActivityFileUploadHeader = "X-Activity-File-Upload"
	OrganizationIDHeader     = "X-Organization-ID"
	ProjectIDHeader          = "X-Project-ID"
	EaasStateEndpointHeader  = "X-Eaas-State-Endpoint"
	EaasStateAPITokenHeader  = "X-Eaas-State-Token"
	EventSourceHeader        = "X-Event-Source"
	EventSourceNameHeader    = "X-Event-Source-Name"
	EventTypeHeader          = "X-Event-Type"
)

Variables

View Source
var WithLogReqTimeout = func(reqTimeout time.Duration) WriterOption {
	return func(w *writer) {
		w.reqTimeout = reqTimeout
	}
}
View Source
var WithSkipTLSVerify = func(skipTLSVerify bool) WriterOption {
	return func(w *writer) {
		w.skipTLSVerify = skipTLSVerify
	}
}
View Source
var WithWriteFlushTickRate = func(tickRate time.Duration) WriterOption {
	return func(w *writer) {
		w.flushTickRate = tickRate
	}
}

Functions

func IsErrConflict

func IsErrConflict(err error) bool

func IsErrExecuteAgain

func IsErrExecuteAgain(err error) bool

func IsErrFailed

func IsErrFailed(err error) bool

func IsErrFunction

func IsErrFunction(err error) bool

func IsErrNotFound

func IsErrNotFound(err error) bool

func IsErrTransient

func IsErrTransient(err error) bool

func NewActivityLogWriter

func NewActivityLogWriter(ctx context.Context, logger *slog.Logger, url, token string, opts ...WriterOption) io.WriteCloser

func NewErrConflict

func NewErrConflict(msg string) error

func NewErrExecuteAgain

func NewErrExecuteAgain(msg string, data map[string]any) error

func NewErrFailed

func NewErrFailed(msg string) error

func NewErrNotFound

func NewErrNotFound(msg string) error

func NewErrTransient

func NewErrTransient(msg string) error

Types

type ErrFunction

type ErrFunction struct {
	ErrCode    errorCode      `json:"error_code"`
	Message    string         `json:"message"`
	StackTrace []stackFrame   `json:"stack_trace"`
	Data       map[string]any `json:"data"`
}

func AsErrFunction

func AsErrFunction(err error) (*ErrFunction, bool)

func (*ErrFunction) Error

func (e *ErrFunction) Error() string

type EventDetails

type EventDetails struct {
	Source     string
	SourceName string
	Type       EventType
}

EventDetails represents metadata about an event, including its source, source name, and type.

func NewEventDetails

func NewEventDetails(request Request) *EventDetails

NewEventDetails creates a new EventDetails instance by extracting metadata fields from the given Request object. The request's metadata is used to populate the EventDetails's Source, SourceName, and Type fields.

func (EventDetails) GetActionName

func (e EventDetails) GetActionName() (string, bool)

GetActionName returns the SourceName and true if the event Source is "action"; otherwise returns an empty string and false.

func (EventDetails) GetSchedulesName

func (e EventDetails) GetSchedulesName() (string, bool)

GetSchedulesName returns the SourceName and true if the event Source is "schedules"; otherwise, returns an empty string and false.

func (EventDetails) GetTypeAsString

func (e EventDetails) GetTypeAsString() string

GetTypeAsString converts the EventDetails's Type field to a string and returns it.

func (EventDetails) GetWorkloadName

func (e EventDetails) GetWorkloadName() (string, bool)

GetWorkloadName returns the SourceName and true if the event Source is "workload"; otherwise, returns an empty string and false.

func (EventDetails) IsAction

func (e EventDetails) IsAction() bool

IsAction determines if the event's Source is set to "action".

func (EventDetails) IsDeploy

func (e EventDetails) IsDeploy() bool

IsDeploy checks if the event's Type is DeployEventType.

func (EventDetails) IsDestroy

func (e EventDetails) IsDestroy() bool

IsDestroy checks if the event's Type is set to DestroyEventType or ForceDestroyEventType.

func (EventDetails) IsEnvironmentDeploy

func (e EventDetails) IsEnvironmentDeploy() bool

IsEnvironmentDeploy checks if the event's Source is "environment" and its Type is DeployEventType.

func (EventDetails) IsEnvironmentDestroy

func (e EventDetails) IsEnvironmentDestroy() bool

IsEnvironmentDestroy checks if the event's Source is "environment" and its Type is DestroyEventType or ForceDestroyEventType.

func (EventDetails) IsForceDestroy

func (e EventDetails) IsForceDestroy() bool

IsForceDestroy checks if the event's Type is set to ForceDestroyEventType.

func (EventDetails) IsSchedules

func (e EventDetails) IsSchedules() bool

IsSchedules determines if the event's Source is set to "schedules".

func (EventDetails) IsWorkload

func (e EventDetails) IsWorkload() bool

IsWorkload checks if the event's Source is set to "workload".

func (EventDetails) IsWorkloadDeploy

func (e EventDetails) IsWorkloadDeploy() bool

IsWorkloadDeploy checks if the event's Source is "workload" and its Type is DeployEventType.

func (EventDetails) IsWorkloadDestroy

func (e EventDetails) IsWorkloadDestroy() bool

IsWorkloadDestroy returns true if the event's Source is "environment" and its Type indicates a destroy operation.

type EventType

type EventType string

EventType represents the type of event, commonly used in event-driven systems for categorization or processing.

const (
	DeployEventType       EventType = "deploy"
	DestroyEventType      EventType = "destroy"
	ForceDestroyEventType EventType = "force-destroy"
)

type FunctionHandler

type FunctionHandler interface {
	Handle(ctx context.Context, logger Logger, req Request) (Response, error)
}

FunctionHandler used for a serverless Go method invocation

type FunctionSDK

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

func NewFunctionSDK

func NewFunctionSDK(opts ...SDKOption) (*FunctionSDK, error)

func (*FunctionSDK) Run

func (f *FunctionSDK) Run(ctx context.Context) error

type Handler

type Handler func(ctx context.Context, logger Logger, req Request) (Response, error)

type Logger

type Logger interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
	Log(ctx context.Context, level slog.Level, msg string, args ...any)
}

type Object

type Object map[string]any

func (Object) GetAsString

func (r Object) GetAsString(key string) (string, bool)

func (Object) GetBool

func (r Object) GetBool(keys ...string) (bool, error)

func (Object) GetFloat64

func (r Object) GetFloat64(keys ...string) (float64, error)

func (Object) GetInt

func (r Object) GetInt(keys ...string) (int, error)

func (Object) GetInt64

func (r Object) GetInt64(keys ...string) (int64, error)

func (Object) GetSlice

func (r Object) GetSlice(keys ...string) ([]interface{}, error)

func (Object) GetString

func (r Object) GetString(keys ...string) (string, error)

func (Object) GetStringMap

func (r Object) GetStringMap(keys ...string) (Object, error)

func (Object) MetaString

func (r Object) MetaString(key string) string

type ReadyResponse

type ReadyResponse struct {
	Ready          bool  `json:"ready"`
	NumConnections int32 `json:"num_connections"`
}

type Request

type Request = Object

type Response

type Response = Object

type SDKOption

type SDKOption func(*SDKOptions)

func WithHandler

func WithHandler(handler Handler) SDKOption

func WithHealthInterval

func WithHealthInterval(healthInterval time.Duration) SDKOption

func WithListener

func WithListener(listener net.Listener) SDKOption

func WithLogFlushRate

func WithLogFlushRate(logFlushRate time.Duration) SDKOption

func WithLogLevel

func WithLogLevel(logLevel slog.Level) SDKOption

func WithLogUploadRetryCount

func WithLogUploadRetryCount(logUploadRetryCount int) SDKOption

func WithLogWriteTimeout

func WithLogWriteTimeout(logWriteTimeout time.Duration) SDKOption

func WithPort

func WithPort(port int) SDKOption

func WithReadTimeout

func WithReadTimeout(readTimeout time.Duration) SDKOption

func WithServerSkipTLSVerify

func WithServerSkipTLSVerify(skipTLSVerify bool) SDKOption

func WithShutdownTimeout

func WithShutdownTimeout(shutdownTimeout time.Duration) SDKOption

func WithWriteTimeout

func WithWriteTimeout(writeTimeout time.Duration) SDKOption

type SDKOptions

type SDKOptions struct {
	Port                int
	Listener            net.Listener
	Handler             Handler
	ReadTimeout         time.Duration
	WriteTimeout        time.Duration
	ShutdownTimeout     time.Duration
	HealthInterval      time.Duration
	LogLevel            slog.Level
	LogUploadRetryCount int
	LogFlushRate        time.Duration
	LogWriteTimeout     time.Duration
	SkipTLSVerify       bool
}

type WriterOption

type WriterOption func(*writer)

Directories

Path Synopsis
pkg

Jump to

Keyboard shortcuts

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