functions

package
v1.8.4 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventAccepted     = "accepted"
	EventRunning      = "running"
	EventCommitted    = "committed"
	EventFailed       = "failed"
	EventDeadLettered = "dead_lettered"
)

EventDeliveryStatus for async function invocations.

View Source
const (
	TenantRequired       = "TENANT_REQUIRED"
	TenantNotFound       = "TENANT_NOT_FOUND"
	TenantNotActive      = "TENANT_NOT_ACTIVE"
	TenantScopeForbidden = "TENANT_SCOPE_FORBIDDEN"
	TenantDBNotReady     = "TENANT_DB_NOT_READY"
)

Stable tenant-scope error codes for function draft test and live callable.

View Source
const ABIVersion = "1"

ABIVersion is the host/guest contract version for Apito Functions.

Variables

View Source
var EmbeddedApitoFunctionsSDK string
View Source
var GlobalInvocationRegistry = NewInvocationRegistry()

GlobalInvocationRegistry is the process-wide registry used by Deno bridge + gateway.

Functions

func AllowCallableRuntime

func AllowCallableRuntime(fn *models.ApitoFunction) bool

AllowCallableRuntime reports whether the REST /function route may execute this runtime. Deno/wasm require secret verification; Hashicorp may still use the route for legacy plugins.

func DataGatewaySubject

func DataGatewaySubject(projectID string) string

DataGatewaySubject builds the NATS subject for worker→engine data RPC.

func DeployDraft

DeployDraft creates an immutable revision + successful build + active deployment and updates the function's ActiveRevisionID. Caller persists rows + function.

func EventSubject

func EventSubject(projectID, functionName string) string

EventSubject builds the JetStream-oriented subject for async function events.

func FindFunctionByName

func FindFunctionByName(project *models.Project, name string) *models.ApitoFunction

FindFunctionByName looks up a function on the project schema.

func InvokeSubject

func InvokeSubject(projectID, functionName string) string

InvokeSubject builds the NATS subject for a synchronous function invoke.

func RegisterCoreDataOps

func RegisterCoreDataOps(g *EngineDataGateway, batch ProjectBatchExecutor)

RegisterCoreDataOps registers the standard data op names on a gateway. Handlers must be supplied by the engine (project driver bound); this only installs stubs that return "not wired" so capability checks can be tested.

func RegisterReadDataOps added in v1.7.13

func RegisterReadDataOps(g *EngineDataGateway, deps GatewayDeps, registry *InvocationRegistry)

RegisterReadDataOps replaces stubbed read handlers with driver-backed implementations. Write / http / email / jwt / secrets stay unavailable until separately implemented.

func RequireCapability

func RequireCapability(caps []string) func(context.Context, *DataGatewayCall) error

RequireCapability is a helper CheckCapability for data.read/data.write prefixes.

func ResolveActiveSource added in v1.7.13

func ResolveActiveSource(ctx context.Context, store ArtifactStore, fn *models.ApitoFunction) string

ResolveActiveSource returns the deployed revision source for live execution. Falls back to draft Source for never-deployed / legacy functions.

func RollbackDeployment

func RollbackDeployment(fn *models.ApitoFunction, target *models.FunctionRevision, deployedBy string) *models.FunctionDeployment

RollbackDeployment points the function at a previous revision. Does not mutate draft Source — only ActiveRevisionID / BinaryURL for live execution.

func ValidateBatchOps

func ValidateBatchOps(ops []BatchOp) error

ValidateBatchOps performs structural validation before execution.

func VerifyFunctionSecret

func VerifyFunctionSecret(fn *models.ApitoFunction, provided string) error

VerifyFunctionSecret compares the caller-provided hash to the function's RestAPISecretURLKey using constant-time comparison. Empty stored secrets fail closed.

Types

type ArtifactStore

type ArtifactStore interface {
	Put(ctx context.Context, key string, data []byte, hash string) error
	Get(ctx context.Context, key string) ([]byte, string, error)
	Delete(ctx context.Context, key string) error
}

