declarative

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 27 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 declarative implements `oa apply`, `oa diff` and `oa export`: it loads Kubernetes-style YAML manifests, validates them against per-kind schemas, diffs them against the live server state fetched through the REST API and applies the difference in dependency order.

Index

Constants

View Source
const (
	KindUser             = "User"
	KindServiceAccount   = "ServiceAccount"
	KindProject          = "Project"
	KindGroup            = "Group"
	KindRepository       = "Repository"
	KindPermissionTarget = "PermissionTarget"
	KindOIDCTrustPolicy  = "OIDCTrustPolicy"
	KindSSOProvider      = "SSOProvider"
	KindWebhook          = "Webhook"
	KindStorageTier      = "StorageTier"
	KindTierPolicy       = "TierPolicy"
)

Manifest kinds.

View Source
const APIVersion = "openartifact.io/v1"

APIVersion is the only manifest apiVersion.

Variables

View Source
var ErrNotAdmin = errors.New("oa apply needs an administrator token (manage permission)")

ErrNotAdmin is returned when the token lacks the manage permission.

View Source
var ErrPrincipalNotFound = errors.New("not found on the server")

ErrPrincipalNotFound is wrapped when a manifest names a user, service account or group that does not exist.

View Source
var ErrSecretUnresolved = errors.New("secret cannot be resolved")

ErrSecretUnresolved is wrapped by every resolution failure.

View Source
var ErrServerTooOld = errors.New("server does not support declarative configuration")

ErrServerTooOld is wrapped when the server lacks the declarative API.

View Source
var ErrUnknownKind = errors.New("unknown kind")

ErrUnknownKind is wrapped when --kind names a kind that does not exist.

Functions

func Bool

func Bool(spec map[string]any, key string) bool

Bool returns spec[key] as a bool (false when absent or not a bool).

func Canon

func Canon(v any) any

Canon converts v into the canonical JSON-typed form the engine compares: all numbers become float64, maps become map[string]any, slices become []any. SecretRef values pass through unchanged.

func ChangedTop

func ChangedTop(changes []Change) map[string]bool

ChangedTop returns the set of top-level field names touched by changes.

func CheckSecrets

func CheckSecrets(plan *Plan, r SecretResolver) []error

CheckSecrets resolves every secret the plan will send, before anything is changed, so a missing environment variable or file aborts the run early.

func FormatValue

func FormatValue(v any) string

FormatValue renders a value for reports: secrets as "(secret)", whole numbers without a decimal point, strings quoted, containers as compact JSON.

func Ident

func Ident(kind, key string) string

Ident formats "Kind/key" for messages.

func IsStatus

func IsStatus(err error, status int) bool

IsStatus reports whether err is an APIError with the given HTTP status.

func KindFilter

func KindFilter(reg *Registry, names []string) (map[string]bool, error)

KindFilter resolves --kind names to a set of canonical kind names. A nil set means no restriction.

func Omit

func Omit(spec map[string]any, keys ...string) map[string]any

Omit returns a copy of spec without keys.

func PatchBody

func PatchBody(changes []Change) map[string]any

PatchBody builds the request body of a PATCH/PUT from changes: dotted paths become nested objects, so {oidc_config.issuer, public} yields {"oidc_config": {"issuer": ...}, "public": ...}. Top-level fields not in changes are absent, which the REST PATCH endpoints treat as unchanged.

func PathEscape

func PathEscape(s string) string

PathEscape escapes one URL path segment (names may contain unusual runes).

func Pick

func Pick(spec map[string]any, keys ...string) map[string]any

Pick returns a copy of spec restricted to keys.

func SortObjects

func SortObjects(reg *Registry, objs []*Object)

SortObjects orders objects for apply: kind rank, kind order, key.

func SortedStrings

func SortedStrings(s []string) []string

SortedStrings returns a sorted copy of s.

func SpecHash

func SpecHash(o *Object) string

SpecHash is the digest recorded in the ownership marker: sha256 of the canonical desired spec, secrets replaced by their reference (never values).

func Str

func Str(spec map[string]any, key string) string

