engine

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 14 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 engine keeps derived state consistent with a set of input rows. Inputs are registered kinds loaded through a Source and changed by Notify, Apply and Delete; derived objects are built by controllers, one per derived kind, each reconciling one output id at a time from current state. Every read a reconcile makes through its Txn is recorded as a dependency edge, so the graph that decides what to rebuild is never declared by hand. A drained batch of changes runs the controllers to a fixpoint and publishes one immutable View; diagnostics (Issue) are part of that derived state.

Out of scope: storage and change feeds (callers implement Source and call Notify), the request path (callers read their own structs, stored from the OnPublish hook, not the View), metrics types (Hooks report numbers), and the contents of runtime cells (package cell). Imports only the standard library and package cell.

Index

Constants

This section is empty.

Variables

View Source
var ErrRetry = errors.New("engine: retry")

ErrRetry marks a transient reconcile failure: retried without backoff on the next drain or after the retry base (Debounce, else 100 ms), whichever comes first.

Functions

func All

func All[T any, R *Txn | *View](r R) iter.Seq[*T]

All iterates every object of kind T in id order, recording Any on a Txn.

func Apply

func Apply[T any](e *Engine, row *T) error

Apply writes an input row the caller already holds and drains at once, so a write is visible on the writing process before its notification returns. Its hooks have run when it returns, unless another goroutine was already running hooks (a hook calling Apply, or the drain loop); that goroutine runs them next.

func ByNameOf

func ByNameOf[T any, R *Txn | *View](r R, name string) *T

ByNameOf reads by slug, recording ByName on a Txn. nil when absent or when two rows share the name.

func Delete

func Delete(e *Engine, ref Ref) error

Delete removes an input row and drains at once; Apply's counterpart.

func Drop

func Drop(tx *Txn)

Drop stages the absence of the output.

func Get

func Get[T any, R *Txn | *View](r R, id string) *T

Get reads one object of kind T by id: from a Txn's working state (recording ByID) or from a View. R is inferred from the first argument. nil when absent.

func Members

func Members[T any](tx *Txn) []*T

Members returns the rows of kind T whose Watch key function maps to the output being reconciled, sorted by id. It records nothing: membership changes dirty the output by themselves.

func Put

func Put[T any](tx *Txn, out *T)

Put stages the output of this reconcile; a nil out is a Drop. Exactly one Put or Drop per reconcile; a second call panics.

func RegisterKind

func RegisterKind[T any](e *Engine, spec KindSpec[T])

RegisterKind declares a kind before Load. Panics after Load: kinds are fixed for the engine's life. One Go type maps to exactly one kind.

func Watch

func Watch[T any](c *Controller, keys func(row *T) []string)

Watch maps a row of kind T to the output ids it belongs to. The engine keeps the reverse index and dirties an output when its membership changes; an output with no members that drops is forgotten.

Types

type Controller

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

Controller is one derived kind plus the function that builds one of its objects from current state.

func NewController

func NewController(name string, produces Kind, reconcile func(tx *Txn, id string) error) *Controller

NewController declares a controller producing kind produces. reconcile builds output id from current state and either Puts it, Drops it, or returns an error. Controllers run in registration order within a round; register parents before children.

type Edge

type Edge struct {
	Kind Kind
	ID   string // ByID
	Name string // ByName
	// contains filtered or unexported fields
}

Edge is a dependency target in one of three forms: by id, by name, or any row of a kind (for patterns and wildcards that cannot name a row).

func Any

func Any(k Kind) Edge

Any is an edge to every object of kind k.

func ByID

func ByID(k Kind, id string) Edge

ByID is an edge to one object by id.

func ByName

func ByName(k Kind, name string) Edge

ByName is an edge to whichever object of kind k holds name. Any change to that object dirties the reader, not only a rename.

type Engine

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

Engine owns the object maps, the graph, the controllers and the publish loop. One per process.

func New

func New(o Options) *Engine

New constructs an engine; RegisterKind and Register run before Load.

func (*Engine) Close

func (e *Engine) Close() error

Close drains the queue once and stops. No publish and no hook call after it returns.

func (*Engine) Load

func (e *Engine) Load(ctx context.Context) error

Load lists every input kind through its Source, runs every controller to fixpoint and publishes generation 1. Boot and nothing else; the hooks for generation 1 have run when it returns.

func (*Engine) Notify

func (e *Engine) Notify(ev Event)

Notify queues an event. Never blocks: the queue coalesces by Ref, keeping the latest op and the highest version (0, which forces a fetch, wins).

func (*Engine) Register

func (e *Engine) Register(c *Controller)

Register adds the controller; panics after Load.

func (*Engine) Resync

func (e *Engine) Resync(ctx context.Context) error

Resync lists every input kind, applies the differences against the held versions (or values, when a Version is 0) and publishes only when something changed.

func (*Engine) View

func (e *Engine) View() *View

View returns the current published view; cheap and lock-free.

type Event

type Event struct {
	Ref     Ref
	Op      Op
	Version int64
}

Event is one change notification, decoded by the caller. Version 0 forces a fetch; a non-zero Version at or below the held one is dropped unfetched.

type Generation

type Generation uint64

Generation numbers each published View; strictly increasing, 0 is the pre-boot empty view.

type Hooks

