resourceauthoring

package
v0.35.2 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 21 Imported by: 1 module, 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 resourceauthoring is the host language service for resource predicates (profile omniview.resource-predicate.v1). It answers one question per request: which edits are valid at this cursor, given the admitted resource schema, the declared parameters and the draft text?

Ownership (P01 §4/§8.2, P07 §1): the host catalog (resourcecatalog) is the only schema authority, the CEL parser is the only syntax authority, and this package is the only authoring authority. Clients render its output and apply its edits; they never walk schemas, canonicalize paths or implement union narrowing. Nothing here evaluates a predicate or owns a second catalog.

Units. Every offset on the wire is a zero-based, half-open UTF-8 byte offset into the exact source of the request's document revision (unit "utf8-byte"). The CEL parser reports Unicode scalar offsets and browser editors count UTF-16 code units; units.go converts between all three against an exact source and rejects offsets that split a scalar or a surrogate pair.

Parser context. A tolerant lexer only delimits tokens and operand chains. The grammatical role of the cursor (member, index, value, operator or expression position) is derived from the token before it, every operand is parsed by the real CEL parser and resolved from that AST, and macro element variables are bound from the parsed receiver of the enclosing macro call. Suggestions are valid only where that role and the schema agree.

Index

Constants

View Source
const (
	// Version names the authoring DTO family (P01 §2/§4).
	Version = "omniview.authoring.v1"
	// PredicateProfile is the only language profile this service completes.
	PredicateProfile = "omniview.resource-predicate.v1"
	// UnitUTF8Byte is the only offset unit on the wire.
	UnitUTF8Byte = "utf8-byte"
	// ImplementationRevision is folded into the environment revision, so a
	// behavioural change of the completion engine invalidates cached answers.
	ImplementationRevision = "omniview.authoring-completion/1"
)

Wire constants of the completion contract.

View Source
const (
	ContextMember     = "member"     // after "." on an operand
	ContextIndex      = "index"      // inside "[ ]" on an operand
	ContextValue      = "value"      // right operand of a comparison, or an "in [...]" element
	ContextOperator   = "operator"   // after a complete operand
	ContextExpression = "expression" // start of an expression
	ContextNone       = "none"       // nothing can be suggested here
)

Context kinds: the grammatical role of the cursor.

View Source
const (
	DraftValid      = "valid"
	DraftIncomplete = "incomplete"
)

Draft states of the whole source, informational only.

View Source
const (
	RootResource  = "resource"
	RootParameter = "parameter"
	RootElement   = "element"  // a macro element variable bound to an array item
	RootImplicit  = "implicit" // a document path typed without its "resource." root
)

Operand roots.

View Source
const (
	KindField     = "field"
	KindRoot      = "root"
	KindParameter = "parameter"
	KindVariable  = "variable"
	KindOperator  = "operator"
	KindMethod    = "method"
	KindMacro     = "macro"
	KindFunction  = "function"
	KindEnumValue = "enumValue"
	KindLiteral   = "literal"
)

Item kinds.

View Source
const (
	ArityBinary = "binary" // "<operand> op <operand>"; the edit selects the operand placeholder
	ArityMethod = "method" // ".name(args)" on the operand
	ArityState  = "state"  // replaces the operand clause with a unary form
	ArityLogic  = "logic"  // joins two complete clauses
)

Operator arities.

View Source
const (
	CompletionComplete  = "complete"
	CompletionTruncated = "truncated"

	TruncatedItems     = "itemBudget"
	TruncatedBytes     = "byteBudget"
	TruncatedTraversal = "traversalBudget"
)

Completion states.

View Source
const ApplicabilityUnknown = "unknown"

ApplicabilityUnknown marks ancestor facts the catalog could not list.

View Source
const PolicyVersion = "omniview.authoring-policy.v1"

PolicyVersion identifies the authoring limits (P01 §9 "Authoring" row).

Variables

View Source
var (
	// ErrSuperseded is the cancellation cause of a request replaced by a newer
	// request for the same document.
	ErrSuperseded = errors.New("completion request superseded by a newer request")
	// ErrStaleRevision rejects a request whose document revision is older than
	// one the host already saw for that document.
	ErrStaleRevision = errors.New("completion request is for a stale document revision")
)

