functions

package
v0.2.37 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package functions emulates the altengine functions service: sandboxed JavaScript, deployed as one bundled ES module and invoked over HTTP, with capability-scoped access to the other services and nothing else.

WHAT IS FAITHFUL, AND WHAT IS NOT

Faithful: the deploy API, the capability model (a function reaches only the services and instances its grants name), the two secret exposures, the outbound allowlist and its SSRF refusals, CORS, and the shape of `env` and of `export default { fetch }`. Code you deploy here runs there.

NOT faithful, and deliberately: this is not a security sandbox. Hosted, tenant code runs in a hard sandbox with no ambient capabilities at all. Here it runs in an embedded JS interpreter inside the emulator process, because the point of running locally is to see your own code work — not to defend the machine against it. Never point this at code you would not run yourself, and never expose the emulator beyond localhost.

The interpreter is ES2020-era and single-threaded. Anything relying on a real Workers runtime detail (streaming bodies, WebSocket upgrades, precise timer semantics) is worth checking against a real deploy before trusting it.

Index

Constants

View Source
const (
	MaxCodeBytes = 5 << 20 // 5 MiB, same as hosted
	// The biggest REQUEST body a deployed function may receive. Nothing to do with the
	// code limit above, which it used to share — a function that accepts an uploaded file
	// inline is not a function with a big bundle, and reading a request through the code
	// limit truncated it at 1 MiB.
	MaxRequestBytes = 10 << 20 // 10 MiB
	// Stored versions kept per function, from the instance's `keepVersions` setting. The active
	// version is always kept on top of it, however old.
	DefaultKeepVersions = 3
	MaxKeepVersions     = 50
	MaxSecrets          = 32
	MaxSecretSize       = 4096
	DefaultCPUMs        = 50
	MaxCPUMs            = 30000
	DefaultSubReq       = 50
	MaxSubReq           = 1000
)

Limits mirror the hosted service so a bundle that is refused there is refused here.

View Source
const MaxSchedulesPerFn = 5

MaxSchedulesPerFn mirrors the hosted cap.

View Source
const MaxSecretHosts = 10

MaxSecretHosts caps the hosts one egress secret may name, as hosted.

Variables

View Source
var ErrBodyTooLarge = errors.New("request body too large")

ErrBodyTooLarge is returned by readBody when the request exceeds MaxRequestBytes.

Functions

func DefaultFunction added in v0.2.33

func DefaultFunction(cfg map[string]any) string

DefaultFunction reads the function that answers every path no function is named for, or "" for none. A value that is not a string reads as none, as hosted parses a stored setting.

func KeepVersions

func KeepVersions(cfg map[string]any) int

KeepVersions reads the retention setting from an instance's config. A missing or malformed value reads as the default, exactly as hosted parses a stored setting.

func NextRun

func NextRun(f CronFields, after time.Time) time.Time

NextRun is the first time strictly after `after` that the expression matches, or the zero time if it never does.

Scans DAY BY DAY, and only within a matching day walks that day's candidate times — which are just the parsed hour and minute lists. Minute-by-minute scanning would have to walk millions of steps for a rare-but-valid expression like `0 0 29 2 *`.

func NormalizeSchedules

func NormalizeSchedules(lines []string) ([]string, error)

NormalizeSchedules turns deploy input into the stored list.

THE SEPARATOR IS THE NEWLINE, and only the newline: a comma is a LIST inside a cron field (`0 9,17 * * *` is 9am and 5pm), so splitting on commas would shred valid expressions. Blanks are dropped and duplicates collapsed.

func Soonest

func Soonest(exprs []string, after time.Time) time.Time

Soonest is the earliest next-run across every expression: the function's real due time.

func ValidateConfig

func ValidateConfig(cfg map[string]any) error

ValidateConfig refuses a functions config whose `keepVersions` is not an integer in 1..50, or whose rate limit or region the hosted service would refuse.

