module

package
v0.3.0-alpha.1 Latest Latest
Warning

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

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

Documentation

Overview

Package module defines pure Module registrations, dependency verification, typed capability-scoped services, and deterministic application lifecycle.

Stability: alpha. Consumers should pin an exact pre-v1 Modary version.

Index

Constants

View Source
const DefaultCleanupCallbackTimeout = 5 * time.Second

DefaultCleanupCallbackTimeout bounds each process-resource cleanup callback when no policy is configured.

View Source
const SchemaVersion = "modary.module/v1alpha2"

SchemaVersion is the Module manifest schema accepted by this package.

Variables

View Source
var (
	// ErrHostUnavailable reports use of a nil or zero-value Host.
	ErrHostUnavailable = errors.New("module host is unavailable")
	// ErrInvalidState identifies an operation rejected by the Host lifecycle.
	ErrInvalidState = errors.New("invalid module host state")
	// ErrInvalidScope identifies a forged, expired, or otherwise unusable Scope.
	// An expired HandlerFactory Resolver also matches it for F0 compatibility;
	// new Resolver-specific code should match ErrInvalidResolver.
	ErrInvalidScope = errors.New("invalid module installation scope")
	// ErrInvalidResolver identifies a forged, expired, retained, or otherwise
	// unusable HandlerFactory Resolver.
	ErrInvalidResolver = errors.New("invalid module service resolver")
	// ErrNilCleanup identifies an attempt to register a nil cleanup callback.
	ErrNilCleanup = errors.New("module cleanup is nil")
	// ErrCallbackPanic identifies a recovered Module lifecycle callback panic.
	ErrCallbackPanic = errors.New("module callback panicked")
	// ErrReservedServiceName identifies an attempt to publish a framework-owned
	// service name with a recreated or otherwise noncanonical key.
	ErrReservedServiceName = errors.New("reserved module service name")
)
View Source
var (
	// ErrContextRequired reports a nil lifecycle or assembled-facade context.
	ErrContextRequired = errors.New("context is required")
	// ErrApplicationUnavailable reports an assembled facade whose Host has
	// begun shutdown or is otherwise unavailable.
	ErrApplicationUnavailable = errors.New("application is unavailable")
)

Functions

func OnStop

func OnStop(scope Scope, cleanup Cleanup) error

OnStop registers process-resource cleanup for the current Module. Callback invocation starts LIFO within a Module and in reverse dependency order across Modules. When a callback times out, its goroutine may overlap later callbacks and provider cleanup; this is not a completion-order guarantee.

func Provide

func Provide[T any](scope Scope, key Key[T], value T) error

Provide publishes a typed service through an active, capability-owning Scope.

func Resolve

func Resolve[T any](resolver Resolver, key Key[T]) (T, error)

Resolve returns the typed service associated with key from a sealed Resolver. It returns ErrInvalidResolver for a forged or nil Resolver and for a retained HandlerFactory Resolver. An expired startup Scope returns ErrInvalidScope.

func ValidateManifest

func ValidateManifest(manifest Manifest) error

ValidateManifest checks identity, version, type, and capability invariants.

Types

type ActionBinding

type ActionBinding struct {
	Descriptor action.Descriptor `json:"descriptor"`
	NewHandler HandlerFactory    `json:"-"`
}

ActionBinding pairs an inspectable Action descriptor with its runtime factory.

type Assembly

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

Assembly is the safe result of finalizing a running Host. It contains the optional governed Action Runtime and optional public component facades; mutable service storage, raw Handlers, and transaction control remain Host-private.

func (Assembly) AuditReader

func (assembly Assembly) AuditReader() audit.Reader

AuditReader returns optional scope-bound audit metadata inspection.

func (Assembly) Authorizer

func (assembly Assembly) Authorizer() authz.Authorizer

Authorizer returns the optional policy evaluator installed by Modules.

func (Assembly) BrowserAuthentication

func (assembly Assembly) BrowserAuthentication() identity.BrowserAuthenticator

BrowserAuthentication returns the optional redirect-login service.

func (Assembly) Database

func (assembly Assembly) Database() database.Store

Database returns the optional ordinary business-data Store installed by Modules. It owns callback-scoped transactions but exposes no raw connection.

func (Assembly) Identities

func (assembly Assembly) Identities() identity.Resolver

Identities returns the optional public actor resolver installed by Modules.

func (Assembly) Observability

func (assembly Assembly) Observability() observe.Service

Observability returns the optional bounded telemetry facade.

func (Assembly) Passwords

func (assembly Assembly) Passwords() identity.PasswordAuthenticator

Passwords returns the optional public password verifier installed by Modules.

func (Assembly) Runtime

func (assembly Assembly) Runtime() action.Runtime

