resources

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: May 29, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package resources provides the canonical desired-state persistence kernel and typed adapter boundary for extensibility resources.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound reports that no persisted resource matched the lookup.
	ErrNotFound = errors.New("resources: record not found")
	// ErrValidation reports that a resource payload or actor failed validation.
	ErrValidation = errors.New("resources: validation failed")
	// ErrInvalidScopeBinding reports that a scope and scope identifier are inconsistent.
	ErrInvalidScopeBinding = errors.New("resources: invalid scope binding")
	// ErrPermissionDenied reports that the resolved actor lacks authority for the request.
	ErrPermissionDenied = errors.New("resources: permission denied")
	// ErrDirectMutationNotAllowed reports that the actor cannot use direct CRUD paths.
	ErrDirectMutationNotAllowed = errors.New("resources: direct mutation not allowed")
	// ErrConflict reports optimistic concurrency or ownership conflicts.
	ErrConflict = errors.New("resources: conflict")
	// ErrPayloadTooLarge reports that a record or snapshot exceeded configured limits.
	ErrPayloadTooLarge = errors.New("resources: payload too large")
	// ErrRateLimited reports that the caller exceeded a configured resource rate limit.
	ErrRateLimited = errors.New("resources: rate limited")
	// ErrSessionNotActive reports that the provided session nonce is not the active nonce for the source.
	ErrSessionNotActive = errors.New("resources: session nonce not active")
	// ErrStaleSourceVersion reports that the snapshot source version is stale or out of sequence.
	ErrStaleSourceVersion = errors.New("resources: stale source version")
	// ErrCodecNotFound reports that no typed codec is registered for a resource kind.
	ErrCodecNotFound = errors.New("resources: codec not found")
	// ErrCodecTypeMismatch reports that a registered codec kind was resolved with the wrong spec type.
	ErrCodecTypeMismatch = errors.New("resources: codec type mismatch")
)

Functions

func RegisterCodec

func RegisterCodec[T any](registry *CodecRegistry, codec KindCodec[T]) error

RegisterCodec adds one typed codec keyed by its resource kind.

func SchemaStatements

func SchemaStatements() []string

SchemaStatements returns the canonical SQLite schema bootstrap for the raw resource kernel.

func ValidateAndCanonicalizeIfRegistered

func ValidateAndCanonicalizeIfRegistered(
	ctx context.Context,
	registry *CodecRegistry,
	kind ResourceKind,
	scope ResourceScope,
	raw []byte,
) ([]byte, bool, error)

ValidateAndCanonicalizeIfRegistered validates one raw spec against a registered codec and returns its canonical encoded form. When the kind has no registered codec yet, the original payload is returned unchanged and validated is false.

Types

type BundleActivationProjector

type BundleActivationProjector[A any, B any] interface {
	Build(ctx context.Context, activations []Record[A], bundles []Record[B]) (ProjectionPlan, error)
	Apply(ctx context.Context, plan ProjectionPlan) error
}

BundleActivationProjector is the explicit mixed-kind projector escape hatch for bundle activations.

type CodecRegistry

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

CodecRegistry holds explicit kind-to-codec registrations for typed adapters.

func NewCodecRegistry

func NewCodecRegistry() *CodecRegistry

NewCodecRegistry constructs an empty kind codec registry.

type Draft

type Draft[T any] struct {
	ID              string
	Scope           ResourceScope
	ExpectedVersion int64
	Spec            T
}

Draft is the typed desired-state mutation shape exposed to domain code.

type Kernel

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

Kernel implements the canonical raw desired-state persistence contract.

func NewKernel

func NewKernel(db *sql.DB, opts ...Option) (*Kernel, error)

NewKernel constructs a new raw resource persistence kernel over the supplied database.

func (*Kernel) ActivateSourceSession

func (k *Kernel) ActivateSourceSession(
	ctx context.Context,
	actor MutationActor,
	source ResourceSource,
	sessionNonce string,
) error

ActivateSourceSession registers the active nonce and resets the snapshot version counter for one source.

func (*Kernel) ApplySourceSnapshotRaw

func (k *Kernel) ApplySourceSnapshotRaw(ctx context.Context, actor MutationActor, snapshot SourceSnapshot) error