ArtifactStore retrieves immutable function artifacts.

type BatchOp

type BatchOp struct {
	Op         string                 `json:"op"` // create, update, delete, connect, disconnect, inc
	Model      string                 `json:"model"`
	ID         string                 `json:"id,omitempty"`
	Payload    map[string]interface{} `json:"payload,omitempty"`
	Connect    map[string]interface{} `json:"connect,omitempty"`
	Disconnect map[string]interface{} `json:"disconnect,omitempty"`
	Field      string                 `json:"field,omitempty"` // for inc
	By         float64                `json:"by,omitempty"`    // for inc
}

BatchOp is one declarative mutation inside an atomic transaction.

type BatchRequest

type BatchRequest struct {
	IdempotencyKey string    `json:"idempotency_key"`
	Operations     []BatchOp `json:"operations"`
}

BatchRequest is the declarative unit-of-work form for ProjectBatchExecutor.

type BatchResult

type BatchResult struct {
	OK     bool                   `json:"ok"`
	IDs    []string               `json:"ids,omitempty"`
	Error  string                 `json:"error,omitempty"`
	Replay bool                   `json:"replay,omitempty"`
	Result map[string]interface{} `json:"result,omitempty"`
}

BatchResult is the outcome of an atomic batch.

func (*BatchResult) StatusCommitted

func (r *BatchResult) StatusCommitted() bool

type DataGatewayCall

type DataGatewayCall struct {
	InvocationID string                 `json:"invocation_id"`
	ProjectID    string                 `json:"project_id"`
	TenantID     string                 `json:"tenant_id,omitempty"`
	Op           string                 `json:"op"`
	Payload      map[string]interface{} `json:"payload,omitempty"`
}

DataGatewayCall is a host-side data/integration request from a function.

type DataGatewayResponse

type DataGatewayResponse struct {
	OK    bool                   `json:"ok"`
	Data  map[string]interface{} `json:"data,omitempty"`
	Error string                 `json:"error,omitempty"`
}

DataGatewayResponse is the host response for a data/integration call.

type DataOpHandler

type DataOpHandler func(ctx context.Context, call *DataGatewayCall) (*DataGatewayResponse, error)

DataOpHandler handles one gateway op.

type DefaultLimitsProvider

type DefaultLimitsProvider struct{}

DefaultLimitsProvider always returns DefaultCallableLimits.

func (DefaultLimitsProvider) LimitsFor

type DenoRuntimeProvider

type DenoRuntimeProvider struct {
	DenoPath string
	WorkDir  string
	Gateway  FunctionDataGateway
	Registry *InvocationRegistry
}

DenoRuntimeProvider executes TypeScript/JavaScript via a pinned Deno binary. When Deno is not installed, Execute returns runtime_unavailable (use StubRuntimeProvider in tests).

func (*DenoRuntimeProvider) Execute

func (*DenoRuntimeProvider) Name

func (p *DenoRuntimeProvider) Name() string

type EngineDataGateway

type EngineDataGateway struct {

	// CheckCapability returns nil if the call is allowed.
	CheckCapability func(ctx context.Context, call *DataGatewayCall) error
	HostCallCount   map[string]int // invocationID → count
	MaxHostCalls    int
	// contains filtered or unexported fields
}

EngineDataGateway is a capability-aware data gateway backed by injectable handlers. The engine wires real project-driver operations; this package stays free of driver imports.

func NewEngineDataGateway

func NewEngineDataGateway() *EngineDataGateway

NewEngineDataGateway creates an empty gateway.

func (*EngineDataGateway) Handle

Handle implements FunctionDataGateway.

func (*EngineDataGateway) Register

func (g *EngineDataGateway) Register(op string, h DataOpHandler)

Register binds an op name to a handler.

type EventDispatcher