Str returns spec[key] as a string ("" when absent or not a string).

func StrList

func StrList(spec map[string]any, key string) []string

StrList returns spec[key] as a string slice (nil when absent).

func TopField

func TopField(path string) string

TopField returns the top-level field of a change path ("members[bob].role" -> "members", "oidc_config.issuer" -> "oidc_config").

func WriteDiff

func WriteDiff(w io.Writer, plan *Plan)

WriteDiff prints the plan as a field-level diff: one header per changed object, then "-" (live) and "+" (desired) lines per field. Unchanged objects are omitted.

func WriteDir

func WriteDir(dir string, docs []ExportDoc) ([]string, error)

WriteDir writes one file per object at <dir>/<kind>/<key>.yaml and returns the paths written.

func WriteJSON

func WriteJSON(w io.Writer, plan *Plan, outcomes []Outcome) error

WriteJSON prints BuildJSON(plan, outcomes) as indented JSON.

func WriteStream

func WriteStream(w io.Writer, docs []ExportDoc) error

WriteStream writes the documents as one multi-document YAML stream.

func WriteSummary

func WriteSummary(w io.Writer, plan *Plan)

WriteSummary prints the one-line totals.

func WriteTable

func WriteTable(w io.Writer, plan *Plan, outcomes []Outcome)

WriteTable prints a one-line-per-object summary. With outcomes, the RESULT column shows what happened to each item.

Types

type APIError

type APIError struct {
	Method  string
	Path    string
	Status  int
	Message string
}

APIError is a non-2xx answer from the server.

func (*APIError) Error

func (e *APIError) Error() string

type Action

type Action string

Action is what the plan does to one object.

const (
	ActionCreate    Action = "create"
	ActionUpdate    Action = "update"
	ActionUnchanged Action = "unchanged"
	ActionDelete    Action = "delete"
)

Plan actions.

type Change

type Change struct {
	// Path is the dotted spec path, e.g. "public" or "oidc_config.issuer".
	Path string `json:"path"`
	Old  any    `json:"old,omitempty"`
	New  any    `json:"new,omitempty"`
	// Secret changes never carry values in reports; New holds the resolved
	// secret only for the kind's Update call.
	Secret bool `json:"secret,omitempty"`
}

Change is one field-level difference between the live and the desired state.

type Client

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

Client is the minimal authenticated JSON client the engine talks to the OpenArtifact REST API with.

func NewClient

func NewClient(baseURL, token string, httpClient *http.Client) *Client

NewClient returns a client for the server at baseURL authenticated with an API token. httpClient may be nil (http.DefaultClient). Every call is bounded by defaultRequestTimeout, whichever http client carries it.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body, out any) error

Do sends a request with an optional JSON body and decodes a JSON answer into out (nil to discard it). Answers outside 2xx become *APIError. The call ends with context.DeadlineExceeded after the client's timeout.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, out any) error

Get is Do(GET) decoding into out.

type Env

type Env struct {
	Client *Client
	// Cache is scratch space for kinds (e.g. account name to id lookups). Kinds
	// must delete entries they invalidate by creating objects.
	Cache map[string]any
}

Env is the per-run context handed to kinds.

func NewEnv

func NewEnv(client *Client) *Env

NewEnv returns an Env for client.

func (*Env) ForgetIdents

func (e *Env) ForgetIdents()

ForgetIdents drops the cached account/group lookups; kinds that create or delete users, service accounts or groups call it so later lookups see them.

func (*Env) GroupID

func (e *Env) GroupID(ctx context.Context, name string) (string, error)

GroupID resolves a group name to its id.

func (*Env) GroupNames

func (e *Env) GroupNames(ctx context.Context) (map[string]string, error)

GroupNames returns id to name for every group.

func (*Env) ServiceAccountID added in v0.16.0

func (e *Env) ServiceAccountID(ctx context.Context, name string) (string, error)

ServiceAccountID resolves a service account name to its id.

func (*Env) UserID

func (e *Env) UserID(ctx context.Context, username string) (string, error)

UserID resolves the name of a user or service account to its id.

func (*Env) UserNames

