operation

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const LiveValidationTimeout = 5 * time.Second
View Source
const MaxBatchDocuments = store.MaxListWindowDocuments
View Source
const (

	// MaxDocumentReferences bounds the relationship and upload work admitted by
	// one document mutation. The limit lives in the operation engine so local
	// calls, jobs, REST, GraphQL, and future transports cannot bypass it.
	MaxDocumentReferences = 512
)
View Source
const MaxLiveValidationEmbeddedScopes = 8
View Source
const MaxLiveValidationFields = 64
View Source
const MaxValidationIssues = 128

MaxValidationIssues bounds error-envelope construction for malformed nested documents. Validation stops once the cap is reached because the mutation is already inadmissible and collecting more paths only consumes resources.

Variables

This section is empty.

Functions

func ResolveIssueTarget added in v0.2.0

func ResolveIssueTarget(ctx Context, target operation.IssueTarget) (schema.Field, string, schema.LocaleCode, error)

ResolveIssueTarget resolves a field callback's relative selectors only within its own candidate value, from the field the callback is bound to. The caller's exact locale and embedded prefix stay bound. The resolved field is named by its placement.

func ResolveRootIssueTarget added in v0.5.0

func ResolveRootIssueTarget(fields []schema.Field, ctx Context, values store.Values, target operation.IssueTarget) (schema.Field, string, schema.LocaleCode, error)

ResolveRootIssueTarget resolves a resource hook's selectors from the document root. A zero target addresses the document itself.

Types

type Access

type Access func(Context) (Decision, error)

type AccessCapabilities

type AccessCapabilities struct {
	Operations OperationCapabilities
	// Fields holds field capabilities by runtime path for each located value,
	// and by canonical path for each resource field and each block placement
	// with located values.
	Fields map[string]FieldCapabilities
	// BlockFields holds, by block slug and definition-relative path, the
	// capabilities of a block definition's field at a placement without
	// located values, such as a row the client has yet to add. It is
	// evaluated once per definition field rather than once per placement.
	BlockFields map[string]map[string]FieldCapabilities
}

AccessCapabilities is the evaluated access of an actor and optional document or input snapshot.

type CapabilitiesRequest

type CapabilitiesRequest struct {
	Collection      string
	ID              string
	Data            store.Values
	Actor           *store.Document
	ActorCollection schema.CollectionSlug
	TrashOnly       bool
	Locale          string
	FallbackLocales []schema.LocaleCode
	DisableFallback bool
	AllLocales      bool
}

CapabilitiesRequest evaluates non-secret operation and field access for an actor. Data is a prospective create/update snapshot. TrashOnly evaluates a deleted document for restore and permanent-delete actions.

type Collection

type Collection struct {
	Key      string
	Schema   schema.Collection
	Access   map[operation.Kind]Access
	Hooks    Hooks
	Bindings []FieldBinding
	// contains filtered or unexported fields
}

type CollectionPageAccess added in v0.3.0

type CollectionPageAccess struct {
	Collection AccessCapabilities
	Documents  map[string]AccessCapabilities
}

type Computed

type Computed func(Context, store.Document) (store.Value, error)

type Config

type Config struct {
	Collections               []Collection
	Store                     store.Store
	AllowIDOnCreate           bool
	MaxDepth                  int
	PluginValidators          map[string]PluginValidator
	DispatchAfterCommit       func(Context, Hook) error
	BeginPermanentDeleteFence func(context.Context, []PermanentDelete) func(bool)
	CleanupPermanentDeletes   func(context.Context, []PermanentDelete) error
	ValidateUploadImport      func(context.Context, schema.Collection, store.Values) error
	RootAfterError            []Hook
	Localization              *schema.LocalizationSettings
	// EditorCollection is the auth collection whose members see drafts by
	// default: the admin's user collection. Empty means no actor does.
	EditorCollection schema.StableID
}

type Context

type Context struct {
	Context         context.Context
	Operation       operation.Kind
	WritePhase      operation.WritePhase
	Collection      schema.Collection
	ID              string
	Actor           *store.Document
	ActorCollection schema.CollectionSlug

	// System marks trusted server code that skips collection and field access
	// rules. Only the Local API sets it; transports never do.
	System bool
	Data   store.Values
	Value  store.Value
	// Root, Siblings and Prior are a field callback's immutable object views of
	// the document, the enclosing object or row, and that object's previous
	// persisted state. Root is zero outside field callbacks; Prior is zero when
	// no previous object exists. Input is a live validator's submitted object.
	Root     store.Value
	Siblings store.Value
	Prior    store.Value
	Input    store.Value

	// Replacement receives a field hook's new value for its own field. The
	// engine sets it for each field hook; other contexts leave it nil.
	Replacement    *FieldReplacement
	LiveValidation bool

	Document *store.Document
	Original *store.Document

	// OccurrenceID correlates a field callback's value; SchemaOccurrenceID
	// names the configured field at the value's placement.
	OccurrenceID       string
	SchemaOccurrenceID string
	ValuePresent       bool

	RuntimePath string
	Error       error
	Locale      schema.LocaleCode
	AllLocales  bool
	Locales     []schema.LocaleCode
	// contains filtered or unexported fields
}

