functions

package
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package functions holds the starter handlers for scale-to-zero functions.

Index

Constants

View Source
const (
	EnvKVMaxKeyBytes   = "APP_FUNCTION_KV_MAX_KEY_BYTES"
	EnvKVMaxValueBytes = "APP_FUNCTION_KV_MAX_VALUE_BYTES"
	EnvKVMaxKeys       = "APP_FUNCTION_KV_MAX_KEYS"
	EnvKVMaxTotalBytes = "APP_FUNCTION_KV_MAX_TOTAL_BYTES"
	EnvKVMaxTTL        = "APP_FUNCTION_KV_MAX_TTL_SECONDS"
	EnvKVURL           = "APP_FUNCTION_KV_URL"

	// KVTokenEnv and KVURLEnv are the variables the function sees.
	KVTokenEnv = "KV_TOKEN"
	KVURLEnv   = "KV_URL"

	// KVAPIPath is where functions reach the store, below the control plane's internal address.
	KVAPIPath = "/api/v1/function-kv"
)

Environment variables that size the per-function key-value store.

View Source
const (
	EnvRequestTimeout        = "APP_FUNCTION_REQUEST_TIMEOUT"
	EnvRequestTimeoutMax     = "APP_FUNCTION_REQUEST_TIMEOUT_MAX"
	EnvMaxConcurrency        = "APP_FUNCTION_MAX_CONCURRENCY"
	EnvMaxConcurrencyCeiling = "APP_FUNCTION_MAX_CONCURRENCY_CEILING"
)

Environment settings read by the control plane. A per-function value of 0 falls back to the Default* variable; the Max* variables bound what a function may ask for.

View Source
const (
	HeaderInvocation = "X-Function-Invocation"
	HeaderAttempt    = "X-Function-Attempt"
	HeaderSource     = "X-Function-Source"
)

Headers sent on every queued call so the handler can correlate and deduplicate it.

View Source
const (
	HeaderTimestamp = "X-Signature-Timestamp"
	HeaderSignature = "X-Signature"
)

Headers a webhook caller sends: a unix timestamp and sha256=hex(HMAC(secret, timestamp + "." + body)).

View Source
const DefaultPort = 8080

DefaultPort is the port every starter handler listens on unless PORT says otherwise.

View Source
const DevMountPath = "/app"

DevMountPath is where the handler directory is mounted in the dev container.

Variables

View Source
var (
	ErrSignatureMissing = errors.New("functions: signature headers missing")
	ErrSignatureStale   = errors.New("functions: signature timestamp outside the replay window")
	ErrSignatureInvalid = errors.New("functions: signature does not match")
)

Errors returned by Verify.

Functions

func NewInvocationID

func NewInvocationID() (string, error)

NewInvocationID returns a random invocation id.

func NewSecret

func NewSecret() (string, error)

NewSecret returns a random webhook secret.

func ParseEnvFile

func ParseEnvFile(data []byte) map[string]string

ParseEnvFile reads KEY=VALUE lines, skipping blanks and # comments.

func RedactHeaders

func RedactHeaders(h http.Header) http.Header

RedactHeaders returns a copy of h without credential headers.

func Sign

func Sign(secret string, timestamp int64, body []byte) string

Sign returns the signature header value for body at the given unix timestamp.

func Verify

func Verify(secret, tsHeader, sigHeader string, body []byte, window time.Duration, now time.Time) (string, error)

Verify checks the timestamp is within window of now and the signature matches. It returns the signature for replay dedupe.

Types

type DevSpec

type DevSpec struct {
	Runtime string
	Image   string
	Command string
}

DevSpec is how to run a handler directory in a throwaway container.

func DetectDevSpec

func DetectDevSpec(dir, image string) (DevSpec, error)

DetectDevSpec picks the runtime of dir from its manifest file. image overrides the default image.

func (DevSpec) ShellCommand

func (s DevSpec) ShellCommand() []string

ShellCommand runs the handler from the mounted directory; the Engine API has no working-dir field on ContainerSpec.

type EnvVar

type EnvVar struct {
	Name        string `json:"name"`
	Required    bool   `json:"required"`
	Description string `json:"description"`
}

EnvVar is one environment variable a starter reads.

type File

type File struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

File is one file of a starter handler.

type Input

type Input struct {
	Function string      `json:"function"`
	Method   string      `json:"method"`
	Path     string      `json:"path"`
	Headers  http.Header `json:"headers"`
	Body     string      `json:"body"`
	At       time.Time   `json:"at"`
}

Input is the stored request of one invocation, kept only for opted-in functions.

type InputStore

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

InputStore keeps recent inputs in memory, bounded by count, body size and age.

func NewInputStore

func NewInputStore(lim InvokeLimits) *InputStore

NewInputStore builds a store honouring lim.

func (*InputStore) Forget

func (s *InputStore) Forget(function string)

Forget drops every stored input of a function, used when capture is turned off.

func (*InputStore) Get

func (s *InputStore) Get(id string) (Input, bool)

Get returns the stored input for id when it has not expired.

func (*InputStore) Put

func (s *InputStore) Put(id string, in Input)

Put stores in under id and drops the oldest entries past the count cap. A body past the byte cap is cut.

type InvokeLimits