type EventDispatcher interface {
	Publish(ctx context.Context, msg *EventMessage) error
	Subscribe(ctx context.Context, handler func(ctx context.Context, msg *EventMessage) error) (func() error, error)
}

EventDispatcher accepts async events for at-least-once delivery.

type EventMessage

type EventMessage struct {
	ID             string                 `json:"id"`
	ProjectID      string                 `json:"project_id"`
	Function       string                 `json:"function"`
	Trigger        string                 `json:"trigger"` // webhook, email, payment, lifecycle
	IdempotencyKey string                 `json:"idempotency_key"`
	Payload        map[string]interface{} `json:"payload"`
	Attempt        int                    `json:"attempt"`
	MaxDeliver     int                    `json:"max_deliver"`
}

EventMessage is an async trigger payload (webhook, email, payment, lifecycle).

type FilesystemArtifactStore

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

FilesystemArtifactStore stores immutable artifacts under a root directory.

func NewFilesystemArtifactStore

func NewFilesystemArtifactStore(dir string) (*FilesystemArtifactStore, error)

NewFilesystemArtifactStore creates a store rooted at dir (created if missing).

func (*FilesystemArtifactStore) Delete

func (s *FilesystemArtifactStore) Delete(ctx context.Context, key string) error

func (*FilesystemArtifactStore) Get

func (*FilesystemArtifactStore) Put

func (s *FilesystemArtifactStore) Put(ctx context.Context, key string, data []byte, hash string) error

type FunctionDataGateway

type FunctionDataGateway interface {
	Handle(ctx context.Context, call *DataGatewayCall) (*DataGatewayResponse, error)
}

FunctionDataGateway fulfills host data/integration calls from a sandbox.

type FunctionInvoker

type FunctionInvoker interface {
	Invoke(ctx context.Context, env *InvocationEnvelope) (*InvocationResult, error)
}

FunctionInvoker dispatches an invocation to the configured transport/runtime.

type FunctionLimits

type FunctionLimits struct {
	MemoryBytes      int64
	Timeout          time.Duration
	MaxRequestBytes  int64
	MaxResponseBytes int64
	MaxLogBytes      int64
	MaxHostCalls     int
	MaxConcurrency   int
}

FunctionLimits captures per-invocation / per-function resource ceilings.

func DefaultCallableLimits

func DefaultCallableLimits() FunctionLimits

DefaultCallableLimits returns conservative defaults for callable functions.

type FunctionLimitsProvider

type FunctionLimitsProvider interface {
	LimitsFor(ctx context.Context, projectID string, fn *models.ApitoFunction) (FunctionLimits, error)
}

FunctionLimitsProvider supplies plan/tier limits (pro injects; open-core uses defaults).

type FunctionTransport

type FunctionTransport interface {
	Request(ctx context.Context, subject string, payload []byte, timeout time.Duration) ([]byte, error)
	RespondHandler(ctx context.Context, subject string, queueGroup string, handler func(payload []byte) ([]byte, error)) (func() error, error)
	Close() error
}

FunctionTransport delivers invocations to workers (local or NATS).

type GatewayBridge added in v1.7.13

type GatewayBridge struct {
	URL          string
	Token        string
	InvocationID string
	// contains filtered or unexported fields
}

GatewayBridge is an ephemeral loopback HTTP server for Deno → host data calls.

func StartGatewayBridge added in v1.7.13

func StartGatewayBridge(ctx context.Context, gateway FunctionDataGateway, inv *InvocationContext) (*GatewayBridge, error)

StartGatewayBridge listens on 127.0.0.1 and serves POST /call for one invocation.

func (*GatewayBridge) Close added in v1.7.13

func (b *GatewayBridge) Close()

Close shuts down the bridge.

type GatewayDeps added in v1.7.13

