script

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 16 Imported by: 0 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.

Documentation

Overview

Package script provides the JavaScript runtime using goja (pure Go ES5.1+). A build tag switches to QJS+Wazero when available.

Package script provides the JavaScript runtime for Kigae's extensibility system. It defines the Runner interface and types for script execution.

Index

Constants

View Source
const (
	MaxAsyncHookAttempts     uint8 = 5
	MaxAsyncHookBatch              = 32
	MaxAsyncHookPayloadBytes       = 1 << 20
	MaxAsyncHookTimeout            = 4 * time.Minute
)

Variables

View Source
var ErrTenantCapacity = errors.New("script tenant concurrency capacity exhausted")

Functions

func AsyncHookInvocationSchemaStatements

func AsyncHookInvocationSchemaStatements(dialect db.Dialect) ([]string, error)

func IsAfterEvent

func IsAfterEvent(e Event) bool

IsAfterEvent returns true if the event is an after_* (best-effort) hook.

func IsBeforeEvent

func IsBeforeEvent(e Event) bool

IsBeforeEvent returns true if the event is a before_* (can reject) hook.

Types

type AsyncHookClaim

type AsyncHookClaim struct {
	Invocation AsyncHookInvocation
	Owner      string
	Fence      uint64
	Attempt    uint8
	LeaseUntil time.Time
}

AsyncHookClaim is a fenced lease. The database lease, not LeaseUntil's process-clock estimate, is authoritative.

type AsyncHookInvocation

type AsyncHookInvocation struct {
	TenantID        contract.TenantID     `json:"tenant_id"`
	Site            string                `json:"site"`
	SourceOperation contract.OperationID  `json:"source_operation_id"`
	ConfigRevision  uint64                `json:"config_revision,omitempty"`
	Sequence        uint16                `json:"sequence"`
	Doctype         string                `json:"doctype"`
	Event           Event                 `json:"event"`
	Record          Record                `json:"record"`
	Document        json.RawMessage       `json:"document"`
	OldDocument     json.RawMessage       `json:"old_document,omitempty"`
	Actor           contract.ActorContext `json:"actor"`
	Grants          []policy.Grant        `json:"grants,omitempty"`
}

AsyncHookInvocation freezes one document lifecycle script selected inside the source operation transaction. It is not a public wire contract.

type AsyncHookInvocationStore

type AsyncHookInvocationStore interface {
	AppendAsyncHookTx(context.Context, *sql.Tx, AsyncHookInvocation) error
	ClaimAsyncHooks(context.Context, contract.TenantID, string, uint16, time.Duration) ([]AsyncHookClaim, error)
	BeginAsyncHook(context.Context, AsyncHookClaim) (*sql.Tx, error)
	MarkAsyncHookExternalEffect(context.Context, AsyncHookClaim) error
	SucceedAsyncHookTx(context.Context, *sql.Tx, AsyncHookClaim) error
	FinishAsyncHook(context.Context, AsyncHookClaim, AsyncHookOutcome) error
}

AsyncHookInvocationStore defines the source-transaction append and recoverable worker boundary. A started external effect is durable before the provider sends the request; an expired such claim must become uncertain.

type AsyncHookOutcome

type AsyncHookOutcome struct {
	Success    bool
	Retry      bool
	Uncertain  bool
	Error      string
	RetryAfter time.Duration
}

type BudgetConfig

type BudgetConfig struct {
	PerTenant      int
	MaxWaiters     int
	MaxTenants     int
	Wait           time.Duration
	DefaultTimeout time.Duration
}

func DefaultBudgetConfig

func DefaultBudgetConfig() BudgetConfig

type BudgetSnapshot

type BudgetSnapshot struct {
	Active           int
	Waiters          int
	ActiveTenants    int
	MaxActiveTenants int
}

type BudgetedRunner

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

BudgetedRunner applies tenant-scoped execution admission before delegating to a process-wide runner. The active/waiting gate map retains entries only while executions reference them and is itself capped.

func NewBudgetedRunner

