session

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: BSD-3-Clause Imports: 12 Imported by: ? 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 session is a Go-usable editable configuration session over a yaseer document tree: read/write/delete fields and resources by path, compile or validate the whole config, and fork copy-on-write to validate speculative edits before merging them back. It is the same abstraction the browser wasm exposes, usable directly from Go (e.g. tau-cli).

The core (edit, fork, merge, save) is DSL-agnostic; compilation is injected via CompilerFor, so the Taubyte binding lives in pkg/tcc/taubyte/v1/schema, not here.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bindings

type Bindings struct {
	CompilerFor    CompilerFor
	FieldValidator FieldValidator
	Completer      Completer
	Layout         Layout
	Generator      Generator
}

Bindings wires a Session to a specific DSL: how to compile it (required), how to partial-validate its fields, how to complete field values, how its documents are laid out, and how its generated fields are minted (all optional).

type CoW

type CoW struct {
	afero.Fs // = afero.NewCopyOnWriteFs(base, layer): Create/OpenFile/Mkdir/Rename/copy-up
	// contains filtered or unexported fields
}

CoW is a copy-on-write filesystem that, unlike afero.CopyOnWriteFs, can delete files that live only in the read-only base. Writes and copy-up are inherited from the embedded *afero.CopyOnWriteFs; deletes are recorded as in-memory whiteouts and the read side (Stat/Open/Readdir) hides whiteouted paths, so a removed base file truly disappears. The overlay files plus the whiteout set are exactly the changeset over the base — cheap to inspect and to collapse on merge.

afero.CopyOnWriteFs.Remove returns EPERM for base-only files (it has no whiteouts); this type exists to close that gap.

func NewCoW

func NewCoW(base afero.Fs) *CoW

NewCoW layers a fresh in-memory overlay over base (kept read-only).

func (*CoW) Changed

func (c *CoW) Changed() (written []string, deleted []string)

Changed returns the changeset over the base: paths written in the overlay and paths whiteouted (deleted). Used to collapse a fork onto its parent on merge.

func (*CoW) Create

func (c *CoW) Create(name string) (afero.File, error)

func (*CoW) Open

func (c *CoW) Open(name string) (afero.File, error)

func (*CoW) OpenFile

func (c *CoW) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error)

func (*CoW) Remove

func (c *CoW) Remove(name string) error

func (*CoW) RemoveAll

func (c *CoW) RemoveAll(name string) error

func (*CoW) Stat

func (c *CoW) Stat(name string) (os.FileInfo, error)

type CompileOptions

type CompileOptions struct {
	Branch string
	Cloud  string
}