ApplySourceSnapshotRaw replaces one source's desired-state snapshot under optimistic source sequencing.

func (*Kernel) DeleteRaw

func (k *Kernel) DeleteRaw(
	ctx context.Context,
	actor MutationActor,
	kind ResourceKind,
	id string,
	expectedVersion int64,
) (err error)

DeleteRaw deletes one raw desired-state record using optimistic concurrency.

func (*Kernel) GetRaw

func (k *Kernel) GetRaw(ctx context.Context, actor MutationActor, kind ResourceKind, id string) (RawRecord, error)

GetRaw fetches one raw desired-state record under the actor's read boundary.

func (*Kernel) ListRaw

func (k *Kernel) ListRaw(ctx context.Context, actor MutationActor, filter ResourceFilter) ([]RawRecord, error)

ListRaw lists raw desired-state records under the actor's read boundary.

func (*Kernel) PutRaw

func (k *Kernel) PutRaw(ctx context.Context, actor MutationActor, draft RawDraft) (record RawRecord, err error)

PutRaw creates or updates one raw desired-state record using optimistic concurrency.

func (*Kernel) ResetSource

func (k *Kernel) ResetSource(ctx context.Context, actor MutationActor, source ResourceSource) error

ResetSource deletes all source-owned records and source state in one transaction.

type KindCodec

type KindCodec[T any] interface {
	Kind() ResourceKind
	DecodeAndValidate(ctx context.Context, scope ResourceScope, raw []byte) (T, error)
	Encode(spec T) ([]byte, error)
	MaxBytes() int
}

KindCodec owns the typed encode/decode boundary for one resource kind.

func NewJSONCodec

func NewJSONCodec[T any](kind ResourceKind, maxBytes int, validator SpecValidator[T]) (KindCodec[T], error)

NewJSONCodec builds a JSON-backed codec with a typed validation hook.

func ResolveCodec

func ResolveCodec[T any](registry *CodecRegistry, kind ResourceKind) (KindCodec[T], error)

ResolveCodec returns the typed codec registered for one resource kind.

type MutationActor

type MutationActor struct {
	Kind          MutationActorKind   `json:"kind"`
	ID            string              `json:"id"`
	SessionNonce  string              `json:"session_nonce,omitempty"`
	Owner         ResourceOwner       `json:"owner"`
	Source        ResourceSource      `json:"source"`
	MaxScope      ResourceScope       `json:"max_scope"`
	GrantedKinds  []ResourceKind      `json:"granted_kinds,omitempty"`
	GrantedScopes []ResourceScopeKind `json:"granted_scopes,omitempty"`
}

MutationActor describes the authoritative caller boundary for one mutation or read.

type MutationActorKind

type MutationActorKind string

MutationActorKind identifies the authenticated caller class.

const (
	// MutationActorKindOperator identifies an operator-authorized control-plane caller.
	MutationActorKindOperator MutationActorKind = "operator"
	// MutationActorKindDaemon identifies a daemon-internal caller.
	MutationActorKindDaemon MutationActorKind = "daemon"
	// MutationActorKindExtension identifies an extension session caller.
	MutationActorKindExtension MutationActorKind = "extension"
)

func (MutationActorKind) Normalize

func (k MutationActorKind) Normalize() MutationActorKind

Normalize returns the canonical trimmed actor kind.

func (MutationActorKind) Validate

func (k MutationActorKind) Validate(path string) error

Validate reports whether the actor kind is supported.

type Option

type Option func(*Kernel)

Option configures a Kernel instance.

func WithMaxSnapshotBytes

func WithMaxSnapshotBytes(limit int) Option

WithMaxSnapshotBytes overrides the per-snapshot byte ceiling.

func WithMaxSnapshotRecords

func WithMaxSnapshotRecords(limit int) Option

WithMaxSnapshotRecords overrides the per-snapshot record count ceiling.

func WithMaxSpecBytes

func WithMaxSpecBytes(limit int) Option

WithMaxSpecBytes overrides the per-record payload ceiling.

func WithNow

func WithNow(now func() time.Time) Option

WithNow overrides the clock used by the kernel.

type ProjectionPlan

type ProjectionPlan interface {
	Kind() ResourceKind
	Revision() int64
	OperationCount() int
}