func NewBudgetedRunner(base Runner, cfg BudgetConfig) (*BudgetedRunner, error)

func (*BudgetedRunner) Close

func (r *BudgetedRunner) Close() error

func (*BudgetedRunner) Execute

func (r *BudgetedRunner) Execute(ctx context.Context, request ExecuteRequest) (*ExecuteResult, error)

func (*BudgetedRunner) Snapshot

func (r *BudgetedRunner) Snapshot() BudgetSnapshot

func (*BudgetedRunner) Validate

func (r *BudgetedRunner) Validate(source string) error

type DocProvider

type DocProvider interface {
	GetDoc(doctype, name string) (map[string]any, error)
	GetList(doctype string, filters map[string]any, orderBy string, limit, offset int) ([]map[string]any, error)
	SaveDoc(doctype string, doc map[string]any, modifiedBy string) error
	CreateDoc(doctype string, doc map[string]any, owner, modifiedBy string) (map[string]any, error)
	DeleteDoc(doctype, name string) error
}

DocProvider is the interface for document CRUD operations. Consumers that only need document access should accept this interface.

type EmbeddedConfig

type EmbeddedConfig struct {
	PoolSize int           // number of prewarmed runtimes (default: 15)
	MaxRAM   int64         // advisory target only; Goja has no enforced heap limit
	Timeout  time.Duration // default execution timeout
}

EmbeddedConfig configures the embedded runner.

func DefaultEmbeddedConfig

func DefaultEmbeddedConfig() EmbeddedConfig

DefaultEmbeddedConfig returns sensible defaults.

type EmbeddedRunner

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

EmbeddedRunner executes scripts in-process using goja. It maintains a pool of prewarmed runtimes for concurrent execution.

func NewEmbeddedRunner

func NewEmbeddedRunner(cfg EmbeddedConfig) *EmbeddedRunner

NewEmbeddedRunner creates a runner with a pool of prewarmed goja runtimes.

func (*EmbeddedRunner) Close

func (r *EmbeddedRunner) Close() error

Close shuts down all runtimes in the pool.

func (*EmbeddedRunner) Execute

Execute runs a script using a runtime from the pool.

func (*EmbeddedRunner) PoolSize

func (r *EmbeddedRunner) PoolSize() int

PoolSize returns the number of runtimes in the pool.

func (*EmbeddedRunner) Validate

func (r *EmbeddedRunner) Validate(script string) error

Validate checks that a script compiles without running it.

type Event

type Event string

Event is the lifecycle hook point.

const (
	EventBeforeInsert Event = "before_insert"
	EventAfterInsert  Event = "after_insert"
	EventBeforeSave   Event = "before_save"
	EventAfterSave    Event = "after_save"
	EventBeforeDelete Event = "before_delete"
	EventAfterDelete  Event = "after_delete"
	EventBeforeSubmit Event = "before_submit"
	EventAfterSubmit  Event = "after_submit"
	EventBeforeCancel Event = "before_cancel"
	EventAfterCancel  Event = "after_cancel"
	EventValidate     Event = "validate"
	EventComputed     Event = "computed"
	// EventPayment is used by named payment-provider scripts invoked before a
	// transaction is inserted.
	EventPayment Event = "payment"
)

type ExecuteRequest

type ExecuteRequest struct {
	Script        string         // JavaScript source
	ScriptType    Type           // doc_event, api_method, etc.
	ScriptName    string         // from _kora_script.name
	DocType       string         // doctype being operated on
	Event         Event          // lifecycle hook point
	Document      map[string]any // current document state
	OldDocument   map[string]any // previous document state (nil for inserts)
	User          string         // authenticated user email
	UserRoles     []string       // user's roles
	Site          string         // site hostname
	Timeout       time.Duration  // per-execution timeout
	Deterministic bool           // disables wall-clock and random JS sources

	// Provider bridges the JS runtime to the Kigae engine.
	// If nil, kora.getDoc/kora.saveDoc etc. return safe defaults.
	Provider KoraProvider
}

ExecuteRequest carries all context for a single script execution.

type ExecuteResult