CompileOptions are the per-compile parameters (empty Branch uses the compiler's default).

type CompilerFor

type CompilerFor func(fs afero.Fs, branch, cloud string) (*interp.Compiler, error)

CompilerFor builds a compiler over an afero filesystem for the given compile parameters. The schema package supplies the Taubyte binding; the session never imports schema, keeping the dependency one-way.

type Completer

type Completer interface {
	// Field returns a field's fixed candidates and, if it references a resource
	// group, that group + the prefix to prepend to each referenced name. found is
	// false when the field is unknown (no such attribute path).
	Field(group string, field []string) (values []string, refGroup, refPrefix string, found bool)
}

Completer supplies a DSL's field completion sources: the fixed candidates (enum members, shape literals) and, for a reference field, the resource group whose in-scope instances are candidates. Injected by the binding.

type FieldIssue

type FieldIssue struct {
	Field   []string `json:"field"`
	Message string   `json:"message"`
}

FieldIssue is one failed check, attributed to the field that failed it. Field is the authored path ("trigger/domains" as ["trigger","domains"]); empty means the issue is about the resource as a whole.

type FieldRef

type FieldRef struct {
	Path   []string
	Compat []string
	// AnyOf is every location the field may be authored at, when the DSL gives
	// it more than one — a storage's size lives at object/size or
	// streaming/size depending on which block the author wrote. AnyOf[0] ==
	// Path; nil when there is only one location.
	AnyOf [][]string
}

FieldRef is where a field may be authored: its canonical path plus the legacy alias that also satisfies it.

type FieldValidator

type FieldValidator interface {
	// ValidateField runs one field's validator; nil if the field has none.
	ValidateField(group string, field []string, value any) error
	// Fields returns the authored paths of a resource group's validated fields.
	Fields(group string) [][]string
	// RequiredFields returns a resource group's required fields — asked for
	// separately because a missing field has no value for the value-driven
	// checks to run against.
	RequiredFields(group string) []RequiredField
}

FieldValidator runs a DSL's declared single-value field validators (enum, string shape, cid, fqdn, ...) for partial validation — no compile. Injected by the binding, since the session core is DSL-agnostic.

type Generator

type Generator interface {
	// GeneratedBy returns the generator id declared for a field, or "" if the
	// field is authored rather than generated.
	GeneratedBy(group string, field []string) string
	// Generate mints a value for that generator, mixing in seed for uniqueness.
	Generate(kind string, seed ...any) (string, error)
}

Generator mints values for the DSL's generated fields (a resource id), so every consumer stops carrying its own "how do I make an id".

type Kind

type Kind struct {
	Name      string `json:"name"`
	Group     string `json:"group"`
	Container bool   `json:"container"`
}

Kind is one kind of thing the DSL names. Group is the canonical key (the config directory it is authored under); Name is the singular the DSL declares for one instance, lowercased, and is accepted as an alias wherever a kind is named.

Container is NOT cosmetic, and a consumer should branch on it rather than treat every kind alike. A container's instances hold resources of their own; in this DSL that is the application, and it is deliberately not declared as a resource — it has no compiled resource type and never appears in the compiled object as one. What IS uniform is everything about editing it: its address, its document, its file, its local validation. So:

address / doc / serialize / validate  — same for every kind, container or not
"which kinds can I create as resources" — filter out Container

Branching on Container is right; branching on a kind's NAME is what this exists to remove.

type Layout

type Layout interface {
	// ContainerDoc returns the document name (e.g. "config") a container group's
	// instances keep their own fields in; "" if group is not a container.
	ContainerDoc(group string) string
	// RootDoc is the project root document name (e.g. "config").
	RootDoc() string
	// Kinds lists the DSL's resource kinds — its top-level groups.
	Kinds() []Kind
}

Layout describes the DSL's document layout so the session can map a resource address to the document that holds it. Injected by the binding: "a container's instances are directories with a config document inside" is DSL knowledge, and the session core stays layout-agnostic without it (nil Layout = every resource address is a leaf document, the pre-Layout behaviour).

type RequiredField

type RequiredField struct {
	FieldRef
	When   *FieldRef
	WhenIn []string
	// Unless inverts both the sense and the default: required UNLESS the
	// discriminator (a bool) is true, and an ABSENT discriminator means
	// required, because an unset bool is false.
	Unless bool
}

RequiredField is a field whose absence is an error, and the condition under which that applies. When is nil when the field is always required; otherwise it names the sibling to read, and WhenIn the values that make it required — a function's pubsub channel is required for a pubsub trigger and meaningless for an http one.

type Session

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

Session is an editable configuration, resident on a private in-memory filesystem. Not safe for concurrent use.

func Adopt

func Adopt(fs afero.Fs, bind Bindings) (*Session, error)

Adopt opens a session directly over fs (no copy) — for callers that already own a private filesystem (e.g. a freshly decompiled config). The session then owns fs; don't mutate it behind the session's back.

func New

func New(src afero.Fs, dir string, bind Bindings) (*Session, error)

New stages the config under dir in src into a private in-memory copy and opens an editable session over it. bind wires the DSL (see the schema package's NewSession).

func (*Session) Address

func (s *Session) Address(kind, name, app string) ([]string, error)

Address is the canonical address of one resource, by kind. This is the entry point for a caller that knows a kind only as a string: it needs no group-name table, no plural rule, and no special case for the container kind (an application is addressed like anything else — passing app for one is an error, since containers don't nest). An empty app means project scope.

func (*Session) Close

func (s *Session) Close()

Close releases the session. The in-memory filesystem is then garbage-collected.

func (*Session) Compile

Compile assembles the whole config; returns the object, deferred checks, and any error.

func (*Session) Complete

func (s *Session) Complete(res, field []string, partial string) ([]string, error)

Complete returns completion candidates for a field's value, filtered by the partial string the user has typed (case-insensitive prefix; "" = all). Fixed candidates come from the DSL (enum members, shape literals); reference fields also offer the target group's instances IN SCOPE (the resource's own app plus root/global), each prefixed. An unknown field path is an error (so a typo isn't mistaken for "no suggestions"); a known field with no candidates returns an empty slice. Returns (nil, nil) if completion isn't wired.

func (*Session) Delete

func (s *Session) Delete(res, field []string) error

Delete removes a whole resource (field == nil/empty) or a single field of it. Deleting a container instance removes its directory, and with it whatever resources it still held.

func (*Session) Exists

func (s *Session) Exists(res []string) bool

Exists reports whether a resource is already in the config — what tells an editor "this is a new resource" without consulting a file listing. It asks the resource's own group, so a container instance counts as existing as soon as its directory does, even before it has a document.

func (*Session) FS

func (s *Session) FS() afero.Fs

FS exposes the session's working filesystem (read-only intent; for compilers / inspection).

func (*Session) Fork

func (s *Session) Fork() (*Session, error)

Fork opens a copy-on-write child over this session: edits land in an overlay, leaving the parent untouched until Merge. Validate the child, then Merge to adopt its changes (or discard it). The parent must not be edited until then.

func (*Session) Generate

func (s *Session) Generate(res, field []string, seed ...any) (string, error)

Generate mints a value for one of a resource's DSL-generated fields (its id), so no consumer carries its own "how do I make an id". The resource's address is mixed in, plus any seed the caller adds; a generator is required to supply its own entropy on top (see engine.Generate), so uniqueness never depends on the seed — which is why this needs to know nothing about the DSL's fields.

func (*Session) Get

func (s *Session) Get(res, field []string) (any, error)

Get reads a field of a resource; a nil/absent value returns (nil, error).

func (*Session) Kinds

func (s *Session) Kinds() []Kind

Kinds lists the resource kinds this DSL defines. A consumer that routes on a kind STRING — a UI rendering whatever its route names — reads the vocabulary here instead of keeping its own kind table beside the schema.

func (*Session) List

func (s *Session) List(p []string) ([]string, error)

List returns the names under a folder path (resource names, app names, ...).

func (*Session) Location

func (s *Session) Location(res []string) (string, error)

Location reports where a resource's document lives — the repo-relative path Serialize returns — WITHOUT flushing, reading or rendering it. A caller that only wants the path (an inventory keyed on the git file list, a rename) pays neither the sync nor the file read, and the answer is still the DSL's rather than a path the caller guessed.

func (*Session) Merge

func (s *Session) Merge() error

Merge replays the fork's in-memory op-log onto the parent seer — no file copying, the parent stays live and consistent — then flushes the parent to its filesystem. After Merge the fork is spent.

func (*Session) Names

func (s *Session) Names(kind, app string) ([]string, error)

Names lists the instances of a kind in scope — the whole project when app is empty, one application's own otherwise. An absent directory is simply empty.

Scoping a CONTAINER kind is an error, exactly as it is in Address: containers don't nest, so "the applications inside this application" is not a question with an answer. Answering it anyway — by quietly ignoring app and returning all of them — would hide the caller's bug, and is the flattening of the container/resource distinction this API exists to avoid.

func (*Session) ResourceAt

func (s *Session) ResourceAt(filePath string) ([]string, bool)

ResourceAt maps a repo-relative YAML path to its canonical resource address; ok is false when the path is not a resource document under the DSL's layout (an unknown directory, a non-YAML file, .git, ...). The inverse of the addressing Serialize returns.

config.yaml                     -> [rootDoc]
functions/x.yaml                -> [functions, x]
applications/a/config.yaml      -> [applications, a]
applications/a/functions/x.yaml -> itself

func (*Session) Root

func (s *Session) Root() []string

Root is the address of the config's own root document — the one resource with no kind above it. A caller that wants to edit it should ask for it rather than spell the document name, which is the DSL's to choose.

func (*Session) Save

func (s *Session) Save(dst afero.Fs, dir string) error

Save flushes the session and writes its config out under dir in dst.

func (*Session) Serialize

func (s *Session) Serialize(res []string) (path string, data []byte, err error)

Serialize flushes pending edits and returns ONE resource's document: its repo-relative path and its exact YAML, comments preserved. Where the document lives is the DSL's business, so the caller never names the file — which is how a caller ends up reading a path tcc never wrote.

func (*Session) Set

func (s *Session) Set(res, field []string, value any) error

Set writes a field of a resource (raw write — no validation; see Validate).

func (*Session) SetResource

func (s *Session) SetResource(res []string, doc map[string]any) error

SetResource makes res's document equal doc, as the minimal set of field writes and deletes: maps recurse, arrays and scalars are leaves, and a key missing from doc is deleted. Untouched YAML — comments included — survives. An explicit nil writes a null; absence deletes.

The ops are applied through a fork so a diff that fails partway can't leave the resource half-written.

func (*Session) Validate

func (s *Session) Validate(ctx context.Context, opts CompileOptions) ([]interp.NextValidation, error)

Validate re-runs the compiler for diagnostics only: it returns the deferred checks and any error, discarding the artifact. Values can't be validated in isolation, so this is the honest whole-config check.

func (*Session) ValidateField

func (s *Session) ValidateField(res, field []string, value any) error

ValidateField checks one field of a resource against value WITHOUT compiling — the cheap live-edit path. It runs the DSL's single-value validator (enum, string shape, cid, fqdn, ...) AND, for a reference field, that the value names a resource that actually exists IN SCOPE (the resource's own app + root/global — the same scope the compiler resolves against, so siblings don't count). Returns nil when partial validation isn't wired or the field carries no constraint.

func (*Session) ValidateResource

func (s *Session) ValidateResource(res []string) []FieldIssue

ValidateResource checks every constrained field of one resource against its current values — single-value validators and reference existence — returning every failure ATTRIBUTED to its field (empty slice = valid). Scoped to the one file and compile-free. It does not run whole-config concerns beyond references (e.g. deferred external checks); those stay in Validate.

Attribution is per declared field ("domains", not "domains/0"); the message already names the offending value.

Jump to

Keyboard shortcuts

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