schema

package
v1.0.0-alpha.14 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package schema is the kernel's single source of truth for OPM schema-side knowledge: CUE paths, metadata decoders, the transformer-context builder, and the OCI-backed schema loader.

Schema is unversioned at the package level. The library consumes exactly one OPM CUE schema package — opmodel.dev/core@v2, resolved through CUE's module system against CUE_REGISTRY. There is no in-tree schema mirror.

Path inventory

CUE paths are exported as package-level cue.Path variables (Metadata, Components, Config, Module, ModuleMetadata, Registry, …). Callers use schema.X verbatim — there is no Paths() accessor, no struct, no lookup.

Metadata decoders

DecodeModuleMetadata, DecodeInstanceMetadata, DecodeProviderMetadata, and DecodePlatformMetadata accept a raw artifact-root cue.Value and return the canonical decoded struct. Missing metadata is fatal for module / instance / platform; provider metadata falls back to a caller-supplied name.

Transformer context

BuildTransformerContext constructs the #TransformerContext value for a single (instance, component, transformer) tuple. The caller is responsible for filling the returned value at schema.Context on the unified transformer.

Schema loader and cache

Loader is the strategy interface for resolving the schema; OCILoader is the sole public implementation, fetching opmodel.dev/core@v2 through CUE's module system. Cache memoizes a single Loader.Load per instance (sync.Once-guarded) and exposes ResolvedVersion for diagnostics.

Long-running consumers attach the Cache to a Kernel (via kernel.WithSchemaLoader) and reuse the kernel-owned cache via kernel.SchemaCache(). The library auto-applies no CUE_REGISTRY default; callers opt in by setting CUE_REGISTRY to schema.PublicRegistry (or to a private mirror) before the first Cache.Get.

Index

Constants

View Source
const AnnotationDefaultNamespace = "module.opmodel.dev/default-namespace"

AnnotationDefaultNamespace is the annotation key carrying a module's suggested default namespace. The annotation is advisory: tooling and operators MAY consult it to seed metadata.namespace on a #ModuleInstance, but the instance remains the authoritative owner of the actual deployed namespace. See adr/001-module-default-namespace-as-annotation.md.

View Source
const DefaultSchemaModule = "opmodel.dev/core@v2"

DefaultSchemaModule is the module identifier used by OCILoader.Load when OCILoader.Module is empty. The default tracks the v2 major; the bare major is expanded through the loader's ".latest" mechanism, resolving the highest published version within v2 at first-load time (SemVer prerelease ordering applies, so a v2.0.0-0.dev.* snapshot never outranks a v2.0.0-alpha.N tag).

View Source
const PublicRegistry = "opmodel.dev=ghcr.io/open-platform-model,registry.cue.works"

PublicRegistry is the documented CUE_REGISTRY mapping for resolving the OPM core schema from its canonical GHCR location with a fallback to registry.cue.works. The library does NOT auto-apply this value as a default; callers opt in by setting CUE_REGISTRY=schema.PublicRegistry (or by passing it via OCILoader.Registry).

Operators in restricted environments may set CUE_REGISTRY to a mirror or to an inline configuration without touching this constant.

Variables