type GatewayDeps interface {
	// GetProjectDriver returns the project DB for the invocation's trusted DB context.
	GetProjectDriver(ctx context.Context, inv *InvocationContext) (interfaces.ProjectDBInterface, error)
	// ResolveModel maps a guest model name to a schema model.
	ResolveModel(inv *InvocationContext, modelArg string) (*models.ModelType, error)
	// NewParam clones the invocation param for a driver call.
	NewParam(inv *InvocationContext) *models.CommonSystemParams
}

GatewayDeps resolves project DB access for function data ops. Implemented by the engine/resolver layer so open-core stays free of driver imports beyond the interfaces package.

type HookLimitsProvider

type HookLimitsProvider struct {
	Hook func(ctx context.Context, projectID string, fn *models.ApitoFunction) (memoryBytes int64, timeoutMs int64, maxConcurrency int, err error)
}

HookLimitsProvider adapts Config.FunctionLimitsHook to FunctionLimitsProvider.

func (HookLimitsProvider) LimitsFor

func (p HookLimitsProvider) LimitsFor(ctx context.Context, projectID string, fn *models.ApitoFunction) (FunctionLimits, error)

type InvocationContext added in v1.7.13

type InvocationContext struct {
	Envelope     *InvocationEnvelope
	DBCtx        context.Context
	Param        *models.CommonSystemParams
	Project      *models.Project
	Capabilities []string
	Gateway      FunctionDataGateway
}

InvocationContext holds trusted host state for one function invocation. Guest code never supplies project/tenant/capabilities — only the registry does.

type InvocationEnvelope

type InvocationEnvelope struct {
	Version      string                 `json:"version"`
	InvocationID string                 `json:"invocation_id"`
	ProjectID    string                 `json:"project_id"`
	TenantID     string                 `json:"tenant_id,omitempty"`
	Function     string                 `json:"function"`
	RevisionID   string                 `json:"revision_id,omitempty"`
	Runtime      string                 `json:"runtime"`
	UserID       string                 `json:"user_id,omitempty"`
	Role         string                 `json:"role,omitempty"`
	Principal    Principal              `json:"principal"`
	Capabilities []string               `json:"capabilities,omitempty"`
	Request      map[string]interface{} `json:"request"`
	DeadlineMs   int64                  `json:"deadline_ms"`
	Idempotency  string                 `json:"idempotency_key,omitempty"`
	ArtifactKey  string                 `json:"artifact_key,omitempty"`
	ArtifactHash string                 `json:"artifact_hash,omitempty"`
	Source       string                 `json:"source,omitempty"`
	Handler      string                 `json:"handler,omitempty"`
}

InvocationEnvelope is the versioned request payload for a function invocation.

func BuildEnvelope

func BuildEnvelope(fn *models.ApitoFunction, projectID, tenantID, userID, role string, request map[string]interface{}, invocationID string) *InvocationEnvelope

BuildEnvelope constructs an invocation envelope from a function definition and GraphQL/REST args.

type InvocationRegistry added in v1.7.13

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

InvocationRegistry maps invocation IDs to trusted host context.

func NewInvocationRegistry added in v1.7.13

func NewInvocationRegistry() *InvocationRegistry

NewInvocationRegistry creates an empty registry.

func (*InvocationRegistry) Get added in v1.7.13

func (r *InvocationRegistry) Get(invocationID string) (*InvocationContext, error)

Get returns a registered invocation context.

func (*InvocationRegistry) Register added in v1.7.13

func (r *InvocationRegistry) Register(inv *InvocationContext) error

Register stores context for an invocation.

func (*InvocationRegistry) Unregister added in v1.7.13

func (r *InvocationRegistry) Unregister(invocationID string)

Unregister removes an invocation context.

type InvocationResult

type InvocationResult struct {
	Version      string                 `json:"version"`
	OK           bool                   `json:"ok"`
	Response     map[string]interface{} `json:"response,omitempty"`
	Error        string                 `json:"error,omitempty"`
	ErrorClass   string                 `json:"error_class,omitempty"` // timeout, oom, permission, egress, abort, …
	Logs         []LogEntry             `json:"logs,omitempty"`
	DurationMs   int64                  `json:"duration_ms,omitempty"`
	HostCalls    int                    `json:"host_calls,omitempty"`
	ResultDigest string                 `json:"result_digest,omitempty"`
}