type Hooks struct {
	OnPublish        func(v *View, s PublishStats)
	OnReconcileError func(controller string, out Ref, err error)
	OnBatchAbandoned func(gen Generation, rounds int)
	OnResync         func(changed int, dur time.Duration)
}

Hooks are the observation points; every field is optional, so a caller sets one without implementing the rest.

Hooks run after the engine lock is released, one call at a time and in the order their events happened (OnPublish in generation order), so a hook may call Apply, Delete or Resync; it must not call Close.

type Issue

type Issue struct {
	Severity Severity
	Code     string
	Source   Ref
	Target   Ref
	Field    string
	Message  string
}

Issue is one diagnostic attached to an object. Code is a stable snake_case id the UI keys on; Field is the spec path; Target is what Source pointed at when it broke.

type Kind

type Kind string

Kind names a class of objects. A plain string keeps Ref and Edge comparable values instead of type parameters.

type KindSpec

type KindSpec[T any] struct {
	Kind Kind
	// Meta is required for input kinds. For derived kinds it is optional and
	// only supplies Name and Version; the id is always the output id.
	Meta   func(*T) Meta
	Source Source[T] // nil for derived kinds (only a controller writes them)
	// Shards is the number of copy-on-write partitions of this kind's map, so
	// a write to a large kind copies one partition; 1 when unset.
	Shards int
}

KindSpec registers one kind as a value rather than a method chain.

type Meta

type Meta struct {
	ID string
	// Name is the slug; empty for kinds without one. A name held by two rows
	// of one kind resolves to neither and raises duplicate_name on both.
	Name string
	// Version is the row's resource version. 0 means unknown: always fetch,
	// never deduplicate.
	Version int64
}

Meta is what the engine needs to know about any object, so it never reads a domain type's own metadata.

type Op

type Op uint8

Op is what happened to an input row.

const (
	OpUpsert Op = iota + 1
	OpDelete
)

type Options

type Options struct {
	// Debounce is how long Notify events collect before one drain. 0 drains
	// on every event.
	Debounce time.Duration
	// MaxRounds bounds the fixpoint loop per drained batch (default 8); past
	// it the batch publishes, the outputs still dirty keep their last output
	// with an issue, and a Resync is scheduled to reconcile them again.
	MaxRounds int
	Hooks     Hooks
	Cells     cell.Linker // the cell registry; nil disables Txn.Link
}

Options holds the knobs the composition root sets.

type PublishStats

type PublishStats struct {
	Gen        Generation
	Inputs     int // input rows applied
	Dirtied    int // derived objects marked dirty
	Reconciled int // reconcile calls made
	Rounds     int
	Duration   time.Duration
}

PublishStats describes one batch, so a metrics hook has numbers without walking the view.

type Ref

type Ref struct {
	Kind Kind
	ID   string
}

Ref identifies one object: its kind and id. Every graph edge, issue and dirty entry needs one comparable identity.

type Severity

type Severity uint8

Severity ranks an Issue.

const (
	SeverityError   Severity = iota + 1 // the object cannot serve
	SeverityWarning                     // it serves, something is probably wrong
)

type Source

type Source[T any] interface {
	List(ctx context.Context) ([]*T, error)
	// Get returns (nil, nil) for a missing row, which the engine applies as a
	// delete.
	Get(ctx context.Context, id string) (*T, error)
}

Source lists and fetches one input kind from its backing store, so the engine owns the load and resync loops without importing storage.

type Txn

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

Txn is the write-side transaction one reconcile runs in. Reads record edges; writes stage into the batch; nothing is visible until publish.

func (*Txn) Issue

func (tx *Txn) Issue(i Issue)

Issue attaches a diagnostic to this reconcile; the set replaces the previous reconcile's set for this output. Source defaults to Out().

func (tx *Txn) Link(k cell.Key)

Link records that the output uses a cell, so the registry keeps it alive while this output is published. A no-op when the engine has no registry.

func (*Txn) Out

func (tx *Txn) Out() Ref

Out is the Ref being reconciled, for issue attribution and cell keys.

type View

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

View is one published generation: every object, the recorded graph and the issues. Immutable once published; object pointers taken from any view stay valid forever.

func (*View) AllIssues

func (v *View) AllIssues() []Issue

AllIssues returns every issue, ordered by the Ref it is attached to, then severity and code.

func (*View) Gen

func (v *View) Gen() Generation

Gen is the generation this view was published as.

func (*View) Issues

func (v *View) Issues(ref Ref) []Issue

Issues returns the issues attached to ref by any controller or the engine, sorted by severity then code.

func (*View) Referrers

func (v *View) Referrers(e Edge) []Ref

Referrers returns every object whose last reconcile recorded e, sorted. An Any edge answers nothing useful and returns nil.

Directories

Path Synopsis
Package cell owns long-lived runtime state (counters, breaker copies, rotation state, shared caches) keyed by stable ids, so the state outlives the published generations that point at it.
Package cell owns long-lived runtime state (counters, breaker copies, rotation state, shared caches) keyed by stable ids, so the state outlives the published generations that point at it.
internal
celllink
Package celllink carries the link changes of a published generation from package engine to package cell.
Package celllink carries the link changes of a published generation from package engine to package cell.

Jump to

Keyboard shortcuts

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