func (e *Env) UserNames(ctx context.Context) (map[string]string, error)

UserNames returns id to name for every user and service account.

type ExportDoc

type ExportDoc struct {
	Kind string
	Key  string
	YAML []byte
}

ExportDoc is one exported manifest document.

func Export

func Export(ctx context.Context, opts ExportOptions) ([]ExportDoc, error)

Export reads the live state and renders it as manifests. Seeded objects are skipped; write-only secrets that are set become secretRef placeholders.

type ExportOmitter

type ExportOmitter interface {
	ExportOmit() []string
}

ExportOmitter is implemented by kinds whose Live.Spec carries fields that `oa export` leaves out by default because they are usually filled by other systems (Group "members", populated by SSO group sync). The fields are emitted with `oa export --with-members`.

type ExportOptions

type ExportOptions struct {
	Registry *Registry
	Client   *Client
	// Kinds restricts the export; empty means every kind except User. Naming
	// User explicitly includes the human users.
	Kinds []string
	// WithMembers includes fields kinds omit by default (Group members).
	WithMembers bool
}

ExportOptions select what `oa export` emits.

type Field

type Field struct {
	Type     Type
	Required bool
	// Nullable accepts an explicit null (the server then inherits a default).
	Nullable bool
	// Enum restricts a TString.
	Enum []string
	// Min is the lower bound of a TInt/TNumber when HasMin is set.
	Min    float64
	HasMin bool
	// Secret marks a write-only field: manifests give a {secretRef: ...}
	// instead of a value and the server never returns it.
	Secret bool
	// Immutable fields cannot change on an existing object.
	Immutable bool
	// FromMeta takes the value from metadata.<field name> instead of spec
	// (Repository project).
	FromMeta bool
	// Fields are the keys of a TObject.
	Fields map[string]*Field
	// Elem is the element type of a TList/TSet/TMap.
	Elem *Field
	// KeyBy names the identity key of TSet/TList elements that are objects. A
	// comma-separated list names a composite key: the elements are identified by
	// their values of those fields, joined with "|" (an absent field is "").
	KeyBy string
}

Field is a node of a kind's spec schema.

type Identifier

type Identifier interface {
	Identity(live *Live) (name string, meta map[string]string)
}

Identifier is implemented by kinds whose natural key is not just the metadata name (Webhook: "<repository>/<name>"). `oa export` uses it to split a live object back into metadata.name and the extra metadata keys.

type Idents

type Idents struct {
	// Users maps the name of every account a user reference may name (human
	// users and service accounts) to its id; Groups maps group name to group id.
	Users  map[string]string
	Groups map[string]string
	// ServiceAccounts maps service account name to id: the subset of Users that
	// can be the target of a trust policy.
	ServiceAccounts map[string]string
}

Idents is the account and group lookup shared by kinds that reference them.

type Item

type Item struct {
	Action  Action
	Kind    string
	Key     string
	Desired *Object
	Live    *Live
	Changes []Change
	// Adopt marks an existing object without a valid ownership marker that
	// apply will take over (writing the marker) even when nothing changes.
	Adopt bool
	// Managed is set on delete items: the object carries a valid marker.
	Managed bool
	// Err is a plan-time problem with this item; any Err makes the whole plan
	// unapplicable.
	Err error
}

Item is one planned operation.

type JSONReport

type JSONReport struct {
	Summary map[Action]int `json:"summary"`
	Items   []jsonItem     `json:"items"`
	Changes bool           `json:"changes"`
	Errors  []string       `json:"errors,omitempty"`
}

JSONReport is the machine-readable form of a plan (and its execution).

func BuildJSON

func BuildJSON(plan *Plan, outcomes []Outcome) *JSONReport

BuildJSON converts a plan (and optional outcomes) into a JSONReport. Secret values never appear: secret changes carry only the flag.

type Kind