ProjectionPlan is the generic metadata surface returned by domain projectors.

type ProjectorRegistration

type ProjectorRegistration interface {
	Kind() ResourceKind
	DependsOn() []ResourceKind
	// contains filtered or unexported methods
}

ProjectorRegistration is an opaque registration token consumed by internal projector wiring.

func NewBundleActivationProjectorRegistration

func NewBundleActivationProjectorRegistration[A any, B any](
	registry *CodecRegistry,
	projector BundleActivationProjector[A, B],
) (ProjectorRegistration, error)

NewBundleActivationProjectorRegistration adapts the explicit mixed-kind bundle activation projector seam.

func NewTypedProjectorRegistration

func NewTypedProjectorRegistration[T any](
	codec KindCodec[T],
	projector TypedProjector[T],
) (ProjectorRegistration, error)

NewTypedProjectorRegistration adapts a single-kind typed projector to the internal raw reconcile seam.

type RawDraft

type RawDraft struct {
	Kind            ResourceKind
	ID              string
	Scope           ResourceScope
	ExpectedVersion int64
	SpecJSON        []byte
}

RawDraft carries one raw desired-state mutation at the persistence boundary.

type RawRecord

type RawRecord struct {
	Kind      ResourceKind
	ID        string
	Version   int64
	Scope     ResourceScope
	Owner     ResourceOwner
	Source    ResourceSource
	SpecJSON  []byte
	CreatedAt time.Time
	UpdatedAt time.Time
}

RawRecord is the persisted raw desired-state shape.

type RawStore

type RawStore interface {
	PutRaw(ctx context.Context, actor MutationActor, draft RawDraft) (RawRecord, error)
	DeleteRaw(ctx context.Context, actor MutationActor, kind ResourceKind, id string, expectedVersion int64) error
	ApplySourceSnapshotRaw(ctx context.Context, actor MutationActor, snapshot SourceSnapshot) error
	GetRaw(ctx context.Context, actor MutationActor, kind ResourceKind, id string) (RawRecord, error)
	ListRaw(ctx context.Context, actor MutationActor, filter ResourceFilter) ([]RawRecord, error)
}

RawStore defines the raw CRUD plus snapshot boundary for desired-state persistence.

type ReconcileDriver

type ReconcileDriver interface {
	Trigger(ctx context.Context, kind ResourceKind, reason ReconcileReason) error
	RunBoot(ctx context.Context) error
	Close(ctx context.Context) error
}

ReconcileDriver drives boot-time and post-commit resource projection.

func NewReconcileDriver

func NewReconcileDriver(
	raw RawStore,
	actor MutationActor,
	registrations []ProjectorRegistration,
	opts ...ReconcileOption,
) (ReconcileDriver, error)

NewReconcileDriver constructs the topology-aware reconcile scheduler.

type ReconcileEvent

type ReconcileEvent struct {
	Type                ReconcileEventType
	Kind                ResourceKind
	Reason              ReconcileReason
	Duration            time.Duration
	Revision            int64
	Operations          int
	ConsecutiveFailures int
	DegradedUntil       time.Time
	Err                 error
}

ReconcileEvent carries one metric-friendly reconcile observation.

type ReconcileEventSink

type ReconcileEventSink interface {
	ObserveReconcileEvent(ctx context.Context, event ReconcileEvent)
}

ReconcileEventSink receives reconcile lifecycle events for metrics and observability wiring.

type ReconcileEventType

type ReconcileEventType string

ReconcileEventType identifies one emitted reconcile event.

const (
	ReconcileEventRequested ReconcileEventType = "requested"
	ReconcileEventCoalesced ReconcileEventType = "coalesced"
	ReconcileEventFailed    ReconcileEventType = "failed"
	ReconcileEventDegraded  ReconcileEventType = "degraded"
	ReconcileEventApplied   ReconcileEventType = "applied"
)

type ReconcileHealth

type ReconcileHealth struct {
	Kind                ResourceKind
	Status              ReconcileHealthStatus
	ConsecutiveFailures int
	DegradedUntil       time.Time
	LastError           error
}

ReconcileHealth captures the current health state for one projected kind.

type ReconcileHealthSink