type ExecuteResult struct {
	Document map[string]any `json:"document,omitempty"` // modified document (nil if unchanged)
	Modified bool           `json:"modified"`           // true if document was changed
	Result   any            `json:"result,omitempty"`   // return value (for api_method scripts)
	Logs     []LogEntry     `json:"logs,omitempty"`     // log messages from the script
	Duration time.Duration  `json:"duration_ms"`        // execution time
}

ExecuteResult is returned by a successful script execution.

type ExternalEffectJournal

type ExternalEffectJournal interface {
	BeforeExternalEffect(context.Context) error
}

ExternalEffectJournal must durably record the start of a non-transactional effect before the provider sends it. It is used by recoverable async hooks.

type ExternalEffectScopedProvider

type ExternalEffectScopedProvider interface {
	WithExternalEffectJournal(ExternalEffectJournal) KoraProvider
}

ExternalEffectScopedProvider attaches a per-invocation effect journal.

type HTTPProvider

type HTTPProvider interface {
	DoHTTP(req *HTTPRequest) (*HTTPResponse, error)
}

HTTPProvider is the interface for making external HTTP requests.

type HTTPRequest

type HTTPRequest struct {
	Method  string
	URL     string
	Headers map[string]string
	Body    string
}

HTTPRequest represents an outgoing HTTP request from a script.

type HTTPResponse

type HTTPResponse struct {
	Status     int
	StatusText string
	Headers    map[string]string
	Body       []byte
}

HTTPResponse represents an HTTP response returned to a script.

type KoraProvider

type KoraProvider interface {
	DocProvider
	SecretProvider
	HTTPProvider
}

KoraProvider is the composed interface for backward compatibility.

type LifecycleInventory

type LifecycleInventory struct {
	Complete                     bool             `json:"complete"`
	RowsInspected                int              `json:"rows_inspected"`
	DocumentEventScripts         int64            `json:"document_event_scripts"`
	ActiveDocumentEventScripts   int64            `json:"active_document_event_scripts"`
	InactiveDocumentEventScripts int64            `json:"inactive_document_event_scripts"`
	ActiveAfterEventScripts      int64            `json:"active_after_event_scripts"`
	ActiveAfterEventByEvent      map[string]int64 `json:"active_after_event_by_event,omitempty"`
	UnknownDocumentEventScripts  int64            `json:"unknown_document_event_scripts"`
	OtherScriptTypes             int64            `json:"other_script_types"`
}

LifecycleInventory contains aggregate counts only. It never returns script names, source, doctypes, or tenant-defined event values.

func InspectLifecycleInventory

func InspectLifecycleInventory(ctx context.Context, database *sql.DB, dialect db.Dialect, siteName string) (LifecycleInventory, error)

InspectLifecycleInventory performs a bounded, read-only scan of script metadata for one tenant. It deliberately does not select names or source.

type LifecycleInventoryError

type LifecycleInventoryError struct {
	Code  string
	Table string
	Cause error
}

LifecycleInventoryError exposes only a stable code and fixed table name. The underlying database error may contain deployment details and is never serialized by the inventory command.

func (*LifecycleInventoryError) Error

func (e *LifecycleInventoryError) Error() string

func (*LifecycleInventoryError) Unwrap

func (e *LifecycleInventoryError) Unwrap() error

type LifecycleScopedProvider

type LifecycleScopedProvider interface {
	WithLifecycleHook(doctype string, event Event, scriptName string) KoraProvider
}

LifecycleScopedProvider lets a provider carry the active lifecycle-script stack into nested operations. Implementations use it to prevent a script from recursively invoking itself while leaving other hooks enabled.

type LogEntry

type LogEntry struct {
	Level   string `json:"level"`   // debug, info, warn, error
	Message string `json:"message"` // log message
}

LogEntry is a single log message from a script execution.

type MutationExecutor

type MutationExecutor interface {
	Execute(context.Context, MutationRequest) (json.RawMessage, error)
}

MutationExecutor executes a nested script write in the current operation transaction. The returned bytes are the canonical command result JSON.