type Kind interface {
	// Name is the manifest kind, e.g. "Repository".
	Name() string
	// Rank orders kinds for apply (ascending) and prune (descending).
	Rank() int
	// Schema describes the manifest spec of this kind.
	Schema() *Field
	// MetaKeys lists the metadata keys besides name this kind accepts that stay
	// in Object.Meta (Webhook: "repository"). Keys mapped into the spec through
	// Field.FromMeta are not listed.
	MetaKeys() []string
	// Key returns the natural key of o: the name, or scope/name where names are
	// only unique within a scope.
	Key(o *Object) string
	// Order orders objects of this kind within an apply pass (ascending); e.g.
	// group repositories after their members.
	Order(o *Object) int
	// Refs lists the objects o depends on.
	Refs(o *Object) []Ref
	// List returns every object of this kind that exists on the server.
	List(ctx context.Context, env *Env) ([]*Live, error)
	// Create creates o. Secrets in o.Spec are already resolved to strings.
	// It returns the server-side id for the ownership marker.
	Create(ctx context.Context, env *Env, o *Object) (id string, err error)
	// Update applies changes to live. Only the changes may be sent; secret
	// changes carry their resolved value in New. It returns the id for the
	// ownership marker (normally live.ID).
	Update(ctx context.Context, env *Env, live *Live, o *Object, changes []Change) (id string, err error)
	// Delete removes live from the server.
	Delete(ctx context.Context, env *Env, live *Live) error
}

Kind implements one manifest kind against the REST API.

func NewGroupKind

func NewGroupKind() Kind

NewGroupKind returns the Group kind.

func NewOIDCTrustPolicyKind added in v0.16.0

func NewOIDCTrustPolicyKind() Kind

NewOIDCTrustPolicyKind returns the OIDCTrustPolicy kind.

func NewPermissionTargetKind

func NewPermissionTargetKind() Kind

NewPermissionTargetKind returns the PermissionTarget kind.

func NewProjectKind

func NewProjectKind() Kind

NewProjectKind returns the Project kind.

func NewRepositoryKind

func NewRepositoryKind() Kind

NewRepositoryKind returns the Repository kind. Its natural key is the repository name (metadata.name); the owning project is metadata.project.

func NewSSOProviderKind

func NewSSOProviderKind() Kind

NewSSOProviderKind returns the SSOProvider kind. Its natural key is the provider slug (metadata.name); the slug and the provider kind are immutable.

func NewServiceAccountKind added in v0.16.0

func NewServiceAccountKind() Kind

NewServiceAccountKind returns the ServiceAccount kind.

func NewStorageTierKind

func NewStorageTierKind() Kind

NewStorageTierKind returns the StorageTier kind. The key is the tier name. spec.backend names a storage backend that must already exist (StorageBackend is not a managed kind); the server-created primary tier has a null backend, is never pruned and cannot be created declaratively.

func NewTierPolicyKind

func NewTierPolicyKind() Kind

NewTierPolicyKind returns the TierPolicy kind. The key is the policy name, which the server enforces to be unique.

func NewUserKind

func NewUserKind() Kind

NewUserKind returns the User kind.

func NewWebhookKind

func NewWebhookKind() Kind

NewWebhookKind returns the Webhook kind.

type Live

type Live struct {
	Kind string
	// Key is the natural key (see Kind.Key).
	Key string
	// ID is the server-side identifier (uuid, slug or name) recorded in the
	// ownership marker.
	ID   string
	Spec map[string]any
	// Secrets reports, per write-only field path, whether a value is set on
	// the server. A path missing from the map means presence is unknown.
	Secrets map[string]bool
	// Seeded marks objects created by the server itself (admin-all,
	// anonymous-read, the system project, the bootstrap admin). They are never
	// pruned.
	Seeded bool
}

Live is one object as it exists on the server, normalized into manifest shape: Spec only contains fields the kind's schema declares.

type LoadOptions

type LoadOptions struct {
	// Paths are files or directories; "-" reads Stdin.
	Paths []string
	// Recursive descends into subdirectories of directory paths.
	Recursive bool
	// Stdin is read for the path "-".
	Stdin io.Reader
}

LoadOptions selects the manifest files to load.

type Marker

type Marker struct {
	Kind        string    `json:"kind"`
	Name        string    `json:"name"`
	ObjectID    string    `json:"object_id"`
	AppliedHash string    `json:"applied_hash"`
	AppliedAt   time.Time `json:"applied_at"`
}