Functions

func AccessGeneration

func AccessGeneration(parts ...string) string

AccessGeneration identifies the host-admitted access under which a schema was resolved: the provider generation, the connection and its source epoch, and the invocation principal with its generation slot. It changes when the provider restarts, the connection's configuration or authority changes, or the principal's grant generation moves. No permission epoch exists on the host yet beyond the principal's generation slot; when one does, it belongs in parts.

func ApplyEdit

func ApplyEdit(source string, edit Edit) (string, error)

ApplyEdit returns source with the edit applied. The edit addresses UTF-8 bytes of source and must lie on scalar boundaries.

func ByteToScalar

func ByteToScalar(source string, offset int) (int, error)

ByteToScalar converts a UTF-8 byte offset to a Unicode scalar offset.

func ByteToUTF16

func ByteToUTF16(source string, offset int) (int, error)

ByteToUTF16 converts a UTF-8 byte offset to a UTF-16 code unit offset.

func EnvironmentRevision

func EnvironmentRevision(celEnvironmentRevision string, declarations map[string]query.BindingType) string

EnvironmentRevision is the authoring identity of the CEL environment a draft is checked in: the catalog-bound environment revision (snapshot, representation and schema revisions), the parameter declaration types, the language profile and this implementation. A changed declaration type invalidates answers even for unchanged source (P01 §4).

func ScalarToByte

func ScalarToByte(source string, scalar int) (int, error)

ScalarToByte converts a Unicode scalar offset, such as the CEL parser's, to a UTF-8 byte offset.

func ScopeKey

func ScopeKey(scope resourcev2.QueryScope) string

ScopeKey is the digest of a normalized query scope: constraints in dimension order, values sorted and de-duplicated, so equal scopes have equal keys.

func SpanToUTF16

func SpanToUTF16(source string, start, end int) (int, int, error)

SpanToUTF16 converts a byte span to UTF-16 code unit offsets of the same source.

func StaleMembers

func StaleMembers(request CompletionRequest, current Identity) []string

StaleMembers names the identity members the request expected and the host no longer has, in a fixed order. Empty expectations are not checked.

func Superseded

func Superseded(ctx context.Context) error

Superseded converts a cancelled request's error into one that names the cause, so callers and tests can tell supersession from a client cancel.

func SupersededError

func SupersededError(ctx context.Context, err error) error

SupersededError classifies the outcome of a request whose context was cancelled by supersession: whatever failure a cancelled step reported, the request ended because a newer one replaced it, so the error is a cancellation carrying ErrSuperseded. Any other error passes through unchanged.

func UTF16SpanToByte

func UTF16SpanToByte(source string, start, end int) (int, int, error)

UTF16SpanToByte is the inverse of SpanToUTF16.

func UTF16ToByte

func UTF16ToByte(source string, units int) (int, error)

UTF16ToByte converts a UTF-16 code unit offset to a UTF-8 byte offset. An offset between the two halves of a surrogate pair has no byte position.

func ValidateOffset

func ValidateOffset(source string, offset int) error

ValidateOffset reports whether offset is a scalar boundary of source.

func ValidateRequest

func ValidateRequest(r CompletionRequest, policy Policy) error

ValidateRequest admits the parts of a request that need no catalog: version, profile, identifiers, source bytes and Unicode, the cursor unit and position, declarations and the suggestion bound. The target is admitted against the catalog by the caller. Nothing is clamped silently: an offset outside the source or inside a scalar is rejected.

Types

type Ancestor

type Ancestor struct {
	Path          []PathSegment `json:"path"`
	Presence      string        `json:"presence"`
	Nullable      string        `json:"nullable"`
	Applicability string        `json:"applicability"`
	Conditions    []Condition   `json:"conditions,omitempty"`
}

Ancestor describes a path ancestor that is not guaranteed: optional, nullable or unknown, or reached only through a union branch. A value predicate below it needs a guard for each such ancestor.

type Completeness