Runtime returns the governed Action execution surface, or nil when no Module declares an Action.

func (Assembly) Sessions

func (assembly Assembly) Sessions() identity.SessionManager

Sessions returns the optional public session manager installed by Modules.

func (Assembly) TaskInspector

func (assembly Assembly) TaskInspector() task.Inspector

TaskInspector returns optional read-only task metadata inspection.

func (Assembly) Tasks

func (assembly Assembly) Tasks() task.Service

Tasks returns the optional durable task service installed by Modules.

func (Assembly) Tokens

func (assembly Assembly) Tokens() identity.TokenAuthenticator

Tokens returns the optional public bearer-token authenticator installed by Modules.

type CallbackPanicError

type CallbackPanicError struct {
	Callback string
}

CallbackPanicError reports a recovered lifecycle callback panic without a process-dependent stack trace. It unwraps to ErrCallbackPanic.

func (*CallbackPanicError) Error

func (err *CallbackPanicError) Error() string

Error returns a stable diagnostic that never formats the recovered value.

func (*CallbackPanicError) Unwrap

func (err *CallbackPanicError) Unwrap() error

Unwrap returns ErrCallbackPanic, including for a typed-nil receiver.

type Capability

type Capability string

Capability identifies an open Module dependency contract. Framework capabilities use the constants below; consumers may declare additional validated values for application-specific services.

const (
	// CapabilityDatabase identifies the canonical database service.
	CapabilityDatabase Capability = "database"
	// CapabilityIdentity identifies canonical identity services.
	CapabilityIdentity Capability = "identity"
	// CapabilityPasswords identifies local password verification. It is
	// deliberately separate from identity resolution and browser sessions.
	CapabilityPasswords Capability = "identity.passwords"
	// CapabilityBearers identifies bearer-token authentication.
	CapabilityBearers Capability = "identity.bearers"
	// CapabilityBrowserAuthentication identifies redirect-based browser login.
	CapabilityBrowserAuthentication Capability = "identity.browser"
	// CapabilitySessions identifies browser-session authentication.
	CapabilitySessions Capability = "identity.sessions"
	// CapabilityAuthorization identifies the canonical authorization service.
	CapabilityAuthorization Capability = "authorization"
	// CapabilityAudit identifies the canonical audit service.
	CapabilityAudit Capability = "audit"
	// CapabilityTasks identifies the canonical durable task service.
	CapabilityTasks Capability = "tasks"
	// CapabilityTaskInspection identifies read-only operational task metadata.
	CapabilityTaskInspection Capability = "tasks.read"
	// CapabilityAuditInspection identifies read-only, scope-bound audit metadata.
	CapabilityAuditInspection Capability = "audit.read"
	// CapabilityObservability identifies explicitly selected bounded telemetry.
	CapabilityObservability Capability = "observability"
)

type Cleanup

type Cleanup func(context.Context) error

Cleanup releases one process resource registered during Module startup. It must honor context cancellation, return promptly after cancellation, and stop using dependent services before returning. A timed-out callback may continue concurrently with later cleanup callbacks, so trusted implementations must never ignore the supplied context and must synchronize any shared cleanup state.

type Definition

type Definition struct {
	Manifest   Manifest          `json:"manifest"`
	Actions    []ActionBinding   `json:"actions,omitempty"`
	Migrations []MigrationSource `json:"migrations,omitempty"`
}

Definition is the complete, side-effect-free declaration of a Module. Inspecting a Definition never starts resources, opens migration sources, or constructs Action handlers.

type Graph

type Graph struct {
	Modules  []string              `json:"modules"`
	Edges    []GraphEdge           `json:"edges"`
	Order    []string              `json:"order"`
	Provides map[Capability]string `json:"provides"`
}

Graph is the deterministic result of resolving Module capability dependencies.

func Verify

func Verify(manifests []Manifest) (Graph, error)

Verify validates manifests and returns their acyclic capability graph.

type GraphEdge

type GraphEdge struct {
	From       string     `json:"from"`
	To         string     `json:"to"`
	Capability Capability `json:"capability"`
}

GraphEdge connects a requiring Module to one capability provider.

type HandlerFactory

type HandlerFactory func(context.Context, Resolver) (action.Handler, error)

HandlerFactory constructs one governed Action handler from a sealed, read-only service view. It is invoked synchronously at most once during startup and must honor context cancellation. Resolver is valid only for the duration of the call: resolve and retain the resulting service values, never retain Resolver or use it from another goroutine. It cannot publish services or register cleanup.

type Host

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

Host validates, starts, and stops one static set of Module registrations. A Host must be constructed with NewHost or NewHostWithOptions and must not be copied; nil, zero-value, partially initialized, and copied Hosts are unavailable.