func ValidateCron

func ValidateCron(expr string) (string, error)

ValidateCron checks an expression for storage, rejecting one that can never match.

Types

type Config

type Config struct {
	Functions    []*Function          `json:"functions"`
	AllowedHosts []string             `json:"allowedHosts"`
	CORSOrigins  []string             `json:"corsOrigins"`
	Secrets      map[string]Secret    `json:"secrets"`
	Versions     map[string][]Version `json:"versions"` // fn name -> history, newest last
}

Config is the per-instance settings blob, mirroring the hosted `instance_config` rows.

func (*Config) EgressSecrets

func (c *Config) EgressSecrets() map[string]Secret

EgressSecrets are the secrets only the outbound proxy may see, for {{NAME}} expansion, with where each may be sent.

func (*Config) EnvSecrets

func (c *Config) EnvSecrets() map[string]string

EnvSecrets are the values the sandbox may read as env.NAME.

func (*Config) Find

func (c *Config) Find(name string) *Function

Find returns the named function from a config, or nil.

func (*Config) Route added in v0.2.33

func (c *Config) Route(segment, defaultFn string, allowDefault bool) *Function

Route picks the function a request answers to: the one its first path segment names, else the default function — never for a console prefix, and never when allowDefault is false (a platform trigger names its function exactly, and must not reach a different one).

func (*Config) SecretNames

func (c *Config) SecretNames() []map[string]any

SecretNames lists names and exposure, never values — the same contract as hosted, where a value cannot be read back once written.

type CronFields

type CronFields struct {
	Minute []int
	Hour   []int
	DOM    []int
	Month  []int
	DOW    []int
}

CronFields is one parsed expression: the set of values each field admits.

func ParseCron

func ParseCron(expr string) (CronFields, error)

ParseCron parses and validates an expression.

type DeployRequest

type DeployRequest struct {
	Name   string            `json:"name"`
	Code   string            `json:"code"`
	Grants map[string]string `json:"grants"`
	// Pointers, so an omitted field inherits while an explicit 0 subrequests is kept: a
	// function may be allowed no outbound calls at all.
	CPUMs       *int `json:"cpuMs"`
	SubRequests *int `json:"subRequests"`
	// json.RawMessage, not []string: an ABSENT field must inherit the deployed schedules
	// while an explicit null clears them, and both decode to a nil slice. Only the raw
	// bytes tell the two apart. Accepts a list or one newline-separated string.
	Schedules json.RawMessage `json:"schedules"`
	// Alias, from before one expression turned out not to be enough.
	Schedule json.RawMessage `json:"schedule"`
	Activate *bool           `json:"activate"`
}

DeployRequest is the body of POST /v1/functions/{instance}/deploy.

type Function

type Function struct {
	Name          string            `json:"name"`
	Grants        map[string]string `json:"grants"`
	ActiveVersion int               `json:"activeVersion"`
	CPUMs         int               `json:"cpuMs"`
	SubRequests   int               `json:"subRequests"`
	// Five-field UTC cron expressions. A LIST because one expression cannot express every
	// schedule: hour and day-of-week are ANDed within an expression, so "09:00 weekdays
	// AND 12:00 Saturday" is genuinely two.
	Schedules []string `json:"schedules,omitempty"`
}

Function is one deployed entry point.

type Handler

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

Handler serves both surfaces.

func NewHandler

func NewHandler(reg *control.Registry, a *auth.Store, store *Store, mux http.Handler) *Handler

NewHandler builds the functions handler. `mux` is the emulator's own router: stub calls are dispatched into it in-process, so `env.datastore` behaves exactly as the REST API does rather than as a second implementation of it.

func (*Handler) Register

func (h *Handler) Register(mux *http.ServeMux)

Register mounts both the deploy API and the invocation prefix.

func (*Handler) StartScheduler

func (h *Handler) StartScheduler(ctx context.Context)