type MutationExecutorFunc

type MutationExecutorFunc func(context.Context, MutationRequest) (json.RawMessage, error)

MutationExecutorFunc adapts a function to MutationExecutor.

func (MutationExecutorFunc) Execute

type MutationRequest

type MutationRequest struct {
	Command         string          `json:"command"`
	Payload         json.RawMessage `json:"payload"`
	Site            string          `json:"site"`
	User            string          `json:"user"`
	Owner           string          `json:"owner,omitempty"`
	PrincipalID     string          `json:"principal_id"`
	PrincipalType   string          `json:"principal_type"`
	SubjectUserID   string          `json:"subject_user_id,omitempty"`
	UserRole        string          `json:"user_role,omitempty"`
	Roles           []string        `json:"roles,omitempty"`
	SkipHookScripts []string        `json:"skip_hook_scripts,omitempty"`
	AllowReadOnly   bool            `json:"allow_read_only,omitempty"`
}

MutationRequest is a script-originated record command. The executor is scoped to the current kernel transaction for lifecycle hooks, or absent after commit when the provider should start a normal operation.

type MutationScopedProvider

type MutationScopedProvider interface {
	WithMutationExecutor(MutationExecutor) KoraProvider
}

MutationScopedProvider lets ORM lifecycle hooks bind a provider to the active transaction without coupling the script package to the ORM.

type NoopProvider

type NoopProvider struct{}

NoopProvider is a safe default that returns errors for all operations. Used when the script runner runs without engine integration (tests, validation).

func (NoopProvider) CreateDoc

func (NoopProvider) CreateDoc(doctype string, doc map[string]any, owner, modifiedBy string) (map[string]any, error)

func (NoopProvider) DeleteDoc

func (NoopProvider) DeleteDoc(doctype, name string) error

func (NoopProvider) DoHTTP

func (NoopProvider) DoHTTP(req *HTTPRequest) (*HTTPResponse, error)

func (NoopProvider) GetDoc

func (NoopProvider) GetDoc(doctype, name string) (map[string]any, error)

func (NoopProvider) GetList

func (NoopProvider) GetList(doctype string, filters map[string]any, orderBy string, limit, offset int) ([]map[string]any, error)

func (NoopProvider) GetSecret

func (NoopProvider) GetSecret(key string) (string, error)

func (NoopProvider) SaveDoc

func (NoopProvider) SaveDoc(doctype string, doc map[string]any, modifiedBy string) error

type Record

type Record struct {
	Name         string     `json:"name"`
	Site         string     `json:"site"`
	ScriptType   Type       `json:"script_type"`
	DocType      string     `json:"doctype"`
	Event        Event      `json:"event"`
	MethodPath   string     `json:"method_path"`
	Schedule     string     `json:"schedule"`
	Priority     int        `json:"priority"`
	IsActive     bool       `json:"is_active"`
	RunAs        string     `json:"run_as"`
	TimeoutMs    int        `json:"timeout_ms"`
	Script       string     `json:"script"`
	CompiledAt   *time.Time `json:"compiled_at,omitempty"`
	CompileError string     `json:"compile_error,omitempty"`
	CreatedBy    string     `json:"created_by"`
	UpdatedBy    string     `json:"updated_by"`
	CreatedAt    time.Time  `json:"creation"`
	UpdatedAt    time.Time  `json:"modified"`
}

Record mirrors a _kora_script row.

type Runner

type Runner interface {
	// Execute runs a script and returns the result or an error.
	Execute(ctx context.Context, req ExecuteRequest) (*ExecuteResult, error)

	// Validate checks whether a script compiles without executing it.
	Validate(script string) error

	// Close releases resources held by the runner.
	Close() error
}

Runner executes JavaScript scripts with sandboxing.

type SecretProvider

type SecretProvider interface {
	GetSecret(key string) (string, error)
}

SecretProvider is the interface for retrieving secrets.

type Store

type Store struct {
	DB      *sql.DB
	Dialect db.Dialect
}

Store persists and retrieves script definitions using its site's database dialect.

