funcstore

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Func Store

Go Report Card PkgGoDev

Func Store is a Go package that provides persistent storage and execution for serverless functions (FaaS). Store a function once, get an ID, invoke it anywhere — in any supported runtime.

It is runtime-agnostic by design: runtimes are pluggable via the Runtime interface rather than bolted on. Ships with three runtimes:

Backed by dracory/neat, so it works with any supported database (SQLite, MySQL, Postgres, etc.) through a single *sql.DB.

Table of contents

  1. Features
  2. Installation
  3. Quick start
  4. Functions & versions
  5. Groups
  6. Runtimes
  7. Testing
  8. License

Features

  • Persistent function registry — functions are stored in the database with alias/alias-path lookup, metadata, timeout and memory-limit settings.
  • Pluggable runtimes — implement Runtime/Program to add new languages.
  • Source versioning — every save snapshots the source; FunctionRestore rolls back to any previous version.
  • Groups — hierarchical organisation with denormalised paths (GroupCreate resolves Path automatically).
  • Invoke by ID, alias path, or alias — FunctionInvoke tries each in turn.
  • Compile-checked on save — FunctionCreate fails fast if the source does not compile under the registered runtime.
  • Auto-migration — optional schema bootstrap via AutomigrateEnabled.

Installation

go get github.com/dracory/funcstore

Quick start

package main

import (
    "context"
    "database/sql"
    _ "modernc.org/sqlite" // or your preferred driver

    "github.com/dracory/funcstore"
)

func main() {
    db, err := sql.Open("sqlite", "file:faas.db")
    if err != nil {
        panic(err)
    }

    store, err := funcstore.NewStore(funcstore.StoreOptions{
        DB:                 db,
        Driver:             "sqlite",
        Runtimes:           []funcstore.Runtime{funcstore.NewGojaRuntime()},
        AutomigrateEnabled: true,
    })
    if err != nil {
        panic(err)
    }

    ctx := context.Background()

    err = store.FunctionCreate(ctx, funcstore.NewFunction().
        SetRuntime("js").
        SetSource("return input * 2").
        SetAlias("double"))
    if err != nil {
        panic(err)
    }

    out, err := store.FunctionInvoke(ctx, "double", 21) // -> 42
    if err != nil {
        panic(err)
    }
    println(out.(int64))
}

Functions & versions

FunctionInterface exposes fluent setters/getters (SetRuntime, SetSource, SetAlias, SetTimeoutMs, SetMetadata, ...). On every update the current source is snapshotted into funcstore_function_versions; manage them with FunctionVersionList, FunctionVersionGet, FunctionVersionDelete, and FunctionRestore (which first snapshots the live source so the rollback itself is recoverable).

Groups

Groups form a tree (parent_id + denormalised path). GroupCreate accepts a group whose Parent is either an ID or a path, and refuses to delete non-empty groups unless DeleteOpts.Cascade is set.

Runtimes

A Runtime compiles source into a Program; Program.Run(input) executes it with a per-invocation timeout. Register the ones you need via StoreOptions.Runtimes:

Runtimes: []funcstore.Runtime{
    funcstore.NewGojaRuntime(),
    funcstore.NewYaegiRuntime(),
    funcstore.NewPhpscriptRuntime(),
}

The PHP runtime sandboxes filesystem access to data/faas/files relative to the working directory.

Testing

go test ./...

Tests run against in-memory SQLite via modernc.org/sqlite — no external services required.

License

This project is licensed under the MIT License. You can find a copy of the license at LICENSE.

Documentation

Overview

Package funcstore provides embedded serverless function storage and execution.

Store a function once, get an ID, invoke it anywhere — in any language. FaaS persists scripts in a database and lets you execute them by ID or alias. It is runtime-agnostic by design: new runtimes are pluggable, not bolted on.

Backed by dracory/neat for 10+ database backends (SQLite, MySQL, Postgres, etc.).

Quick start:

store, _ := funcstore.NewStore(funcstore.StoreOptions{
    DB:       db,
    Driver:   "sqlite",
    Runtimes: []funcstore.Runtime{funcstore.NewGojaRuntime()},
    AutomigrateEnabled: true,
})