StartScheduler runs the tick loop until ctx is cancelled.

func (*Handler) WithHost

func (h *Handler) WithHost(addr string) *Handler

WithHost tells the bindings where this emulator answers, so a URL minted inside a function call (a blob upload or download, a channel subscribe) points somewhere the caller can actually reach. See bindings.stampHost.

type Secret

type Secret struct {
	Value      string   `json:"value"`
	Egress     bool     `json:"egress"`
	Hosts      []string `json:"hosts,omitempty"`
	QueryParam string   `json:"queryParam,omitempty"`
}

Secret carries its exposure. Hosted, an `egress` secret exists ONLY inside the outbound proxy and never enters the sandbox; the same split is enforced here so a function that works locally is not relying on a value it will not be given in production.

An egress secret also says where it may go: Hosts (allowlist syntax) and, optionally, the one QueryParam it may be placed in. Hosts is nil only on a secret stored before binding existed, which keeps expanding into headers toward any allowlisted host until it is bound.

type Store

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

Store holds deployed code and per-instance config. Code lives on disk when the emulator was given a data dir, so a restart does not lose a deploy; in memory otherwise.

func NewStore

func NewStore(dataDir string) (*Store, error)

NewStore builds the store, loading anything previously persisted. It fails rather than start empty when the persisted state exists but cannot be read.

func (*Store) Activate

func (s *Store) Activate(instanceID, name string, version int) (int, error)

Activate points a function at an existing version (rollback), returning the version it was serving before.

func (*Store) Code

func (s *Store) Code(instanceID, name string, version int) (string, bool)

Code returns one version's source.

func (*Store) Config

func (s *Store) Config(instanceID string) *Config

Config returns a COPY of an instance's config, so callers cannot mutate shared state.

func (*Store) DeleteFunction

func (s *Store) DeleteFunction(instanceID, name string) (int, error)

DeleteFunction removes a function, its schedules, and every stored version. Returns how many versions were removed.

func (*Store) DeleteVersion

func (s *Store) DeleteVersion(instanceID, name string, version int) error

DeleteVersion removes one stored version. Refuses the version being served, as hosted does: removing it would leave the function pointing at code that no longer exists.

func (*Store) Deploy

func (s *Store) Deploy(instanceID string, req DeployRequest, keep int) (map[string]any, error)

Deploy stores a new version and (by default) activates it.

Mirrors the hosted pipeline including the parts that are easy to get wrong: an omitted field INHERITS from the existing function rather than resetting it, so redeploying code does not silently drop the grants the function needs.

keep is the instance's retention setting (see KeepVersions); history beyond it is pruned after the deploy, never including the version the function serves.

func (*Store) Prune

func (s *Store) Prune(instanceID string, keep int) int

Prune applies a retention setting to every function in an instance, returning how many versions were removed. Called when the setting is lowered, so it takes effect now rather than at each function's next deploy.

func (*Store) SetSecrets

func (s *Store) SetSecrets(instanceID string, in map[string]json.RawMessage) (map[string]Secret, error)

SetSecrets replaces the whole secret map, resolving keep-existing entries.

A submitted entry may omit its value to mean "keep the stored one" — hosted, values are write-only and cannot be read back, so without this an editor could not change one secret's exposure without re-typing every other credential.

func (*Store) SetSettings

func (s *Store) SetSettings(instanceID string, allowedHosts, corsOrigins []string) error

SetSettings replaces the outbound allowlist and CORS origins.

func (*Store) Versions

func (s *Store) Versions(instanceID, name string) []Version

Versions returns the deploy history for one function, newest first.

type Version

type Version struct {
	Version   int    `json:"version"`
	SizeBytes int    `json:"size_bytes"`
	SHA256    string `json:"sha256"`
	CreatedAt int64  `json:"created_at"`
}

Version is one immutable deploy of one function.

Jump to

Keyboard shortcuts

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