type ReconcileHealthSink interface {
	ReportReconcileHealth(ctx context.Context, health ReconcileHealth)
}

ReconcileHealthSink receives kind-health updates from the driver.

type ReconcileHealthStatus

type ReconcileHealthStatus string

ReconcileHealthStatus captures the scheduler health state for one kind.

const (
	ReconcileHealthStatusHealthy  ReconcileHealthStatus = "healthy"
	ReconcileHealthStatusFailing  ReconcileHealthStatus = "failing"
	ReconcileHealthStatusDegraded ReconcileHealthStatus = "degraded"
)

type ReconcileOption

type ReconcileOption func(*reconcileDriver)

ReconcileOption configures a reconcile driver instance.

func WithReconcileCoalesceWindow

func WithReconcileCoalesceWindow(window time.Duration) ReconcileOption

WithReconcileCoalesceWindow overrides the per-kind rerun coalescing window.

func WithReconcileDegradedBackoff

func WithReconcileDegradedBackoff(backoff time.Duration) ReconcileOption

WithReconcileDegradedBackoff overrides the degraded-circuit backoff.

func WithReconcileEventSink

func WithReconcileEventSink(sink ReconcileEventSink) ReconcileOption

WithReconcileEventSink wires a metric-friendly event sink into the driver.

func WithReconcileFailureThreshold

func WithReconcileFailureThreshold(threshold int) ReconcileOption

WithReconcileFailureThreshold overrides the failure count that opens the degraded circuit.

func WithReconcileHealthSink

func WithReconcileHealthSink(sink ReconcileHealthSink) ReconcileOption

WithReconcileHealthSink wires a health sink into the driver.

func WithReconcileKindTimeout

func WithReconcileKindTimeout(kind ResourceKind, timeout time.Duration) ReconcileOption

WithReconcileKindTimeout overrides the timeout for one kind.

func WithReconcileKindTimeouts

func WithReconcileKindTimeouts(timeouts map[ResourceKind]time.Duration) ReconcileOption

WithReconcileKindTimeouts overrides timeouts for multiple kinds.

func WithReconcileLogger

func WithReconcileLogger(logger *slog.Logger) ReconcileOption

WithReconcileLogger overrides the driver logger.

func WithReconcileNow

func WithReconcileNow(now func() time.Time) ReconcileOption

WithReconcileNow overrides the clock used by the driver.

func WithReconcileTimeout

func WithReconcileTimeout(timeout time.Duration) ReconcileOption

WithReconcileTimeout overrides the default per-kind reconcile timeout.

type ReconcileReason

type ReconcileReason string

ReconcileReason identifies why one kind was scheduled.

const (
	ReconcileReasonBoot       ReconcileReason = "boot"
	ReconcileReasonWrite      ReconcileReason = "write"
	ReconcileReasonDependency ReconcileReason = "dependency"
)

func (ReconcileReason) Normalize

func (r ReconcileReason) Normalize() ReconcileReason

Normalize returns the canonical trimmed reason.

func (ReconcileReason) Validate

func (r ReconcileReason) Validate(path string) error

Validate reports whether the reconcile reason is supported.

type Record

type Record[T any] struct {
	Kind      ResourceKind
	ID        string
	Version   int64
	Scope     ResourceScope
	Owner     ResourceOwner
	Source    ResourceSource
	Spec      T
	CreatedAt time.Time
	UpdatedAt time.Time
}

Record is the typed desired-state record shape exposed to domain code.

type ResourceFilter

type ResourceFilter struct {
	Kind   ResourceKind
	Scope  *ResourceScope
	Owner  *ResourceOwner
	Source *ResourceSource
	Limit  int
}

ResourceFilter narrows list operations at the persistence boundary.

type ResourceKind

type ResourceKind string

ResourceKind identifies one canonical desired-state resource family.

func (ResourceKind) Normalize

func (k ResourceKind) Normalize() ResourceKind

Normalize returns the canonical trimmed resource kind.

func (ResourceKind) Validate

func (k ResourceKind) Validate(path string) error

Validate reports whether the resource kind is present.

type ResourceOwner

type ResourceOwner struct {
	Kind ResourceOwnerKind `json:"kind"`
	ID   string            `json:"id"`
}