func NewHost

func NewHost() *Host

NewHost constructs a Host with the default cooperative shutdown policy.

func NewHostWithOptions

func NewHostWithOptions(options HostOptions) (*Host, error)

NewHostWithOptions validates options and constructs a Host. NewHost is the simple default for applications that do not need a custom shutdown policy.

func (*Host) Assemble

func (host *Host) Assemble() (Assembly, error)

Assemble resolves public component facades inside a running Host. Governance services and Action persistence are required only when a Module declares an Action. The first call constructs the Host-owned facade set or caches its failure; every later call while running returns the same immutable Assembly or error. All returned facades share the Host-owned lifecycle. Callers can neither substitute policy or dependencies nor obtain underlying service values through the returned Assembly.

func (*Host) Catalog

func (host *Host) Catalog() ([]action.CatalogEntry, error)

Catalog validates and returns the static read-only Action catalog.

func (*Host) Manifests

func (host *Host) Manifests() []Manifest

Manifests returns defensive copies of registered Module manifests.

func (*Host) Migrate

func (host *Host) Migrate(ctx context.Context) error

Migrate applies every selected forward migration without starting feature Modules or binding Action handlers. It starts only the database provider and its transitive dependencies, then cleans those resources before returning. Like Start, it is a one-shot Host lifecycle operation.

func (*Host) Register

func (host *Host) Register(registrations ...Registration) error

Register adds pure Module registrations before the Host starts.

func (*Host) Shutdown

func (host *Host) Shutdown(ctx context.Context) error

Shutdown starts the shared Host shutdown sequence and waits for it within ctx. The sequence revokes and drains every assembled facade before Module cleanup, and continues independently if this caller stops waiting.

func (*Host) Start

func (host *Host) Start(ctx context.Context) error

Start validates, migrates, and starts Modules in dependency order.

func (*Host) StartedModules

func (host *Host) StartedModules() []string

StartedModules returns Module IDs that completed startup in dependency order.

func (*Host) State

func (host *Host) State() State

State returns the current lifecycle state.

type HostOptions

type HostOptions struct {
	Shutdown ShutdownPolicy
	Runtime  action.RuntimePolicy
	// SkipMigrations disables the default apply-before-start behavior. It is
	// intended for serving processes paired with an explicit Migrate invocation.
	SkipMigrations bool
}

HostOptions configures lifecycle and optional governed Runtime behavior without changing Module contracts.

type Key

type Key[T any] struct {
	// contains filtered or unexported fields
}

Key binds a Go service type to the capability that owns it.

func ActionDatabase

func ActionDatabase() Key[database.Access]

ActionDatabase returns the governed-operation database Access key. It can mutate only through a transaction-bound context supplied by the Action Runtime and cannot begin a transaction.

func AuditHook

func AuditHook() Key[audit.Hook]

AuditHook returns the canonical audit Hook service key.

func AuditReader

func AuditReader() Key[audit.Reader]

AuditReader returns the canonical bounded audit Reader key.

func Authorizer

func Authorizer() Key[authz.Authorizer]

Authorizer returns the canonical authorization service key.

func BrowserAuthenticator

func BrowserAuthenticator() Key[identity.BrowserAuthenticator]

BrowserAuthenticator returns the canonical redirect-login service key.

func Database

func Database() Key[database.Store]

Database and the other standard key accessors return copies backed by a package-owned identity. Consumers can pass public keys between Modules but cannot replace the canonical key for the process. Privileged Action persistence has no public key.

func IdentityResolver

func IdentityResolver() Key[identity.Resolver]

IdentityResolver returns the canonical identity-resolver service key.

func MustKey

func MustKey[T any](name string, capability Capability) Key[T]

MustKey constructs a service key for a package-level literal and panics if that programmer-owned declaration is invalid. Runtime input should use NewKey and handle its error.

func NewKey

func NewKey[T any](name string, capability Capability) (Key[T], error)

NewKey constructs an unforgeable typed service key after validating its public name and capability. Names require at least two dot-separated segments; capabilities use canonical dot or slash-separated segments.

func Observability

func Observability() Key[observe.Service]

Observability returns the canonical bounded HTTP observability key.

func PasswordAuthenticator

func PasswordAuthenticator() Key[identity.PasswordAuthenticator]

PasswordAuthenticator returns the canonical password-verifier service key.

func SessionManager

func SessionManager() Key[identity.SessionManager]

SessionManager returns the canonical server-side session service key.

func TaskInspector

func TaskInspector() Key[task.Inspector]

TaskInspector returns the canonical bounded task Inspector key.

func Tasks

func Tasks() Key[task.Service]

Tasks returns the canonical durable task service key.

func TokenAuthenticator