func (Context) ActorValues added in v0.15.0

func (ctx Context) ActorValues() store.Value

ActorValues returns an immutable view of the actor document's values, or the zero Value without an actor.

func (Context) BoundField added in v0.15.0

func (ctx Context) BoundField() schema.Field

BoundField returns the field a field callback is bound to, named by its placement: a block definition's field takes the placement's canonical path and stable ID. It is the zero Field outside field callbacks.

func (Context) ReplaceValue added in v0.15.0

func (ctx Context) ReplaceValue(value store.Value) error

ReplaceValue sets a field hook's own value. Only field hooks the engine dispatches receive a replacement slot. Elsewhere, such as in a validator, access rule, default or deferred hook, the value could not be applied, so asking to replace it is an error rather than a silently lost change.

type Decision

type Decision struct {
	Kind   DecisionKind
	Access *query.Node
}

type DecisionKind

type DecisionKind string
const (
	Allow DecisionKind = "allow"
	Deny  DecisionKind = "deny"
	Where DecisionKind = "where"
)

type DistinctRequest

type DistinctRequest struct {
	Collection      string
	Field           query.Path
	Filter          query.Expression
	Page            int
	Limit           int
	Actor           *store.Document
	ActorCollection schema.CollectionSlug
	// System skips access rules for trusted server code; see Request.System.
	System          bool
	Draft           *bool
	TrashOnly       bool
	Locale          string
	FallbackLocales []schema.LocaleCode
	DisableFallback bool
}

DistinctRequest describes one access-checked local distinct read. The field itself remains deliberately limited by store.ValidateDistinctRequest.

type Engine

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

func New

func New(config Config) (*Engine, error)

func (*Engine) Capabilities

func (engine *Engine) Capabilities(ctx context.Context, request CapabilitiesRequest) (result AccessCapabilities, err error)

Capabilities evaluates access without running validation, hooks, mutations, or commits. Filtered decisions remain predicates on store reads so a document-specific true result has the same authorization semantics as the corresponding operation.

func (*Engine) CopyLocale

func (engine *Engine) CopyLocale(ctx context.Context, collectionName, documentID string, source, target schema.LocaleCode, expectedRevision int, actor *store.Document, authorizationOptions ...LocalizationOptions) (document store.Document, err error)

CopyLocale copies readable localized values from one exact locale into a different locale through the lifecycle appropriate to the current status. Copying into a published document is itself a live edit, so it requires both update and publish access and runs publish hooks atomically.

func (*Engine) CountVersions added in v0.13.0

func (engine *Engine) CountVersions(ctx context.Context, collectionName, documentID string, actor *store.Document, localeOptions ...LocalizationOptions) (int, error)

CountVersions counts retained, authorized snapshots without resolving their output fields.

func (*Engine) Distinct

func (engine *Engine) Distinct(ctx context.Context, request DistinctRequest) (result store.DistinctPage, err error)

Distinct reads unique scalar values through the collection read rule and a single atomic adapter query. It is intentionally separate from Execute: the initial contract is a Local API query, not a new document lifecycle or general aggregation operation.

func (*Engine) Execute

func (engine *Engine) Execute(ctx context.Context, request Request) (result Result, err error)

func (*Engine) ExecuteBatch

func (engine *Engine) ExecuteBatch(ctx context.Context, requests []Request) (results []Result, err error)

ExecuteBatch runs ordinary operations in one transaction. Every item uses the same access, validation, hook, version, and redaction pipeline as Execute.

func (*Engine) ForceUnlockAuth

func (engine *Engine) ForceUnlockAuth(ctx context.Context, collectionName, documentID string, actor *store.Document, actorCollection schema.CollectionSlug) (err error)

ForceUnlockAuth clears an auth document's private login lockout state in the same transaction that evaluates and applies its update access predicate. Unlike ordinary CRUD, an omitted update rule fails closed for this privileged account-management action.

func (*Engine) ListJoin added in v0.2.0