ResourceOwner identifies the stamped owner for a record.

func (ResourceOwner) Normalize

func (o ResourceOwner) Normalize() ResourceOwner

Normalize returns a trimmed owner value.

func (ResourceOwner) Validate

func (o ResourceOwner) Validate(path string) error

Validate reports whether the owner is present.

type ResourceOwnerKind

type ResourceOwnerKind string

ResourceOwnerKind identifies the stamped ownership family for a record.

func (ResourceOwnerKind) Normalize

func (k ResourceOwnerKind) Normalize() ResourceOwnerKind

Normalize returns the canonical trimmed owner kind.

type ResourceScope

type ResourceScope struct {
	Kind ResourceScopeKind `json:"kind"`
	ID   string            `json:"id,omitempty"`
}

ResourceScope describes the persistence scope for one record.

func (ResourceScope) Normalize

func (s ResourceScope) Normalize() ResourceScope

Normalize returns a trimmed scope value.

func (ResourceScope) Validate

func (s ResourceScope) Validate(path string) error

Validate reports whether the scope binding is internally consistent.

type ResourceScopeKind

type ResourceScopeKind string

ResourceScopeKind identifies the desired-state visibility scope.

const (
	// ResourceScopeKindGlobal identifies a global-scope record.
	ResourceScopeKindGlobal ResourceScopeKind = "global"
	// ResourceScopeKindWorkspace identifies a workspace-scope record.
	ResourceScopeKindWorkspace ResourceScopeKind = "workspace"
)

func (ResourceScopeKind) Normalize

func (k ResourceScopeKind) Normalize() ResourceScopeKind

Normalize returns the canonical trimmed scope kind.

func (ResourceScopeKind) Validate

func (k ResourceScopeKind) Validate(path string) error

Validate reports whether the scope kind is supported.

type ResourceSource

type ResourceSource struct {
	Kind ResourceSourceKind `json:"kind"`
	ID   string             `json:"id"`
}

ResourceSource identifies the stamped canonical source for a record.

func (ResourceSource) Normalize

func (s ResourceSource) Normalize() ResourceSource

Normalize returns a trimmed source value.

func (ResourceSource) Validate

func (s ResourceSource) Validate(path string) error

Validate reports whether the source is present.

type ResourceSourceKind

type ResourceSourceKind string

ResourceSourceKind identifies the stamped source family for a record.

func (ResourceSourceKind) Normalize

func (k ResourceSourceKind) Normalize() ResourceSourceKind

Normalize returns the canonical trimmed source kind.

type SourceSessionManager

type SourceSessionManager interface {
	ActivateSourceSession(ctx context.Context, actor MutationActor, source ResourceSource, sessionNonce string) error
	ResetSource(ctx context.Context, actor MutationActor, source ResourceSource) error
}

SourceSessionManager manages active source-session state for snapshot publication.

type SourceSnapshot

type SourceSnapshot struct {
	SourceVersion int64
	Records       []RawDraft
}

SourceSnapshot carries the full desired-state snapshot for one source session.

type SpecValidator

type SpecValidator[T any] func(ctx context.Context, scope ResourceScope, spec T) (T, error)

SpecValidator enforces typed invariants after decoding and before persistence.

type Store

type Store[T any] interface {
	Put(ctx context.Context, actor MutationActor, draft Draft[T]) (Record[T], error)
	Delete(ctx context.Context, actor MutationActor, id string, expectedVersion int64) error
	Get(ctx context.Context, actor MutationActor, id string) (Record[T], error)
	List(ctx context.Context, actor MutationActor, filter ResourceFilter) ([]Record[T], error)
}

Store is the typed CRUD façade used by domain code.

func NewStore

func NewStore[T any](raw RawStore, codec KindCodec[T]) (Store[T], error)

NewStore constructs a typed store façade over the raw persistence kernel.

type TypedProjector

type TypedProjector[T any] interface {
	Kind() ResourceKind
	DependsOn() []ResourceKind
	Build(ctx context.Context, records []Record[T]) (ProjectionPlan, error)
	Apply(ctx context.Context, plan ProjectionPlan) error
}

TypedProjector is the standard single-kind typed projector contract.

Jump to

Keyboard shortcuts

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