type Completeness struct {
	Kind   string `json:"kind"`
	Reason string `json:"reason,omitempty"`
}

Completeness states whether Items is everything applicable. Truncated is not absence: more suggestions may exist, and the client must not narrow the list locally as if it were complete.

type CompletionRequest

type CompletionRequest struct {
	Version          string `json:"version"`
	RequestID        string `json:"requestId"`
	DocumentID       string `json:"documentId"`
	DocumentRevision uint64 `json:"documentRevision"`
	Source           string `json:"source"`
	Cursor           Cursor `json:"cursor"`
	Profile          string `json:"profile"`
	// Declarations are the typed parameters saved with the query. They are
	// types only: execution values are neither needed nor accepted.
	Declarations map[string]query.BindingType `json:"declarations,omitempty"`
	Target       Target                       `json:"target"`

	CatalogRevision        string `json:"catalogRevision,omitempty"`
	RepresentationRevision string `json:"representationRevision,omitempty"`
	SchemaRevision         string `json:"schemaRevision,omitempty"`
	EnvironmentRevision    string `json:"environmentRevision,omitempty"`
	AccessGeneration       string `json:"accessGeneration,omitempty"`

	// MaxSuggestions is positive; the host clamps it to its ceiling and
	// reports the effective value in the response.
	MaxSuggestions int `json:"maxSuggestions"`
}

CompletionRequest asks for edits at one cursor of one document revision.

The five optional identity members carry what the caller last observed in a response. A non-empty member that no longer matches the host's admitted state rejects the request with RESET_REQUIRED, so a caller can never apply suggestions computed under a different schema, environment or access than it believes. Omit them on the first request or to resynchronize.

func (*CompletionRequest) UnmarshalJSON