store.FunctionCreate(ctx, funcstore.NewFunction().
    SetRuntime("js").
    SetSource("return input * 2").
    SetAlias("double"))

out, _ := store.FunctionInvoke(ctx, "double", 21)   // -> 42

Index

Constants

View Source
const (
	COLUMN_ID         = "id"
	COLUMN_GROUP_ID   = "group_id"
	COLUMN_ALIAS      = "alias"
	COLUMN_ALIAS_PATH = "alias_path"
	COLUMN_NAME       = "name"
	COLUMN_RUNTIME    = "runtime"
	COLUMN_SOURCE     = "source"
	COLUMN_TIMEOUT_MS = "timeout_ms"
	COLUMN_MEM_LIMIT  = "mem_limit"
	COLUMN_METADATA   = "metadata"
	COLUMN_CREATED_AT = "created_at"
	COLUMN_UPDATED_AT = "updated_at"
)

Column names for the funcstore_functions table.

View Source
const (
	COLUMN_GROUP_ID_G        = "id"
	COLUMN_GROUP_SLUG        = "slug"
	COLUMN_GROUP_PARENT_ID   = "parent_id"
	COLUMN_GROUP_PATH        = "path"
	COLUMN_GROUP_DESCRIPTION = "description"
	COLUMN_GROUP_METADATA    = "metadata"
	COLUMN_GROUP_CREATED_AT  = "created_at"
	COLUMN_GROUP_UPDATED_AT  = "updated_at"
)

Column names for the funcstore_groups table.

View Source
const (
	COLUMN_VERSION_ID          = "id"
	COLUMN_VERSION_FUNCTION_ID = "function_id"
	COLUMN_VERSION_SOURCE      = "source"
	COLUMN_VERSION_CREATED_AT  = "created_at"
)

Column names for the funcstore_function_versions table.

View Source
const (
	RUNTIME_JS  = "js"
	RUNTIME_GO  = "go"
	RUNTIME_PHP = "php"
)

Runtime identifiers.

View Source
const DefaultMemLimit = 16777216

DefaultMemLimit is the default per-function memory limit in bytes.

View Source
const DefaultTimeoutMs = 5000

DefaultTimeoutMs is the default execution timeout if neither the function nor the invocation specifies one.

View Source
const Version = "0.1.0"

Version is the current package version.

Variables

View Source
var (
	ErrNotFound       = errors.New("funcstore: function not found")
	ErrGroupNotFound  = errors.New("funcstore: group not found")
	ErrRuntime        = errors.New("funcstore: runtime error")
	ErrTimeout        = errors.New("funcstore: execution timed out")
	ErrPanic          = errors.New("funcstore: runtime panic")
	ErrUnknownRuntime = errors.New("funcstore: unknown runtime")
	ErrAliasTaken     = errors.New("funcstore: alias already taken")
	ErrAliasAmbiguous = errors.New("funcstore: alias exists in multiple groups")
	ErrInvalidID      = errors.New("funcstore: invalid function ID")
)

Typed errors returned by funcstore operations.

Functions

This section is empty.

Types

type DeleteOpts

type DeleteOpts struct {
	// Cascade, when true, deletes child groups and their functions.
	// By default a non-empty group refuses to be deleted.
	Cascade bool
}

DeleteOpts controls group deletion.

type FunctionInterface