func (engine *Engine) ListJoin(ctx context.Context, collection, id, field string, request Request) (result Result, err error)

ListJoin keeps configured inverse-relation membership out of caller query admission. The source document and join field must be readable, and the target still runs through Execute with its own collection and field access rules.

func (*Engine) LiveRead added in v0.2.0

func (engine *Engine) LiveRead(ctx context.Context, request CapabilitiesRequest) (store.Document, error)

LiveRead is the advisory callback reader. It shares the original snapshot and actor but does not run lifecycle hooks, output resolvers, or fallback reads.

func (*Engine) LiveValidate added in v0.2.0

func (engine *Engine) LiveValidate(ctx context.Context, request LiveValidationRequest) (result LiveValidationResult, err error)

LiveValidate evaluates explicitly attached read-only checks. It deliberately does not enter Execute: a browser snapshot is not a prepared write candidate.

func (*Engine) MutateJoin

func (engine *Engine) MutateJoin(ctx context.Context, request JoinMutationRequest) (result JoinMutationResult, err error)

MutateJoin applies inverse relation deltas through ordinary target updates in one transaction. Target access, field access, validation, hooks, versions, and after-commit dispatch remain owned by Execute.

func (*Engine) MutatePublicationTarget added in v0.3.0

func (engine *Engine) MutatePublicationTarget(ctx context.Context, request CapabilitiesRequest, kind operation.Kind, mutation TransactionMutation) (err error)

MutatePublicationTarget runs one framework-owned callback after the selected lifecycle access predicate has matched a mutation-locked document and before that write transaction commits.

func (*Engine) PublicationTarget added in v0.3.0

func (engine *Engine) PublicationTarget(ctx context.Context, request CapabilitiesRequest, kind operation.Kind) (document store.Document, err error)

PublicationTarget loads only the metadata needed to schedule a publish or unpublish. The selected lifecycle access predicate remains attached to the same atomic store read, so scheduling does not accidentally require Read.

func (*Engine) ReadUploadMetadata added in v0.3.0

func (engine *Engine) ReadUploadMetadata(ctx context.Context, request Request) (document store.Document, err error)

ReadUploadMetadata returns canonical storage metadata only to the upload coordinator. Update combines read and update predicates; duplicate uses the same source-head and retained-locale read decisions as Execute. Response field redaction must never substitute a rendition for the private source.

func (*Engine) ReadUploadOwner added in v0.2.0

func (engine *Engine) ReadUploadOwner(ctx context.Context, key string, request Request) (Result, error)

ReadUploadOwner proves object membership through ordinary collection read access. Object keys and configured size keys are framework-owned lookup constraints, even when their metadata fields are hidden from document reads.

func (*Engine) ResolveFilteredSelection

func (engine *Engine) ResolveFilteredSelection(ctx context.Context, request FilteredSelectionRequest) (result FilteredSelectionResult, err error)

ResolveFilteredSelection freezes one bounded, read-visible ID set and its exact per-document capabilities without running hooks or mutations.

func (*Engine) Restore

func (engine *Engine) Restore(ctx context.Context, collectionName, documentID string, revision, expectedRevision int, draft bool, actor *store.Document, localeOptions ...LocalizationOptions) (Result, error)

func (*Engine) RestorePopulated

func (engine *Engine) RestorePopulated(ctx context.Context, collectionName, documentID string, revision, expectedRevision int, draft bool, actor *store.Document, populations []query.Population, outputFields []query.Path, localeOptions ...LocalizationOptions) (result Result, err error)

RestorePopulated restores a revision and applies a bounded relationship population plan to the returned document in the update transaction.

func (*Engine) Version

func (engine *Engine) Version(ctx context.Context, collectionName, documentID string, revision int, actor *store.Document, localeOptions ...LocalizationOptions) (store.Version, error)

Version returns one authorized snapshot revision.

func (*Engine) Versions

func (engine *Engine) Versions(ctx context.Context, collectionName, documentID string, actor *store.Document, localeOptions ...LocalizationOptions) (versions []store.Version, err error)

type Error

type Error struct {
	Code    string
	Status  int
	Message string
	Issues  []schema.Issue
	Cause   error
	// Committed reports that the durable transaction succeeded before a later
	// after-commit effect failed. Callers that stage external resources must not
	// roll those resources back when this is true.
	Committed bool
	// CommitAttempted reports that Commit was sent but its durable outcome could
	// not be proven. External resources must be retained and reconciled instead
	// of rolled back when this is true.
	CommitAttempted bool
	// contains filtered or unexported fields
}

func (*Error) Error

func (operationError *Error) Error() string