View Source
var (
	// Artifact root.
	Metadata = cue.ParsePath("metadata")

	// Module instance.
	Components         = cue.ParsePath("components")
	Values             = cue.ParsePath("values")
	Config             = cue.MakePath(cue.Def("config"))
	Module             = cue.MakePath(cue.Def("module"))         // instance's reference to its source #Module
	ModuleMetadataPath = cue.MakePath(cue.Def("moduleMetadata")) // instance-side projection of #module.metadata. Suffixed -Path to avoid collision with the ModuleMetadata struct type.

	// Module-internal field. DebugValues is a Module field — NOT a separate
	// kernel artifact. Frontends that want a debug overlay read it from
	// Module.Package and decide whether to layer it into the values stack;
	// the kernel never receives debugValues as a parameter.
	DebugValues = cue.ParsePath("debugValues")

	// Provider.
	Transformers = cue.ParsePath("#transformers")

	// Platform. Five paths point at #registry and the four CUE-computed views
	// over it. KnownResources / KnownTraits are retained in the inventory
	// even though enhancement 0001's #Platform reshape drops the fields —
	// downstream consumers may still query them via LookupPath, and a missing
	// field yields a non-existent cue.Value rather than a hard error.
	Registry             = cue.ParsePath("#registry")
	KnownResources       = cue.ParsePath("#knownResources")
	KnownTraits          = cue.ParsePath("#knownTraits")
	ComposedTransformers = cue.ParsePath("#composedTransformers")
	Matchers             = cue.ParsePath("#matchers")
	MatchersResources    = cue.ParsePath("#matchers.resources")
	MatchersTraits       = cue.ParsePath("#matchers.traits")

	// Transformer body and matching predicates.
	Transform                    = cue.ParsePath("#transform")
	TransformerRequiredLabels    = cue.ParsePath("requiredLabels")
	TransformerRequiredResources = cue.ParsePath("requiredResources")
	TransformerRequiredTraits    = cue.ParsePath("requiredTraits")
	TransformerOptionalTraits    = cue.ParsePath("optionalTraits")

	// Inside #transform.
	Component = cue.ParsePath("#component")
	Context   = cue.MakePath(cue.Def("context"))
	Output    = cue.ParsePath("output")

	// Sub-paths of #context filled per (instance, component, transformer) pair.
	// Was: ContextModuleReleaseMetadata
	ContextModuleInstanceMetadata = cue.MakePath(cue.Def("context"), cue.Def("moduleInstanceMetadata"))
	ContextComponentMetadata      = cue.MakePath(cue.Def("context"), cue.Def("componentMetadata"))
	ContextRuntimeName            = cue.MakePath(cue.Def("context"), cue.Def("runtimeName"))

	// Component sub-paths.
	//
	// Blueprints are deliberately omitted: a Blueprint is a composition
	// template — its composedResources / composedTraits unify into a
	// Component's spec at CUE-evaluation time (see component.cue _allFields).
	// By the time the renderer sees a Component, blueprints are already
	// merged. Walking #blueprints separately would double-count.
	// MatchLabels is the component's MATCHING identity (0010 D36) — the
	// derived union of its attached primitives' matchLabels. The matcher
	// reads this, and only this, for label predicates; metadata.labels is
	// descriptive and stays readable by non-matching consumers (component
	// summaries, the transformer render context).
	MatchLabels         = cue.ParsePath("matchLabels")
	MetadataLabels      = cue.ParsePath("metadata.labels")
	MetadataAnnotations = cue.ParsePath("metadata.annotations")
	MetadataFQN         = cue.ParsePath("metadata.fqn")
	ComponentResources  = cue.MakePath(cue.Def("resources"))
	ComponentTraits     = cue.MakePath(cue.Def("traits"))
)

CUE paths the kernel, matcher, helpers, and renderer use to read or write fields on an OPM artifact. Every consumer that previously called binding.Paths() now references these vars directly.

Definition fields (those starting with "#" in CUE) use cue.MakePath with cue.Def selectors; concrete fields use cue.ParsePath. The two forms are not interchangeable — definition paths constructed with ParsePath do not resolve on closed structs.

Functions

func BuildTransformerContext

func BuildTransformerContext(
	cueCtx *cue.Context,
	inst InstanceView,
	compName string,
	schemaComp cue.Value,
	runtimeName string,
) (cue.Value, []string, error)

BuildTransformerContext constructs the #context value for a single (instance, component, transformer) pair. The caller fills the returned value at schema.Context on the unified transformer.

schemaComp must be the schema-preserving component value (the one that still has metadata.labels and metadata.annotations as concrete fields). Decode errors on those metadata fields surface as warnings, not errors.

Types

type Cache

type Cache struct {
	// Loader is the strategy used to resolve and build the schema value.
	// Required.
	Loader Loader
	// contains filtered or unexported fields
}

Cache memoizes a single Loader.Load invocation per instance and exposes the resolved schema module version for diagnostics. It owns no goroutines and no I/O of its own; the Loader carries those concerns.

The first Cache.Get invocation runs Loader.Load through sync.Once; every subsequent Get (including the one that loses the race) returns the same cached value or the same cached error. Errors are cached too — the load is never retried. To force a re-fetch, construct a fresh Cache with a fresh Loader.