func (*Store) AppendAsyncHookTx

func (s *Store) AppendAsyncHookTx(ctx context.Context, tx *sql.Tx, invocation AsyncHookInvocation) error

func (*Store) BeginAsyncHook

func (s *Store) BeginAsyncHook(ctx context.Context, claim AsyncHookClaim) (*sql.Tx, error)

func (*Store) ClaimAsyncHooks

func (s *Store) ClaimAsyncHooks(ctx context.Context, tenant contract.TenantID, owner string, limit uint16, lease time.Duration) ([]AsyncHookClaim, error)

func (*Store) Delete

func (s *Store) Delete(site, name string) error

Delete removes a script by site and name.

func (*Store) EnsureAsyncHookInvocationSchema

func (s *Store) EnsureAsyncHookInvocationSchema(ctx context.Context) error

func (*Store) FinishAsyncHook

func (s *Store) FinishAsyncHook(ctx context.Context, claim AsyncHookClaim, outcome AsyncHookOutcome) error

func (*Store) Insert

func (s *Store) Insert(r Record) error

Insert creates a new script record.

func (*Store) LoadActiveScripts

func (s *Store) LoadActiveScripts(site string, doctype string, event Event) ([]Record, error)

LoadActiveScripts returns all active scripts for a site, filtered by optional doctype+event.

func (*Store) LoadActiveScriptsTx

func (s *Store) LoadActiveScriptsTx(ctx context.Context, tx *sql.Tx, site string, doctype string, event Event) ([]Record, error)

LoadActiveScriptsTx selects lifecycle scripts through the caller's tenant transaction. Kernel operations use this so their selected script snapshot shares the same database view as the record mutation and any durable invocation rows written before commit.

func (*Store) LoadAllForSite

func (s *Store) LoadAllForSite(site string) ([]Record, error)

LoadAllForSite returns all scripts for a site.

func (*Store) LoadByName

func (s *Store) LoadByName(site, name string) (*Record, error)

LoadByName returns a single script by site and name.

func (*Store) LoadExecutions

func (s *Store) LoadExecutions(site, name string, limit int) ([]map[string]any, error)

LoadExecutions returns recent executions for a script.

func (*Store) LoadMethodScript

func (s *Store) LoadMethodScript(site string, methodPath string) (*Record, error)

LoadMethodScript returns the active api_method script for a given method path, or nil.

func (*Store) LogExecution

func (s *Store) LogExecution(site string, rec Record, docType, docName string, event Event, triggerUser string, durationMs int, status string, errMsg string) error

LogExecution records a script execution in _kora_script_execution.

func (*Store) MarkAsyncHookExternalEffect

func (s *Store) MarkAsyncHookExternalEffect(ctx context.Context, claim AsyncHookClaim) error

func (*Store) SucceedAsyncHookTx

func (s *Store) SucceedAsyncHookTx(ctx context.Context, tx *sql.Tx, claim AsyncHookClaim) error

func (*Store) Update

func (s *Store) Update(site, name string, req UpdateRequest, updatedBy string) error

Update modifies an existing script record. Only non-nil fields are applied.

type Type

type Type string

Type classifies the kind of script.

const (
	TypeDocEvent  Type = "doc_event"
	TypeAPIMethod Type = "api_method"
	TypeScheduled Type = "scheduled"
)

type UpdateRequest

type UpdateRequest struct {
	ScriptType *string `json:"script_type,omitempty"`
	DocType    *string `json:"doctype,omitempty"`
	Event      *string `json:"event,omitempty"`
	MethodPath *string `json:"method_path,omitempty"`
	Schedule   *string `json:"schedule,omitempty"`
	Priority   *int    `json:"priority,omitempty"`
	IsActive   *bool   `json:"is_active,omitempty"`
	RunAs      *string `json:"run_as,omitempty"`
	TimeoutMs  *int    `json:"timeout_ms,omitempty"`
	Script     *string `json:"script,omitempty"`
}

UpdateRequest carries the fields that can be updated on a script.

Jump to

Keyboard shortcuts

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