func (r *CompletionRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a request strictly: duplicate members, unknown members, invalid Unicode and trailing data are rejected before any field is trusted. Bounds that need a policy are checked by ValidateRequest.

type CompletionResponse

type CompletionResponse struct {
	Version          string        `json:"version"`
	RequestID        string        `json:"requestId"`
	DocumentID       string        `json:"documentId"`
	DocumentRevision uint64        `json:"documentRevision"`
	Cursor           Cursor        `json:"cursor"`
	Identity         Identity      `json:"identity"`
	Schema           SchemaSummary `json:"schema"`
	Context          Context       `json:"context"`
	Items            []Item        `json:"items"`
	Completion       Completeness  `json:"completion"`
	// MaxSuggestions is the effective ceiling applied to this request.
	MaxSuggestions int `json:"maxSuggestions"`
}

CompletionResponse answers one request and echoes its identities.

func Complete

func Complete(ctx context.Context, in Input) (CompletionResponse, error)

Complete returns the edits valid at the cursor. It is a pure function of its input and the context's cancellation: the same request against the same admitted schema gives the same answer.

type Condition

type Condition struct {
	Pointer string `json:"pointer"`
	Branch  int    `json:"branch"`
	// Combinator is "anyOf" or "oneOf".
	Combinator string `json:"combinator"`
}

Condition names the union branch that makes a field applicable. It is an applicability fact, never a claim that CEL narrows the type.

type Context

type Context struct {
	// Kind is member, index, value, operator, expression or none.
	Kind string `json:"kind"`
	// Draft is valid or incomplete for the whole source; completion never
	// requires a valid draft.
	Draft string `json:"draft"`
	// Prefix is the decoded text before the cursor inside the replaced token.
	Prefix string `json:"prefix"`
	// Replace is the token the default edit replaces, including text after
	// the cursor, so mid-token edits stay valid.
	Replace Range `json:"replace"`
	// Root is resource, parameter, element or implicit.
	Root string `json:"root,omitempty"`
	// Path is the schema path of the operand, empty for the document root.
	Path    []PathSegment `json:"path,omitempty"`
	Operand *Operand      `json:"operand,omitempty"`
	// Ancestors applies to every field suggestion of this response.
	Ancestors []Ancestor `json:"ancestors,omitempty"`
	// Keys is "dynamic" when the operand is a map whose keys the schema does
	// not name. Observed-key discovery (P17) fills such positions.
	Keys string `json:"keys,omitempty"`
}

Context is the parser context the suggestions were derived from.

type Cursor

type Cursor struct {
	Offset int    `json:"offset"`
	Unit   string `json:"unit"`
}

Cursor is a position in the request source.

type Edit

type Edit struct {
	Start     int    `json:"start"`
	End       int    `json:"end"`
	Unit      string `json:"unit"`
	Text      string `json:"text"`
	Selection *Range `json:"selection,omitempty"`
}

Edit replaces Start..End of the request source with Text. Selection, when present, addresses Text and marks where the user supplies the next operand; a zero-width selection is a caret.

type Identity

type Identity struct {
	// Plugin is the provider routing key; Provider is the catalog's canonical
	// provider id used in resource addresses.
	Plugin         string `json:"plugin"`
	Provider       string `json:"provider"`
	Connection     string `json:"connection"`
	Type           string `json:"type"`
	Representation string `json:"representation"`
	// ScopeKey is an opaque digest of the normalized query scope.
	ScopeKey               string `json:"scopeKey"`
	CatalogRevision        string `json:"catalogRevision"`
	RepresentationRevision string `json:"representationRevision"`
	SchemaRevision         string `json:"schemaRevision,omitempty"`
	// EnvironmentRevision covers the parameter declarations, the profile and
	// completion implementation, and the catalog-bound CEL environment.
	EnvironmentRevision string `json:"environmentRevision"`
	// AccessGeneration is an opaque equality token for the host-admitted
	// provider generation, connection epoch and invocation principal.
	AccessGeneration string `json:"accessGeneration"`
}

Identity names everything a completion depends on. A client may apply a response only while every member still matches its own state; a member that changed means the suggestions are stale.

type Input

type Input struct {
	Request CompletionRequest
	// Identity is the host-computed identity the response echoes.
	Identity Identity
	// Schema is the resolved representation schema; nil for an absent,
	// unsupported or unavailable binding, which completes dynamically.
	Schema *resourcecatalog.Schema
	// Summary reports how the schema participates.
	Summary SchemaSummary
	// Navigation bounds each catalog navigation (fields and visits).
	Navigation resourcecatalog.Policy
	Policy     Policy
}

Input is everything one completion needs. The caller (the resource controller) has already admitted the target and resolved the schema; this package fetches nothing and holds no state between requests.

type Item

type Item struct {
	Label         string      `json:"label"`
	Kind          string      `json:"kind"`
	Detail        string      `json:"detail,omitempty"`
	Documentation string      `json:"documentation,omitempty"`
	Type          *TypeInfo   `json:"type,omitempty"`
	Checking      string      `json:"checking,omitempty"`
	Presence      string      `json:"presence,omitempty"`
	Nullable      string      `json:"nullable,omitempty"`
	Applicability string      `json:"applicability,omitempty"`
	Conditions    []Condition `json:"conditions,omitempty"`
	HasChildren   bool        `json:"hasChildren,omitempty"`
	// Arity is set on operators, methods, macros and functions.
	Arity string `json:"arity,omitempty"`
	// Rootless marks a field typed without its "resource." root; its edit
	// supplies the root.
	Rootless bool `json:"rootless,omitempty"`
	Edit     Edit `json:"edit"`
}

Item is one suggestion.

type Operand

type Operand struct {
	Range         Range       `json:"range"`
	Type          *TypeInfo   `json:"type,omitempty"`
	Checking      string      `json:"checking,omitempty"`
	Presence      string      `json:"presence,omitempty"`
	Nullable      string      `json:"nullable,omitempty"`
	Applicability string      `json:"applicability,omitempty"`
	Conditions    []Condition `json:"conditions,omitempty"`
}

Operand is the schema-resolved expression the cursor operates on.

type PathSegment

type PathSegment struct {
	// Kind is "field", "mapValue" or "item".
	Kind string `json:"kind"`
	Name string `json:"name,omitempty"`
}

PathSegment is one schema navigation step from the document root.

type Policy

type Policy struct {
	// MaxSuggestions is the item ceiling of one response (P01: 128).
	MaxSuggestions int
	// MaxResponseBytes bounds the encoded response (P01: 65536).
	MaxResponseBytes int
	// MaxSourceBytes bounds the draft (P01 CEL source: 16384).
	MaxSourceBytes int
	// MaxDeclarations bounds the typed parameters (P01: 128).
	MaxDeclarations int
	// MaxPathDepth bounds the schema path of one operand, and with it the
	// number of catalog navigations a request performs.
	MaxPathDepth int
	// MaxDocumentationBytes bounds title and description text per item.
	MaxDocumentationBytes int
	// MaxIdentifierBytes bounds request, document and identity strings.
	MaxIdentifierBytes int
	// Deadline is the request deadline (P01: 250ms), covering catalog
	// admission, resolution and completion. Zero disables it.
	Deadline time.Duration
	// MaxDocuments bounds tracked documents; the least recently used are
	// evicted. DocumentIdleTTL expires idle entries.
	MaxDocuments    int
	DocumentIdleTTL time.Duration
}

Policy bounds one completion request and the document registry. Every limit is a finite safety ceiling; a request can lower MaxSuggestions but never raise any of them.

func DefaultPolicy

func DefaultPolicy() Policy

DefaultPolicy returns the reference ceilings of P01 §9.

func (Policy) Valid

func (p Policy) Valid() bool

Valid reports whether every ceiling is positive, except Deadline which may be zero in tests that supply their own context.

type Range

type Range struct {
	Start int    `json:"start"`
	End   int    `json:"end"`
	Unit  string `json:"unit"`
}

Range is a zero-based, half-open span. In an Edit it addresses the source of the request's document revision; in Edit.Selection it addresses Edit.Text.

type SchemaSummary

type SchemaSummary struct {
	// State is the provider binding state: absent, available or unavailable.
	State   string `json:"state"`
	Dialect string `json:"dialect,omitempty"`
	// Validation is full, reduced or none.
	Validation string `json:"validation"`
	// HostEvaluation is schemaChecked, dynamic, unavailable or unsupported.
	HostEvaluation     string `json:"hostEvaluation"`
	HostEvaluationCode string `json:"hostEvaluationCode,omitempty"`
}

SchemaSummary reports how the type's schema participates, with the same distinct states the catalog overlay keeps.

type Sessions

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

Sessions enforces "one active request per document and owner" with supersession, so a burst of keystrokes never queues work: each new request cancels the one in flight, and a request older than one already seen is refused. It keeps one small record per document, bounded by Policy.MaxDocuments and expired after Policy.DocumentIdleTTL, and no request payload.

Eviction only forgets a document's highest revision; a late response of an evicted document is still discarded by the client's own identity check.

func NewSessions

func NewSessions(policy Policy) *Sessions

NewSessions returns an empty registry.

func (*Sessions) Begin

func (s *Sessions) Begin(ctx context.Context, owner, document string, revision uint64) (context.Context, func(), error)

Begin registers a request for revision of document. It returns a context that is cancelled with ErrSuperseded when a newer request for the document begins, and a release function the caller must call exactly when the request ends.

A revision lower than the highest seen is refused. An equal revision (for example a moved cursor) is allowed: the newer arrival supersedes the older.

func (*Sessions) Len

func (s *Sessions) Len() int

Len reports the number of tracked documents.

type Target

type Target struct {
	Route resourcev2.AccessRoute `json:"route"`
	Type  string                 `json:"type"`
	// Representation is optional; empty selects the type's default.
	Representation string `json:"representation,omitempty"`
	// Scope is validated against the type's query dimensions. Omitted
	// dimensions mean "any" within the route, exactly as ResolveTarget.
	Scope resourcev2.QueryScope `json:"scope"`
}

Target names the resource type being queried. The host admits every field against its own catalog and connection state; none confers trust.

type TypeInfo

type TypeInfo struct {
	// Names are sorted JSON Schema type names; empty means any.
	Names  []string `json:"names"`
	Format string   `json:"format,omitempty"`
}

TypeInfo is the declared JSON type of a field.

Jump to

Keyboard shortcuts

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