type FunctionInterface interface {
	// Identity
	// GetID returns the unique identifier of the function.
	GetID() string
	// SetID sets the unique identifier of the function.
	SetID(id string) FunctionInterface

	// Alias — human-friendly callable key (unique, optional)
	// GetAlias returns the alias of the function.
	GetAlias() string
	// SetAlias sets the alias of the function.
	SetAlias(alias string) FunctionInterface

	// Name — free-form display label (not used for lookup)
	// GetName returns the display name of the function.
	GetName() string
	// SetName sets the display name of the function.
	SetName(name string) FunctionInterface

	// Runtime — the runtime identifier (e.g. "js")
	// GetRuntime returns the runtime identifier.
	GetRuntime() string
	// SetRuntime sets the runtime identifier.
	SetRuntime(runtime string) FunctionInterface

	// Source — the script source code
	// GetSource returns the script source code.
	GetSource() string
	// SetSource sets the script source code.
	SetSource(source string) FunctionInterface

	// TimeoutMs — per-function execution timeout in milliseconds
	// GetTimeoutMs returns the timeout in milliseconds.
	GetTimeoutMs() int64
	// SetTimeoutMs sets the timeout in milliseconds.
	SetTimeoutMs(timeoutMs int64) FunctionInterface

	// MemLimit — per-function memory limit in bytes.
	// NOTE: this value is persisted but not currently enforced by any
	// runtime; in-process interpreters cannot reliably cap memory usage.
	// GetMemLimit returns the memory limit in bytes.
	GetMemLimit() int64
	// SetMemLimit sets the memory limit in bytes.
	SetMemLimit(memLimit int64) FunctionInterface

	// Metadata — caller-defined JSON blob
	// GetMetadata returns the metadata JSON string.
	GetMetadata() string
	// SetMetadata sets the metadata JSON string.
	SetMetadata(metadata string) FunctionInterface

	// Group — the group this function belongs to, expressed as a path or ID.
	// The store resolves the value to a concrete group_id at Register time.
	// GetGroup returns the group path or ID.
	GetGroup() string
	// SetGroup sets the group path or ID.
	SetGroup(group string) FunctionInterface

	// GroupID — the resolved group ID persisted by the store.
	// GetGroupID returns the resolved group ID.
	GetGroupID() string
	// SetGroupID sets the resolved group ID.
	SetGroupID(groupID string) FunctionInterface

	// AliasPath — denormalised "group/alias" path for indexed lookup.
	// GetAliasPath returns the denormalised alias path.
	GetAliasPath() string
	// SetAliasPath sets the denormalised alias path.
	SetAliasPath(aliasPath string) FunctionInterface

	// Timestamps
	// GetCreatedAt returns the creation timestamp as a unix integer string.
	GetCreatedAt() string
	// SetCreatedAt sets the creation timestamp.
	SetCreatedAt(createdAt string) FunctionInterface
	// GetUpdatedAt returns the last update timestamp as a unix integer string.
	GetUpdatedAt() string
	// SetUpdatedAt sets the last update timestamp.
	SetUpdatedAt(updatedAt string) FunctionInterface

	// DataObject methods (from embedded dataobject.DataObject)
	// Data returns all function data as a map.
	Data() map[string]string
	// Get retrieves a value by key from the function data.
	Get(key string) string
	// Set stores a value by key in the function data.
	Set(key string, value string)
	// Hydrate populates the function with data from a map.
	Hydrate(data map[string]string)
	// IsDirty returns true if the function has unsaved changes.
	IsDirty() bool
	// MarkAsDirty marks the function as dirty.
	MarkAsDirty(columns ...string)
	// MarkAsNotDirty clears the dirty state of the function.
	MarkAsNotDirty(columns ...string)
}

FunctionInterface defines the contract for FaaS function entities. A function is a persisted script that can be invoked by ID or alias.

func NewFunction

func NewFunction() FunctionInterface

// NewFunction creates a new Function instance with default values. The function is initialized with a generated UUID, empty fields, and current timestamps.

type FunctionVersionInterface

type FunctionVersionInterface interface {
	// GetID returns the unique identifier of the version.
	GetID() string
	// SetID sets the unique identifier of the version.
	SetID(id string) FunctionVersionInterface

	// FunctionID — the function this version belongs to.
	GetFunctionID() string
	SetFunctionID(functionID string) FunctionVersionInterface

	// Source — the function source code captured at this version.
	GetSource() string
	SetSource(source string) FunctionVersionInterface

	// CreatedAt — unix timestamp string of when the version was saved.
	GetCreatedAt() string
	SetCreatedAt(createdAt string) FunctionVersionInterface

	// DataObject methods (from embedded dataobject.DataObject)
	Data() map[string]string
	Get(key string) string
	Set(key string, value string)
	Hydrate(data map[string]string)
	IsDirty() bool
	MarkAsDirty(columns ...string)
	MarkAsNotDirty(columns ...string)
}