type InvokeLimits struct {
	InputEntries   int
	InputBodyBytes int
	InputRetention time.Duration
	RequestBytes   int
	ResponseBytes  int
	Timeout        time.Duration
	LogPad         time.Duration
}

InvokeLimits are the size and time caps for test invocations and stored inputs.

func InvokeLimitsFromEnv

func InvokeLimitsFromEnv(lookup func(string) (string, bool)) InvokeLimits

InvokeLimitsFromEnv reads the caps through lookup (os.LookupEnv when nil), falling back to defaults.

type KVConfig

type KVConfig struct {
	store.KVLimits
	MaxTTLSeconds int
}

KVConfig is the server-wide key-value store sizing.

func KVConfigFromEnv

func KVConfigFromEnv(getenv func(string) string) KVConfig

KVConfigFromEnv reads KVConfig from the environment; getenv nil uses os.Getenv.

type Limiter

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

Limiter counts requests held per function. The zero value is ready to use.

func (*Limiter) Acquire

func (l *Limiter) Acquire(name string, limit int) (release func(), ok bool)

Acquire takes a slot for name; ok is false when limit slots are already taken. A limit of 0 or less never refuses.

func (*Limiter) Held

func (l *Limiter) Held(name string) int

Held reports how many requests are held for name.

type Limits

type Limits struct {
	DefaultTimeout     time.Duration
	TimeoutCeiling     time.Duration
	DefaultConcurrency int
	ConcurrencyCeiling int
}

Limits are the server-wide defaults and ceilings for per-function limits.

func LimitsFromEnv

func LimitsFromEnv(getenv func(string) string) Limits

LimitsFromEnv reads Limits from the environment; getenv nil uses os.Getenv.

func (Limits) Concurrency

func (l Limits) Concurrency(s store.FunctionSettings) int

Concurrency is the most requests held at once for s, or 0 for no limit.

func (Limits) Timeout

func (l Limits) Timeout(s store.FunctionSettings) time.Duration

Timeout is the held-request wait for s, or 0 when neither the function nor the server sets one.

type Queue

type Queue struct {
	Store  QueueStore
	Apps   QueueApps
	Target Target
	Config TriggerConfig
	Logger *slog.Logger
	Client *http.Client
	Now    func() time.Time
	// contains filtered or unexported fields
}

Queue delivers queued calls to sleeping functions with retries and a dead-letter state.

func (*Queue) Kick

func (q *Queue) Kick()

Kick asks idle workers to look for work now instead of at the next poll.

func (*Queue) Run

func (q *Queue) Run(ctx context.Context) error

Run starts the worker pool and blocks until ctx ends.

type QueueApps

type QueueApps interface {
	GetDesiredService(ctx context.Context, name string) (*store.DesiredService, error)
}

QueueApps resolves a function to its service.

type QueueStore

type QueueStore interface {
	ClaimFunctionInvocation(ctx context.Context, now time.Time) (store.FunctionInvocation, bool, error)
	SettleFunctionInvocation(ctx context.Context, id, status string, next time.Time, code int, errMsg string, now time.Time) error
	RequeueRunningFunctionInvocations(ctx context.Context, now time.Time) (int64, error)
	PruneFunctionInvocations(ctx context.Context, cutoff time.Time) (int64, error)
}

QueueStore is the persistence the worker needs.

type Runtime

type Runtime struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Files []File `json:"files"`
}

Runtime is a language Railpack builds without a Dockerfile.

func Lookup

func Lookup(id string) (Runtime, bool)

Lookup returns the runtime with the given id.

func Runtimes

func Runtimes() []Runtime

Runtimes lists the starter runtimes in a stable order.

type Starter

type Starter struct {
	ID          string   `json:"id"`
	Preset      string   `json:"preset"`
	Name        string   `json:"name"`
	Runtime     string   `json:"runtime"`
	UsesKV      bool     `json:"uses_kv"`
	Description string   `json:"description"`
	Env         []EnvVar `json:"env"`
	Files       []File   `json:"files"`
}

Starter is a complete, tested handler for one of the idea presets.

func LookupStarter

func LookupStarter(id string) (Starter, bool)

LookupStarter returns the starter with the given id.

func Starters

func Starters() []Starter

Starters lists the idea-preset starters with their files, in a stable order.

type Target

type Target interface {
	Prepare(ctx context.Context, svc *store.DesiredService) (string, error)
}

Target wakes a function and returns the base URL it answers on.

type TriggerConfig

type TriggerConfig struct {
	ReplayWindow     time.Duration
	MaxBodyBytes     int64
	MaxQueued        int
	MaxAttempts      int
	BackoffBase      time.Duration
	BackoffMax       time.Duration
	AttemptTimeout   time.Duration
	PollInterval     time.Duration
	Workers          int
	DoneRetention    time.Duration
	WebhookPerMinute int
}

TriggerConfig bounds the webhook trigger and the async queue. Every value is an env var.

func TriggerConfigFromEnv

func TriggerConfigFromEnv(lookup func(string) (string, bool)) TriggerConfig

TriggerConfigFromEnv reads the APP_FUNCTION_* variables; unset or invalid values take the documented default.

func (TriggerConfig) Backoff

func (c TriggerConfig) Backoff(attempt int) time.Duration

Backoff is the delay before the next try after attempt (1 based): base doubled per attempt, capped.

Jump to

Keyboard shortcuts

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