func (*Error) Unwrap

func (operationError *Error) Unwrap() error

type FieldAccess

type FieldAccess func(Context) (bool, error)

type FieldBinding added in v0.2.0

type FieldBinding struct {
	ID string
	// Block names the block definition that declares Field, whose path and ID
	// are then definition-relative. It is empty for a resource's own field.
	Block          string
	Field          schema.Field
	Hooks          Hooks
	Access         FieldRules
	Validators     []FieldValidator
	LiveValidators []FieldLiveValidator
	Computed       Computed
	Default        FieldDefault
}

FieldBinding is private runtime configuration, lowered once from one field of a resource or of a block definition. A definition's binding applies at every placement of the definition: a document walk supplies each location's placement, so bindings follow definitions, not placements. No request contains an authoring node or resolves a callback from a document path. Field paths are only schema navigation and diagnostics.

type FieldCapabilities

type FieldCapabilities struct {
	Read   bool
	Create bool
	Update bool
}

type FieldDefault added in v0.2.0

type FieldDefault func(Context) (store.Value, bool, error)

FieldDefault supplies one absent value during eligible initialization.

type FieldLiveValidator added in v0.2.0

type FieldLiveValidator func(Context) ([]schema.Issue, bool, error)

FieldLiveValidator reports whether its typed input was available separately from an empty, successful set of advisory issues.

type FieldReplacement added in v0.15.0

type FieldReplacement struct {
	Value store.Value
	Set   bool
}

FieldReplacement records a field hook's new value for its own field.

type FieldRules

type FieldRules struct {
	Create FieldAccess
	Read   FieldAccess
	Update FieldAccess
}

type FieldValidator added in v0.2.0

type FieldValidator func(Context) ([]schema.Issue, error)

type FilteredSelectionItem

type FilteredSelectionItem struct {
	ID           string
	Capabilities AccessCapabilities
}

type FilteredSelectionRequest

type FilteredSelectionRequest struct {
	Collection      string
	Filter          query.Expression
	Actor           *store.Document
	ActorCollection schema.CollectionSlug
	TrashOnly       bool
	Locale          string
	FallbackLocales []schema.LocaleCode
	DisableFallback bool
	AllLocales      bool
}

type FilteredSelectionResult

type FilteredSelectionResult struct {
	Items []FilteredSelectionItem
}

type Hook

type Hook func(Context) error

type Hooks

type Hooks struct {
	BeforeDuplicate []Hook
	BeforeValidate  []Hook
	BeforeChange    []Hook
	BeforeOperation []Hook
	BeforeRead      []Hook
	BeforeDelete    []Hook
	AfterChange     []Hook
	AfterRead       []Hook
	AfterDelete     []Hook
	AfterOperation  []Hook
	AfterError      []Hook
	AfterCommit     []Hook
}

type JoinMutationRequest

type JoinMutationRequest struct {
	Collection      string
	ID              string
	Field           string
	Additions       []string
	Removals        []string
	Actor           *store.Document
	ActorCollection schema.CollectionSlug
	// System skips access rules for trusted server code; see Request.System.
	System          bool
	Locale          string
	FallbackLocales []schema.LocaleCode
	DisableFallback bool
	AllLocales      bool
}

JoinMutationRequest describes explicit inverse-relation changes. Additions and removals are deltas because a rendered join can be a limited subset of all matching target documents.

type JoinMutationResult

type JoinMutationResult struct {
	Document store.Document
	Added    int
	Removed  int
}

JoinMutationResult reports the refreshed source document and applied deltas.

type LiveValidationEmbeddedScope added in v0.2.0

type LiveValidationEmbeddedScope struct {
	Field       string
	TreeKey     string
	CaseTag     string
	VariantSlug string
	Identity    string
	Data        store.Values
}

type LiveValidationEvaluation added in v0.2.0

type LiveValidationEvaluation struct {
	Path   string
	Target string
	Status string
	Issues []schema.Issue
}

type LiveValidationRequest added in v0.2.0

type LiveValidationRequest struct {
	Collection      string
	ID              string
	Draft           *bool
	Data            store.Values
	Fields          []string
	Embedded        []LiveValidationEmbeddedScope
	Actor           *store.Document
	ActorCollection schema.CollectionSlug
	Locale          string
}

type LiveValidationResult added in v0.2.0

type LiveValidationResult struct{ Evaluations []LiveValidationEvaluation }

type LocalizationOptions

type LocalizationOptions struct {
	Locale          string
	FallbackLocales []schema.LocaleCode
	DisableFallback bool
	AllLocales      bool
	// ActorCollection identifies the exact auth collection that owns Actor on
	// specialized version and locale operations.
	ActorCollection schema.CollectionSlug
	// System skips access rules for trusted server code; see Request.System.
	System bool
}