InvocationResult is the versioned response from a function invocation.

type LocalTransport

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

LocalTransport is an in-process FunctionTransport for self-host/dev and tests.

func NewLocalTransport

func NewLocalTransport() *LocalTransport

NewLocalTransport creates an empty local transport.

func (*LocalTransport) Close

func (t *LocalTransport) Close() error

func (*LocalTransport) Request

func (t *LocalTransport) Request(ctx context.Context, subject string, payload []byte, timeout time.Duration) ([]byte, error)

func (*LocalTransport) RespondHandler

func (t *LocalTransport) RespondHandler(ctx context.Context, subject string, _ string, handler func(payload []byte) ([]byte, error)) (func() error, error)

type LogEntry

type LogEntry struct {
	Level   string `json:"level"`
	Message string `json:"message"`
	At      string `json:"at,omitempty"`
}

LogEntry is a bounded structured log line from a function.

type ManagerOption

type ManagerOption func(*RuntimeManager)

ManagerOption configures RuntimeManager.

func WithArtifactStore

func WithArtifactStore(s ArtifactStore) ManagerOption

WithArtifactStore sets the artifact store.

func WithDataGateway

func WithDataGateway(g FunctionDataGateway) ManagerOption

WithDataGateway sets the data gateway.

func WithGlobalConcurrency

func WithGlobalConcurrency(n int) ManagerOption

WithGlobalConcurrency sets the process-wide concurrency semaphore.

func WithLimitsProvider

func WithLimitsProvider(p FunctionLimitsProvider) ManagerOption

WithLimitsProvider sets the limits provider.

func WithTransport

func WithTransport(t FunctionTransport) ManagerOption

WithTransport sets the function transport.

type MemoryBatchExecutor

type MemoryBatchExecutor struct {
	Apply func(ctx context.Context, projectID, tenantScope string, op BatchOp) (string, error)
	// contains filtered or unexported fields
}

MemoryBatchExecutor is an in-memory ProjectBatchExecutor for tests and drivers that have not yet implemented transactional batches. Production SQLite wiring replaces this with a driver-backed executor.

func NewMemoryBatchExecutor

func NewMemoryBatchExecutor() *MemoryBatchExecutor

NewMemoryBatchExecutor creates a batch executor with an optional Apply hook.

func (*MemoryBatchExecutor) ExecuteBatch

func (e *MemoryBatchExecutor) ExecuteBatch(ctx context.Context, projectID, tenantScope string, req *BatchRequest) (*BatchResult, error)

type MemoryEventDispatcher

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

MemoryEventDispatcher is an in-process event bus for tests/self-host without JetStream.

func NewMemoryEventDispatcher

func NewMemoryEventDispatcher() *MemoryEventDispatcher

func (*MemoryEventDispatcher) DeadLetters

func (d *MemoryEventDispatcher) DeadLetters() []*EventMessage

func (*MemoryEventDispatcher) Publish

func (d *MemoryEventDispatcher) Publish(ctx context.Context, msg *EventMessage) error

func (*MemoryEventDispatcher) Subscribe

func (d *MemoryEventDispatcher) Subscribe(ctx context.Context, handler func(ctx context.Context, msg *EventMessage) error) (func() error, error)

type NATSConn

type NATSConn interface {
	RequestWithContext(ctx context.Context, subject string, data []byte) ([]byte, error)
	QueueSubscribe(subject, queue string, handler func(subject string, data []byte) ([]byte, error)) (func() error, error)
	Close()
}

NATSConn is the minimal NATS surface used by NATSFunctionTransport. Implementations wrap nats.Conn without importing nats into every build.

type NATSFunctionTransport

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

NATSFunctionTransport implements FunctionTransport over authenticated NATS.