FunctionVersionInterface defines the contract for a saved source snapshot of a function. Versions are created automatically by FunctionUpdate when the source code changes, and can be restored via FunctionRestore.

func NewFunctionVersion

func NewFunctionVersion() FunctionVersionInterface

NewFunctionVersion creates a new FunctionVersion with a generated ID and current timestamp.

type GroupFilter

type GroupFilter struct {
	Parent    string
	Recursive bool
}

GroupFilter is used to list groups. Parent, when non-empty, matches groups whose parent path or ID equals it. Recursive, when true, returns all descendant groups instead of only direct children.

type GroupInterface

type GroupInterface interface {
	// GetID returns the unique identifier of the group.
	GetID() string
	// SetID sets the unique identifier of the group.
	SetID(id string) GroupInterface

	// Slug — the leaf segment of the path (e.g. "transforms").
	GetSlug() string
	SetSlug(slug string) GroupInterface

	// Parent — the parent group as a path or ID. This is the input value;
	// the store resolves it to ParentID.
	GetParent() string
	SetParent(parent string) GroupInterface

	// ParentID — the resolved parent group ID persisted by the store.
	GetParentID() string
	SetParentID(parentID string) GroupInterface

	// Path — the denormalised full path (e.g. "payments/transforms").
	GetPath() string
	SetPath(path string) GroupInterface

	// Description — a human-readable summary.
	GetDescription() string
	SetDescription(description string) GroupInterface

	// Metadata — caller-defined JSON blob.
	GetMetadata() string
	SetMetadata(metadata string) GroupInterface

	// Timestamps
	GetCreatedAt() string
	SetCreatedAt(createdAt string) GroupInterface
	GetUpdatedAt() string
	SetUpdatedAt(updatedAt string) GroupInterface

	// DataObject methods
	Data() map[string]string
	Get(key string) string
	Set(key string, value string)
	Hydrate(data map[string]string)
	IsDirty() bool
	MarkAsDirty(columns ...string)
	MarkAsNotDirty(columns ...string)
}

GroupInterface defines the contract for a function group. A group is a named node in a self-referential tree; its Path is the denormalised full path ("payments/transforms").

func NewGroup

func NewGroup() GroupInterface

NewGroup creates a new Group with a generated ID and current timestamps.

type Program

type Program interface {
	// Run executes the compiled program with the given input and returns
	// the result.
	Run(input any) (any, error)
}

Program is a compiled, executable artifact produced by a Runtime. Implementations should be safe for concurrent Run calls.

Implementations that support stopping a runaway execution should additionally implement Interrupt(). The store calls it when a function exceeds its timeout or the invocation context is cancelled, preventing abandoned goroutines from consuming CPU forever.

type Runtime

type Runtime interface {
	// Name returns the runtime identifier (e.g. "js", "tengo", "lua").
	Name() string

	// Compile parses source into an executable Program.
	Compile(source string) (Program, error)
}

Runtime is the pluggable interface for script execution backends. New runtimes (Lua, Tengo, Starlark, WASM, etc.) implement this interface and register with the store via StoreOptions.Runtimes or RegisterRuntime.

func NewGojaRuntime

func NewGojaRuntime() Runtime

NewGojaRuntime creates a JavaScript runtime backed by Goja.

func NewPhpscriptRuntime

func NewPhpscriptRuntime() Runtime

NewPhpscriptRuntime creates a PHP runtime backed by phpscript.

func NewYaegiRuntime

func NewYaegiRuntime() Runtime

NewYaegiRuntime creates a Go runtime backed by Yaegi.

type StoreInterface