func TokenAuthenticator() Key[identity.TokenAuthenticator]

TokenAuthenticator returns the canonical bearer-token authenticator key.

func (Key[T]) Capability

func (key Key[T]) Capability() Capability

Capability returns the capability governing this service key.

func (Key[T]) Name

func (key Key[T]) Name() string

Name returns the canonical namespaced service name.

type Manifest

type Manifest struct {
	SchemaVersion string       `yaml:"schemaVersion" json:"schemaVersion"`
	ID            string       `yaml:"id" json:"id"`
	Version       string       `yaml:"version" json:"version"`
	Type          ModuleType   `yaml:"type" json:"type"`
	Requires      []Capability `yaml:"requires,omitempty" json:"requires,omitempty"`
	Provides      []Capability `yaml:"provides,omitempty" json:"provides,omitempty"`
}

Manifest is the stable, serializable identity and capability contract for a Module. Definition adds the Module's Actions and migration sources.

type MigrationSource

type MigrationSource struct {
	Driver string `json:"driver"`
	Files  fs.FS  `json:"-"`
}

MigrationSource declares one driver-specific, forward-only migration set. Files is rooted at the directory containing the migration files. Open(".") must return a non-nil fs.ReadDirFile that follows the positive-size ReadDir batching and end-of-directory contract. Modary bounds directory entries, individual files, and the aggregate source before SQL validation or database effects. Definition validation only checks the declaration and never opens it.

type ModuleType

type ModuleType string

ModuleType classifies a Module's role in the application graph.

const (
	// ModuleTypeFeature identifies a Module that contributes product behavior.
	ModuleTypeFeature ModuleType = "feature"
	// ModuleTypeAdapter identifies a Module that provides infrastructure.
	ModuleTypeAdapter ModuleType = "adapter"
)

type Registration

type Registration struct {
	Definition Definition
	Start      StartFunc
}

Registration combines a pure Definition with its optional runtime startup.

func Register

func Register(manifest Manifest, start StartFunc, actions ...ActionBinding) Registration

Register constructs a Registration from a manifest, startup callback, and Action bindings.

type Resolver

type Resolver interface {
	// contains filtered or unexported methods
}

Resolver is a sealed, short-lived read-only service view. Only installation resolvers and scopes created by this package can implement it; Host deliberately cannot. A HandlerFactory may use its Resolver only synchronously during that factory call.

type Scope

type Scope interface {
	Resolver
	// contains filtered or unexported methods
}

Scope is the sealed capability-limited view supplied during Module startup. Its operations are safe for concurrent use while StartFunc is active. Every goroutine using it must finish before StartFunc returns.

type ShutdownPolicy

type ShutdownPolicy struct {
	CallbackTimeout time.Duration
}

ShutdownPolicy controls bounded process-resource cleanup. Each callback gets its own timeout. Invocation starts LIFO within a Module and in reverse dependency order across Modules, but completion is not serialized after a timeout: a noncooperative callback may overlap later callbacks and provider cleanup. Trusted callbacks must honor cancellation and stop using dependencies promptly. A zero timeout selects the safe default.

type StartFunc

type StartFunc func(context.Context, Scope) error

StartFunc initializes one Module synchronously during Host startup. It is invoked at most once, must honor context cancellation and deadlines, and must not retain Scope after returning. Scope operations are concurrency-safe while the callback is active, but the callback must join every goroutine using Scope before it returns. Services and cleanup callbacks derived during startup must themselves satisfy their documented lifetime and concurrency contracts.

type State

type State string

State identifies the current Module Host lifecycle phase.

const (
	// StateUnavailable identifies a nil or zero-value Host. Such a Host cannot
	// enter the lifecycle and must be constructed with NewHost.
	StateUnavailable State = "unavailable"
	// StateNew accepts Module registrations and has not started resources.
	StateNew State = "new"
	// StateStarting is validating or starting registered Modules.
	StateStarting State = "starting"
	// StateRunning exposes assembled component facades and, when declared,
	// permits governed Action execution.
	StateRunning State = "running"
	// StateStopping is draining execution and cleaning Module resources.
	StateStopping State = "stopping"
	// StateStopped has completed an orderly shutdown.
	StateStopped State = "stopped"
	// StateFailed records an unsuccessful startup or cleanup outcome.
	StateFailed State = "failed"
)

type StateError

type StateError struct {
	Operation string
	State     State
}

StateError reports an operation that is invalid in the observed Host state.

func (*StateError) Error

func (err *StateError) Error() string

Error describes the rejected lifecycle operation.

func (*StateError) Unwrap

func (err *StateError) Unwrap() error

Unwrap returns ErrInvalidState, including for a typed-nil receiver.

Jump to

Keyboard shortcuts

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