Each Cache instance owns its own memoization. The library MUST NOT expose a package-level Cache singleton; long-running consumers attach the Cache to a Kernel (or equivalent lifetime anchor) and keep that anchor alive across operations.

func (*Cache) Get

func (c *Cache) Get(ctx *cue.Context) (cue.Value, error)

Get returns the schema cue.Value, invoking the underlying Loader at most once per Cache instance. Concurrent first-call invocations are serialized via sync.Once; the call that wins runs Loader.Load and the rest observe the cached result.

Returns the zero cue.Value and a non-nil error if Loader.Load fails; the error is cached and subsequent calls return it without re-invoking the Loader.

func (*Cache) ResolvedVersion

func (c *Cache) ResolvedVersion() string

ResolvedVersion returns the schema module version that the underlying Loader resolved during the first successful Cache.Get (e.g. "v2.0.0-alpha.4" when the default identifier resolved to that instance).

Returns the empty string before the first successful Get, after a failed Get, or when the Loader does not surface a resolved version. The value is diagnostic-only: callers SHOULD log it but MUST NOT branch behavior on it.

type ComponentContextData

type ComponentContextData struct {
	Name        string            `json:"name"`
	Labels      map[string]string `json:"labels,omitempty"`
	Annotations map[string]string `json:"annotations,omitempty"`
}

ComponentContextData is the Go-side mirror of #TransformerContext.#componentMetadata.

type InstanceMetadata

type InstanceMetadata struct {
	// Name is the instance name (from --name or module.metadata.name).
	Name string `json:"name"`

	// Namespace is the target namespace.
	Namespace string `json:"namespace"`

	// FQN is the instance's OWN fully qualified name
	// (registryPath:name:namespace), defined by core v2 on
	// #ModuleInstance.metadata and decoded via the schema.MetadataFQN path.
	// Distinct from the source module's FQN (InstanceView.ModuleFQN).
	FQN string `json:"fqn,omitempty"`

	// UUID is the instance identity UUID.
	// Computed by CUE as SHA1(OPMNamespace, moduleUUID:name:namespace).
	UUID string `json:"uuid"`

	// Labels are the merged instance labels (module labels + standard opm labels).
	Labels map[string]string `json:"labels,omitempty"`

	// Annotations are the merged instance annotations.
	Annotations map[string]string `json:"annotations,omitempty"`
}

InstanceMetadata contains instance-level identity information. Used for inventory tracking, resource labeling, and CLI output.

Was: ReleaseMetadata

func DecodeInstanceMetadata

func DecodeInstanceMetadata(v cue.Value) (*InstanceMetadata, error)

DecodeInstanceMetadata extracts InstanceMetadata from a #ModuleInstance artifact root. A missing metadata field is fatal.

Was: DecodeReleaseMetadata

type InstanceView

type InstanceView interface {
	InstanceName() string
	Namespace() string
	InstanceUUID() string
	// InstanceFQN is the instance's own metadata.fqn
	// (registryPath:name:namespace, core v2) — the value the transformer
	// context's #moduleInstanceMetadata.fqn carries (0010 D41).
	InstanceFQN() string
	ModuleFQN() string
	ModuleVersion() string
	Labels() map[string]string
	Annotations() map[string]string
}

InstanceView is the read-only view of a module instance that BuildTransformerContext needs. The interface exists so the context builder stays decoupled from opm/module; any caller-supplied type that exposes these accessors can drive context construction (e.g. tests).

Was: ReleaseView

type Loader

type Loader interface {
	Load(ctx *cue.Context) (cue.Value, error)
}