Marker is the server-side ownership record of an object created or adopted by `oa apply`.

type Markers

type Markers map[string]Marker

Markers indexes markers by Ident(kind, name).

func Preflight

func Preflight(ctx context.Context, c *Client) (Markers, error)

Preflight verifies the token can manage the server and returns the ownership markers.

type Object

type Object struct {
	Kind string
	Name string
	// Meta holds the metadata keys other than name that the kind allows and
	// that are not mapped into the spec (e.g. Webhook "repository").
	Meta map[string]string
	Spec map[string]any
	Pos  Pos
	// FieldPos maps a dotted spec path to the position of its value.
	FieldPos map[string]Pos
}

Object is one desired object loaded from a manifest document.

Spec holds JSON-typed values (string, float64, bool, []any, map[string]any, nil) in the same shape and snake_case names as the REST API. Fields the schema marks Secret hold a SecretRef until the engine resolves it.

func Load

func Load(reg *Registry, opts LoadOptions) ([]*Object, error)

Load reads, parses and validates every manifest under opts.Paths. All problems are collected: the returned error is a ValidationErrors. Objects are returned in file order.

type Options

type Options struct {
	Registry *Registry
	Client   *Client
	Load     LoadOptions
	// Kinds restricts manifests and pruning to these kinds (case-insensitive
	// names); empty means every kind.
	Kinds           []string
	Prune           bool
	PruneAll        bool
	ForceSecrets    bool
	ContinueOnError bool
	Resolver        SecretResolver
}

Options configure a plan or apply run.

type Outcome

type Outcome struct {
	Item   *Item
	Status Status
	Err    error
}

Outcome is the result of executing one plan item.

func Execute

func Execute(ctx context.Context, opts Options, p *Prepared) []Outcome

Execute applies the plan. It stops at the first failure unless continueOnError is set; items not reached are reported as skipped.

func Failed

func Failed(outcomes []Outcome) []Outcome

Failed returns the failed outcomes.

type Plan

type Plan struct {
	Items []*Item
}

Plan is the ordered list of operations: creates/updates/unchanged in dependency order, then deletes in reverse dependency order.

func BuildPlan

func BuildPlan(in PlanInput) *Plan

BuildPlan diffs the desired objects against the live state.

func (*Plan) Counts

func (p *Plan) Counts() map[Action]int

Counts returns the number of items per action.

func (*Plan) Errors

func (p *Plan) Errors() []error

Errors returns the plan-time errors.

func (*Plan) HasChanges

func (p *Plan) HasChanges() bool

HasChanges reports whether applying the plan would modify the server (adoption alone only writes ownership markers and is not a change).

type PlanInput

type PlanInput struct {
	Registry *Registry
	Desired  []*Object
	// Live holds the objects found on the server per kind. A kind without an
	// entry was not fetched: references to it are not checked and it is never
	// pruned.
	Live    map[string][]*Live
	Markers Markers
	// Prune deletes managed objects absent from Desired; PruneAll also deletes
	// unmanaged ones (never seeded objects, never Users or ServiceAccounts
	// unless the kind filter names that kind).
	Prune        bool
	PruneAll     bool
	ForceSecrets bool
	// Kinds restricts pruning to these kinds (nil = every fetched kind).
	Kinds map[string]bool
}

PlanInput is everything BuildPlan needs; it performs no I/O.

type Pos

type Pos struct {
	File string
	Line int
}

Pos is a position in a manifest file.

func (Pos) String

func (p Pos) String() string

type Prepared

type Prepared struct {
	Plan    *Plan
	Markers Markers
	Env     *Env
}

Prepared is a loaded, validated and planned run.

func Prepare

func Prepare(ctx context.Context, opts Options) (*Prepared, error)

Prepare loads the manifests, reads the live state and builds the plan.

type Prunable

type Prunable interface {
	Prunable(live *Live) bool
}

Prunable is implemented by kinds where some live objects are not worth deleting: User "deletion" only disables the account, so an already disabled user would show up as a pending deletion forever.

