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
- Variables
- func AsyncHookInvocationSchemaStatements(dialect db.Dialect) ([]string, error)
- func IsAfterEvent(e Event) bool
- func IsBeforeEvent(e Event) bool
- type AsyncHookClaim
- type AsyncHookInvocation
- type AsyncHookInvocationStore
- type AsyncHookOutcome
- type BudgetConfig
- type BudgetSnapshot
- type BudgetedRunner
- type DocProvider
- type EmbeddedConfig
- type EmbeddedRunner
- type Event
- type ExecuteRequest
- type ExecuteResult
- type ExternalEffectJournal
- type ExternalEffectScopedProvider
- type HTTPProvider
- type HTTPRequest
- type HTTPResponse
- type KoraProvider
- type LifecycleInventory
- type LifecycleInventoryError
- type LifecycleScopedProvider
- type LogEntry
- type MutationExecutor
- type MutationExecutorFunc
- type MutationRequest
- type MutationScopedProvider
- type NoopProvider
- func (NoopProvider) CreateDoc(doctype string, doc map[string]any, owner, modifiedBy string) (map[string]any, error)
- func (NoopProvider) DeleteDoc(doctype, name string) error
- func (NoopProvider) DoHTTP(req *HTTPRequest) (*HTTPResponse, error)
- func (NoopProvider) GetDoc(doctype, name string) (map[string]any, error)
- func (NoopProvider) GetList(doctype string, filters map[string]any, orderBy string, limit, offset int) ([]map[string]any, error)
- func (NoopProvider) GetSecret(key string) (string, error)
- func (NoopProvider) SaveDoc(doctype string, doc map[string]any, modifiedBy string) error
- type Record
- type Runner
- type SecretProvider
- type Store
- func (s *Store) AppendAsyncHookTx(ctx context.Context, tx *sql.Tx, invocation AsyncHookInvocation) error
- func (s *Store) BeginAsyncHook(ctx context.Context, claim AsyncHookClaim) (*sql.Tx, error)
- func (s *Store) ClaimAsyncHooks(ctx context.Context, tenant contract.TenantID, owner string, limit uint16, ...) ([]AsyncHookClaim, error)
- func (s *Store) Delete(site, name string) error
- func (s *Store) EnsureAsyncHookInvocationSchema(ctx context.Context) error
- func (s *Store) FinishAsyncHook(ctx context.Context, claim AsyncHookClaim, outcome AsyncHookOutcome) error
- func (s *Store) Insert(r Record) error
- func (s *Store) LoadActiveScripts(site string, doctype string, event Event) ([]Record, error)
- func (s *Store) LoadActiveScriptsTx(ctx context.Context, tx *sql.Tx, site string, doctype string, event Event) ([]Record, error)
- func (s *Store) LoadAllForSite(site string) ([]Record, error)
- func (s *Store) LoadByName(site, name string) (*Record, error)
- func (s *Store) LoadExecutions(site, name string, limit int) ([]map[string]any, error)
- func (s *Store) LoadMethodScript(site string, methodPath string) (*Record, error)
- func (s *Store) LogExecution(site string, rec Record, docType, docName string, event Event, ...) error
- func (s *Store) MarkAsyncHookExternalEffect(ctx context.Context, claim AsyncHookClaim) error
- func (s *Store) SucceedAsyncHookTx(ctx context.Context, tx *sql.Tx, claim AsyncHookClaim) error
- func (s *Store) Update(site, name string, req UpdateRequest, updatedBy string) error
- type Type
- type UpdateRequest
Constants ¶
const ( MaxAsyncHookAttempts uint8 = 5 MaxAsyncHookBatch = 32 MaxAsyncHookPayloadBytes = 1 << 20 MaxAsyncHookTimeout = 4 * time.Minute )
Variables ¶
var ErrTenantCapacity = errors.New("script tenant concurrency capacity exhausted")
Functions ¶
func IsAfterEvent ¶
IsAfterEvent returns true if the event is an after_* (best-effort) hook.
func IsBeforeEvent ¶
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 BudgetConfig ¶
type BudgetConfig struct {
PerTenant int
MaxWaiters int
MaxTenants int
Wait time.Duration
DefaultTimeout time.Duration
}
func DefaultBudgetConfig ¶
func DefaultBudgetConfig() BudgetConfig
type BudgetSnapshot ¶
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 ¶
func (r *EmbeddedRunner) Execute(ctx context.Context, req ExecuteRequest) (*ExecuteResult, error)
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 ¶
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 ¶
HTTPRequest represents an outgoing HTTP request from a script.
type HTTPResponse ¶
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 ¶
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 ¶
func (f MutationExecutorFunc) Execute(ctx context.Context, req MutationRequest) (json.RawMessage, error)
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) 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)
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 ¶
SecretProvider is the interface for retrieving secrets.
type Store ¶
Store persists and retrieves script definitions using its site's database dialect.
func (*Store) AppendAsyncHookTx ¶
func (*Store) BeginAsyncHook ¶
func (*Store) ClaimAsyncHooks ¶
func (*Store) EnsureAsyncHookInvocationSchema ¶
func (*Store) FinishAsyncHook ¶
func (s *Store) FinishAsyncHook(ctx context.Context, claim AsyncHookClaim, outcome AsyncHookOutcome) error
func (*Store) LoadActiveScripts ¶
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 ¶
LoadAllForSite returns all scripts for a site.
func (*Store) LoadByName ¶
LoadByName returns a single script by site and name.
func (*Store) LoadExecutions ¶
LoadExecutions returns recent executions for a script.
func (*Store) LoadMethodScript ¶
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 ¶
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.