LocalizationOptions selects the locale projection for version reads.

type OperationCapabilities

type OperationCapabilities struct {
	Admin           bool
	Create          bool
	Read            bool
	ReadVersions    bool
	Update          bool
	Delete          bool
	Duplicate       bool
	Publish         bool
	Unpublish       bool
	RestoreDeleted  bool
	DeletePermanent bool
	SelectAll       bool
	Unlock          bool
}

type PermanentDelete

type PermanentDelete struct {
	Collection schema.Collection
	DocumentID string
	Original   store.Document
}

PermanentDelete identifies one document whose durable deletion must be fenced with lifecycle-sensitive in-process state such as preview grants.

type PluginValidator

type PluginValidator func(schema.Field, store.Value, string) []schema.Issue

type Rejection added in v0.5.0

type Rejection struct {
	Message string
	Issues  []schema.Issue
}

Rejection is a hook's deliberate refusal of an operation. Unlike an ordinary hook error, its message and issues are meant for the caller: the engine returns them as a rejected operation instead of an internal failure.

func (*Rejection) Error added in v0.5.0

func (rejection *Rejection) Error() string

type Request

type Request struct {
	Operation  operation.Kind
	Collection string
	ID         string
	Data       store.Values
	Filter     query.Expression

	Actor           *store.Document
	ActorCollection schema.CollectionSlug
	// System runs the request as trusted server code: collection, field, draft
	// and reference access rules are skipped, while validation, hooks, versions
	// and reference integrity still apply. Only the Local API sets it.
	System bool
	Page   int
	Limit  int
	// SkipTotal reads a collection list page without counting every match:
	// the page has no Total and an exact HasNextPage. Index windows never count.
	SkipTotal   bool
	IndexWindow *store.IndexWindow
	Sort        []query.Sort
	Select      []query.Path
	Populate    []query.Population
	// IncludeAccess enriches an ordinary collection list with collection and
	// per-document capabilities evaluated in the list's read transaction.
	IncludeAccess bool
	// OutputFields limits computed and inverse-join resolution. Nil preserves
	// the local API's historical behavior of resolving every output field; a
	// non-nil empty slice resolves none. This is deliberately separate from
	// Select because computed resolvers may depend on unprojected stored data.
	OutputFields []query.Path
	// Draft overrides versioned read visibility or selects the status written
	// by create/update. Nil preserves the caller's existing behavior.
	Draft *bool
	// ExpectedRevision, when nonzero, must equal the revision of the document
	// as the operation locks it, before any hook runs; otherwise the operation
	// fails with a conflict. Writes the operation's own hooks make in its
	// transaction do not conflict with it.
	ExpectedRevision int
	Status           *store.Status
	ImportID         string
	ImportCreatedAt  time.Time
	ImportUpdatedAt  time.Time
	TrashOnly        bool
	StoragePrepared  bool
	// ValidateUploadObjects re-adopts existing upload keys. The engine locks and
	// verifies every final key inside the write transaction before committing
	// metadata that can make those objects live again.
	ValidateUploadObjects bool
	LocalizationPrepared  bool

	// SkipFieldAccess is reserved for framework-owned initialization that must
	// author the first administrator before an actor exists. Collection access,
	// validation, hooks, and the transaction remain active.
	SkipFieldAccess     bool
	TransactionMutation TransactionMutation
	// TransactionResource binds one framework-owned external resource to the
	// true outer transaction. Commit retains it, a definite rollback cleans it
	// up, and an unknown commit outcome retains it for reconciliation rather
	// than risking a dangling durable row.
	TransactionResource *TransactionResource
	Locale              string
	FallbackLocales     []schema.LocaleCode
	DisableFallback     bool
	AllLocales          bool
	// contains filtered or unexported fields
}

type Result

type Result struct {
	Document   *store.Document
	Page       *store.Page
	PageAccess *CollectionPageAccess
}

type TransactionResource

type TransactionResource struct {
	Commit   func()
	Rollback func(context.Context) error
	Unknown  func()
	// contains filtered or unexported fields
}

TransactionResource coordinates an external resource whose durable system cannot participate in the document-store transaction.

func (*TransactionResource) Claimed

func (resource *TransactionResource) Claimed() bool

Claimed reports whether the operation engine attached the resource to a document transaction. Once claimed, only the true outer transaction may finalize it; callers must not perform eager fallback cleanup.

Jump to

Keyboard shortcuts

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