type Ref

type Ref struct {
	Kind string
	// Also lists the further kinds that satisfy the reference when Kind has no
	// object with this key (a user reference accepts a ServiceAccount: account
	// names are unique across both).
	Also []string
	Key  string
	// Field is the spec path holding the reference, for error messages.
	Field string
}

Ref is a reference from one object to another that must exist (in the manifests or on the server) for the object to be applied.

type Registry

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

Registry is the set of kinds the engine manages, keyed by manifest kind.

func DefaultRegistry

func DefaultRegistry() *Registry

DefaultRegistry returns the registry with every supported kind.

func NewRegistry

func NewRegistry(kinds ...Kind) *Registry

NewRegistry returns a registry of the given kinds.

func (*Registry) Get

func (r *Registry) Get(name string) (Kind, bool)

Get returns the kind named name (exact, case-sensitive manifest spelling).

func (*Registry) Lookup

func (r *Registry) Lookup(name string) (Kind, bool)

Lookup is Get with a case-insensitive name, for command-line flags.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns the kind names in apply order.

func (*Registry) Ordered

func (r *Registry) Ordered() []Kind

Ordered returns the kinds in apply order (ascending rank, then name).

type SecretRef

type SecretRef struct {
	Env  string
	File string
}

SecretRef points at a secret resolved on the machine running oa. Exactly one field is set. File is already absolute (relative paths are resolved against the manifest's directory when the manifest is loaded).

func PlanSecretRefs added in v0.16.1

func PlanSecretRefs(plan *Plan) []SecretRef

PlanSecretRefs lists the distinct secret references the plan is going to send (creates and updates), sorted by their String form. A caller that cannot read the environment or files itself uses it to ask for the values.

func (SecretRef) String

func (r SecretRef) String() string

type SecretResolver

type SecretResolver struct {
	// LookupEnv defaults to os.LookupEnv.
	LookupEnv func(string) (string, bool)
	// ReadFile defaults to a bounded os.ReadFile.
	ReadFile func(string) ([]byte, error)
}

SecretResolver turns SecretRefs into values on the machine running oa. The zero value reads the process environment and the file system.

func (SecretResolver) Resolve

func (r SecretResolver) Resolve(ref SecretRef) (string, error)

Resolve returns the secret ref points at. Empty secrets are an error, a trailing newline of a file is stripped.

type Status

type Status string

Status is the outcome of one executed item.

const (
	StatusApplied Status = "applied"
	StatusFailed  Status = "failed"
	StatusSkipped Status = "skipped"
)

Item outcomes.

type Type

type Type int

Type is the type of a manifest field.

const (
	// TObject is a mapping with the fixed keys in Field.Fields.
	TObject Type = iota
	TString
	TInt
	TNumber
	TBool
	// TList is an ordered list of Field.Elem.
	TList
	// TSet is an unordered list of Field.Elem (compared sorted; Elem objects
	// are ordered by Field.KeyBy).
	TSet
	// TMap is a mapping with free string keys and Field.Elem values; it is
	// replaced as a whole.
	TMap
	// TAny accepts any JSON-typed value; it is compared as a whole.
	TAny
)

Field types.

type ValidationError

type ValidationError struct {
	Pos Pos
	// Ident is "Kind/name" of the object, empty for file-level problems.
	Ident string
	// Path is the dotted field path, empty for the object itself.
	Path string
	Msg  string
}

ValidationError is one problem in a manifest, positioned at file:line.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type ValidationErrors

type ValidationErrors []error

ValidationErrors is the aggregate returned by Load.

func (ValidationErrors) Error

func (v ValidationErrors) Error() string

func (ValidationErrors) Unwrap

func (v ValidationErrors) Unwrap() []error

Unwrap lets errors.Is/As see the individual errors.

type Validator

type Validator interface {
	Validate(o *Object) []error
}

Validator is implemented by kinds with cross-field rules the schema cannot express (e.g. an SSO provider needs the config block matching its kind). It runs after schema validation; returned errors are reported at the object's position.

Jump to

Keyboard shortcuts

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