type StoreInterface interface {
	// MigrateUp creates the funcstore tables and default root group.
	MigrateUp(ctx context.Context) error
	// MigrateDown drops the funcstore tables.
	MigrateDown(ctx context.Context) error

	// RegisterRuntime adds a Runtime to the store after construction.
	RegisterRuntime(r Runtime)

	// GroupCreate inserts a new group and returns it with resolved Path.
	// Parent may be a group ID or path; an empty Parent creates a root group.
	GroupCreate(ctx context.Context, g GroupInterface) (GroupInterface, error)
	// GroupFindByID retrieves a group by ID.
	GroupFindByID(ctx context.Context, id string) (GroupInterface, error)
	// GroupFindByPath retrieves a group by its denormalised path.
	GroupFindByPath(ctx context.Context, path string) (GroupInterface, error)
	// GroupList returns groups matching the filter.
	GroupList(ctx context.Context, filter GroupFilter) ([]GroupInterface, error)
	// GroupUpdate overwrites mutable fields of an existing group.
	GroupUpdate(ctx context.Context, g GroupInterface) error
	// GroupDelete removes a group by ID. Non-empty groups are refused unless Cascade is true.
	GroupDelete(ctx context.Context, id string, opts DeleteOpts) error

	// FunctionCreate inserts a new function record.
	// If the function's ID is empty, one is auto-generated.
	// The source is compile-checked against the registered runtime (fail-fast).
	// If the function's Group is empty, it is placed in the default root group.
	FunctionCreate(ctx context.Context, fn FunctionInterface) error

	// FunctionFindByID retrieves a function by its ID.
	FunctionFindByID(ctx context.Context, id string) (FunctionInterface, error)

	// FunctionFindByAlias retrieves a function by its alias or alias path.
	FunctionFindByAlias(ctx context.Context, alias string) (FunctionInterface, error)

	// FunctionInvoke executes a function by its ID, alias path, or alias.
	// The key is first tried as an ID; if not found, it is tried as an alias path and then an alias.
	// The input is passed to the runtime as the "input" binding.
	FunctionInvoke(ctx context.Context, key string, input any) (any, error)

	// FunctionList returns all stored functions ordered by created_at descending.
	FunctionList(ctx context.Context) ([]FunctionInterface, error)

	// FunctionUpdate overwrites all mutable fields of an existing function (matched by ID).
	FunctionUpdate(ctx context.Context, fn FunctionInterface) error

	// FunctionDelete removes a function by its ID.
	FunctionDelete(ctx context.Context, id string) error

	// FunctionVersionList returns all saved source versions for a function,
	// ordered newest-first by ID (UUIDv7 IDs are time-ordered, which is more
	// precise than the second-resolution created_at timestamps).
	FunctionVersionList(ctx context.Context, functionID string) ([]FunctionVersionInterface, error)

	// FunctionVersionGet retrieves a single version by its ID.
	FunctionVersionGet(ctx context.Context, versionID string) (FunctionVersionInterface, error)

	// FunctionVersionDelete removes a version by its ID.
	FunctionVersionDelete(ctx context.Context, versionID string) error

	// FunctionRestore rolls back a function's source to a previous version.
	// It first snapshots the current source (so the current state is also
	// recoverable), then sets the function's source to the version's source.
	FunctionRestore(ctx context.Context, functionID string, versionID string) error

	// DB returns the underlying *sql.DB (useful for app-level integration).
	DB() *sql.DB
}

StoreInterface defines the persistence and execution contract for funcstore functions. Implementations may use any database backend; the default SQL-backed store (NewStore) works with any *sql.DB (SQLite, MySQL, Postgres, etc.).

func NewStore

func NewStore(opts StoreOptions) (StoreInterface, error)

NewStore creates a SQL-backed StoreInterface from the given options.

type StoreOptions

type StoreOptions struct {
	DB                 *sql.DB
	Driver             string    // "sqlite", "mysql", "postgres" — controls placeholder syntax
	TableName          string    // defaults to "funcstore_functions"
	GroupsTableName    string    // defaults to "funcstore_groups"
	VersionsTableName  string    // defaults to "funcstore_function_versions"
	AutomigrateEnabled bool      // if true, runs MigrateUp on construction
	Runtimes           []Runtime // runtimes to register (e.g. NewGojaRuntime())
}

StoreOptions configures a new SQL-backed store.

Jump to

Keyboard shortcuts

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