Loader resolves the OPM core CUE schema and returns it as a built cue.Value. Implementations MUST return a value whose definitions (#Module, #ModuleInstance, #Platform, #Resource, #Trait, #ComponentTransformer, …) are reachable via LookupPath.

The library exposes exactly one Loader implementation: OCILoader. Any other Loader satisfying the interface is internal-only and MUST NOT appear in the public API surface.

type ModuleInstanceContextData

type ModuleInstanceContextData struct {
	Name        string            `json:"name"`
	Namespace   string            `json:"namespace"`
	FQN         string            `json:"fqn"`
	Version     string            `json:"version"`
	UUID        string            `json:"uuid"`
	Labels      map[string]string `json:"labels,omitempty"`
	Annotations map[string]string `json:"annotations,omitempty"`
}

ModuleInstanceContextData is the Go-side mirror of #TransformerContext.#moduleInstanceMetadata. Field names use json tags that match the CUE definition fields.

Was: ModuleReleaseContextData

type ModuleMetadata

type ModuleMetadata struct {
	// Name is the canonical module name from module.metadata.name (kebab-case).
	Name string `json:"name"`

	// Description is a brief description of the module.
	Description string `json:"description,omitempty"`

	// ModulePath is the CUE registry module path from metadata.modulePath.
	// This is the registry path (e.g., "opmodel.dev/modules"), NOT a filesystem path.
	ModulePath string `json:"modulePath"`

	// Version is the module version (semver).
	Version string `json:"version"`

	// FQN is the fully qualified module name (modulePath/name:version).
	// Example: "opmodel.dev/modules/my-app:1.0.0"
	FQN string `json:"fqn"`

	// UUID is the module identity UUID (from #Module.metadata.identity).
	UUID string `json:"uuid"`

	// Labels from the module definition (pre-build, author-declared).
	Labels map[string]string `json:"labels,omitempty"`

	// Annotations from the module definition.
	Annotations map[string]string `json:"annotations,omitempty"`
}

ModuleMetadata contains module-level identity and version information. This is the module's canonical metadata, distinct from the instance it is deployed as. Populated by DecodeModuleMetadata.

func DecodeModuleMetadata

func DecodeModuleMetadata(v cue.Value) (*ModuleMetadata, error)

DecodeModuleMetadata extracts ModuleMetadata from a #Module artifact root. A missing metadata field is fatal.

type OCILoader

type OCILoader struct {
	// Module is the schema module identifier. Empty means
	// [DefaultSchemaModule] ("opmodel.dev/core@v2").
	//
	// A bare major form ("…@v0") is automatically expanded to "…@v0.latest"
	// before calling [load.Instances]; CUE's standalone-package loader
	// requires either a fully qualified version, "@latest", or
	// "<major>.latest" outside a module context.
	Module string

	// Registry overrides CUE_REGISTRY for this load. Empty inherits from
	// the process environment.
	Registry string

	// CacheDir overrides CUE_CACHE_DIR for this load. Empty inherits from
	// the process environment (or CUE's default ~/.cache/cuelang/).
	CacheDir string
}

OCILoader resolves the OPM core schema through CUE's module system. It is the canonical and only public Loader implementation.

The zero value is a valid Loader: empty fields resolve via process environment (CUE_REGISTRY, CUE_CACHE_DIR) and the DefaultSchemaModule identifier. Explicit field values override environment values.

OCILoader.Load does not mutate process state (no os.Setenv); env overrides are plumbed into load.Config.Env for the single load call.

func (OCILoader) Load

func (l OCILoader) Load(ctx *cue.Context) (cue.Value, error)

Load implements Loader.

type PlatformMetadata

type PlatformMetadata struct {
	Name        string            `json:"name"`
	Type        string            `json:"type"`
	Description string            `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	Annotations map[string]string `json:"annotations,omitempty"`
}

PlatformMetadata is the canonical decoded platform-level metadata. Type is the top-level #Platform.type field hoisted into the metadata projection so callers see one Go-level identity record per Platform artifact.

func DecodePlatformMetadata

func DecodePlatformMetadata(v cue.Value) (*PlatformMetadata, error)

DecodePlatformMetadata extracts PlatformMetadata from a #Platform value. metadata.{name,description,labels,annotations} is decoded directly into the struct; the top-level #Platform.type field is read separately and merged into Metadata.Type so callers see one identity record per Platform. A missing metadata field is fatal.

type ProviderMetadata

type ProviderMetadata struct {
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	Version     string            `json:"version,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	Annotations map[string]string `json:"annotations,omitempty"`
}

ProviderMetadata is the canonical decoded provider-level metadata.

func DecodeProviderMetadata

func DecodeProviderMetadata(v cue.Value, fallbackName string) (*ProviderMetadata, error)

DecodeProviderMetadata extracts ProviderMetadata from a #Provider value. fallbackName is used when the artifact's metadata is absent or its name field decoded as empty — typically the config map key under which the provider was loaded.

Jump to

Keyboard shortcuts

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