func NewNATSFunctionTransport

func NewNATSFunctionTransport(conn NATSConn) *NATSFunctionTransport

NewNATSFunctionTransport wraps a NATS connection.

func (*NATSFunctionTransport) Close

func (t *NATSFunctionTransport) Close() error

func (*NATSFunctionTransport) Request

func (t *NATSFunctionTransport) Request(ctx context.Context, subject string, payload []byte, timeout time.Duration) ([]byte, error)

func (*NATSFunctionTransport) RespondHandler

func (t *NATSFunctionTransport) RespondHandler(ctx context.Context, subject string, queueGroup string, handler func(payload []byte) ([]byte, error)) (func() error, error)

type Principal

type Principal struct {
	Mode   string `json:"mode"` // caller | service
	UserID string `json:"user_id,omitempty"`
	Role   string `json:"role,omitempty"`
}

Principal describes who the function runs as.

type ProjectBatchExecutor

type ProjectBatchExecutor interface {
	ExecuteBatch(ctx context.Context, projectID, tenantScope string, req *BatchRequest) (*BatchResult, error)
}

ProjectBatchExecutor runs declarative ops in one driver transaction (optional capability).

type RuntimeManager

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

RuntimeManager routes Apito Function invocations to the correct RuntimeProvider via a FunctionTransport. HashiCorp plugins remain outside this manager.

func NewRuntimeManager

func NewRuntimeManager(providers []RuntimeProvider, opts ...ManagerOption) *RuntimeManager

NewRuntimeManager creates a manager with the given providers.

func (*RuntimeManager) Artifacts

func (m *RuntimeManager) Artifacts() ArtifactStore

Artifacts returns the artifact store (may be nil).

func (*RuntimeManager) DataGateway

func (m *RuntimeManager) DataGateway() FunctionDataGateway

DataGateway returns the configured data gateway (may be nil).

func (*RuntimeManager) Invoke

Invoke implements FunctionInvoker.

func (*RuntimeManager) RegisterProvider

func (m *RuntimeManager) RegisterProvider(p RuntimeProvider)

RegisterProvider adds or replaces a runtime provider.

type RuntimeProvider

type RuntimeProvider interface {
	Name() string
	Execute(ctx context.Context, env *InvocationEnvelope, limits FunctionLimits) (*InvocationResult, error)
}

RuntimeProvider executes a function for a specific runtime (deno, wasm).

type StubRuntimeProvider

type StubRuntimeProvider struct {
	RuntimeName string
}

StubRuntimeProvider is a test/dev provider that echoes the request (no Deno binary required).

func (*StubRuntimeProvider) Execute

func (*StubRuntimeProvider) Name

func (p *StubRuntimeProvider) Name() string

type TenantScopeError added in v1.7.13

type TenantScopeError struct {
	Code    string
	Message string
}

TenantScopeError is returned before Deno/SQL when SaaS tenant scope is missing or invalid.

func AsTenantScopeError added in v1.7.13

func AsTenantScopeError(err error) (*TenantScopeError, bool)

AsTenantScopeError returns the typed error when present.

func NewTenantScopeError added in v1.7.13

func NewTenantScopeError(code, message string) *TenantScopeError

func (*TenantScopeError) Error added in v1.7.13

func (e *TenantScopeError) Error() string

type WazeroRuntimeProvider

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

WazeroRuntimeProvider executes prebuilt WASM artifacts with memory-page limits (via RuntimeConfig) and context cancellation. It does not claim native CPU fuel.

func NewWazeroRuntimeProvider

func NewWazeroRuntimeProvider(ctx context.Context) *WazeroRuntimeProvider

NewWazeroRuntimeProvider creates a provider.

func (*WazeroRuntimeProvider) Close

func (*WazeroRuntimeProvider) Execute

func (*WazeroRuntimeProvider) Name

func (p *WazeroRuntimeProvider) Name() string

Jump to

Keyboard shortcuts

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