bindly

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 29 Imported by: 1 module, 15 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.

README

Bindly

Bindly is a provider-driven dependency injector for Go structs. It compiles binding metadata once, then resolves values from an invocation scope without capturing request data in the compiled plan.

Core Model

Binder is the public binding interface implemented by *Injector:

type Binder interface {
    Bind(context.Context, any, ...BindOption) error
}

Consumers may accept bindly.Binder without depending on injector construction. Existing calls without options keep their behavior; compiled plans and other native options remain available. Specialized scope adapters may restrict options to preserve their own source or plan authority and must report unsupported options.

  • An application Injector owns provider definitions, transformers, type metadata, and generic resources.
  • CompilePlan converts component metadata into an immutable reusable plan.
  • ForScope creates an invocation injector. Local providers shadow parent providers by kind and the scope owns its value cache.
  • Bind resolves each binding from the active scope, transforms and converts the value, and writes it to the typed target.
root, err := bindly.NewInjector(bindly.WithProviders(appProviders...))
if err != nil {
    return err
}

plan, err := root.CompilePlan(reflect.TypeOf(Input{}),
    bindly.BindingSpec{
        Path:     "AccountID",
        Name:     "accountID",
        Location: state.Location{Kind: request.QueryKind, In: "accountId"},
    },
)
if err != nil {
    return err
}

requestScope, err := request.New(req,
    request.WithPathParams(pathParams),
)
if err != nil {
    return err
}
defer requestScope.Close()

scope, err := root.ForScope(requestScope.Providers()...)
if err != nil {
    return err
}

input := &Input{}
if err := scope.Bind(ctx, input, bindly.WithPlan(plan)); err != nil {
    return err
}

Plans contain field selectors and metadata only. Provider lookup always occurs against the injector performing Bind, so one plan can safely serve sibling request scopes.

Injector.HasProvider(kind) checks whether that exact provider kind is registered in the injector or its lookup ancestry, including registry parents. It does not execute providers or resolve values. A nil injector returns false. Registration visibility does not establish binding authority or reserve the registration against later changes.

Bind Tags

For package-defined Go shapes, Bindly can compile tags directly:

type Input struct {
    AccountID int           `bind:"accountID,kind=query,in=accountId,required"`
    IDs       []int         `bind:"ids,kind=query,in=id"`
    Request   *http.Request `bind:"request,kind=http_request"`
}

The bind tag carries the original Datly parameter-tag surface: positional or explicit name, kind, in, when, scope, errorCode, errorMessage, dataType, cardinality, with, required, cacheable, async, uri, resource, and value. The complete reflect.StructTag remains available as binding metadata, so independent tags such as codec, predicate, description, and format are not flattened into Bindly-specific fields.

Datly-generated or DQL-defined components should use BindingSpec and CompilePlan; they should not synthesize tags and parse them again.

Request Providers

provider/request groups HTTP-related providers as one package while keeping their data points independent:

  • http_request
  • query
  • path
  • header
  • cookie
  • form
  • body

Query, header, form, and multipart providers use the destination type: scalar destinations receive the first repeated value, while slice and array destinations receive every value. Untyped provider lookup also preserves every repeated value. Form and body can both resolve typed multipart values and file headers, matching Datly parameter semantics. The body provider also supports JSON, named JSON fields, raw bytes or strings, and custom media-type decoders. Custom decoders can be registered with request.WithDecoder. Configure the multipart memory threshold with request.WithMaxMultipartMemory. Scope.Close removes temporary files owned by the cloned multipart request; header overlays share that cleanup ownership.

A single empty query value is present by default. Opt into treating it as absent with request.WithIgnoreEmptyQueryParameters(true) or the invocation-local request.WithQueryPolicy; repeated values retain their presence.

For direct body access, body.New accepts raw bytes, a content type and a binding-name-to-JSON-field alias map. Value accepts the invocation context, target type and field name; an empty name selects the whole body:

source, err := body.New(raw, "application/json", map[string]string{
    "payload": "data",
})
if err != nil {
    return err
}
value, found, err := source.Value(ctx, reflect.TypeFor[Payload](), "payload")

JSON decoding derives Has markers from supplied fields, including explicit null, zero and false. body.WithExactFieldNames opts into exact named-field lookup. body.WithDecoders configures custom media-type decoding.

request.NewDeferred keeps these providers available while reading body bytes only when body, form, source capture, or full raw-request access is requested. Metadata lookup does not read bytes. Body and form share one request snapshot; read and initialization errors are retained, and header overlays share cleanup. The existing decoder, multipart-memory, and source-overlay options also apply. request.New retains its eager construction. body.NewDeferred defers an initialized body source through an invocation-owned loader.

Typed JSON body decoding excludes selected fields tagged internal:"true", including fields promoted through an internal embedding, before decoding. Public field resolution follows native JSON dominance and case matching; public numbers, duplicate member order, aliases, and custom scalar decoding retain their JSON behavior. Presence markers are derived from authorized keys. Raw JSON capture remains byte preserving. Public opaque custom JSON contracts retain ownership of their representation.

A binding can opt into allocating an empty record for a supplied whole JSON null with BindingSpec.BodyNullPolicy = "empty-record", or the tag bodyNullPolicy=empty-record. The target must be a direct pointer to a struct at body/, without source-type adaptations or transformers. Missing bodies still fail required binding. The allocated record is fresh, its body is present, and its field markers are all false. Invalid policies and targets fail plan compilation; other bindings retain their null behavior.

Replay uses the receiving binding's null policy and keeps original raw null through capture and dependency projection. Trusted typed capture verifies its local JSON roundtrip with full value and presence equality; serialized replay bytes subsequently use public body decoding and do not carry that trust.

Cache Semantics

Each Bind owns an invocation cache keyed by provider owner, location and target type. A binding-level cacheable value overrides the provider's locator.CachePolicy; providers without a policy default to non-cacheable.

The injector also owns a value cache for cacheable, source-independent bindings using an explicit plan. ForScope creates a separate value cache. Default persistent reuse is disabled when binding from a source object or observing binding metadata. WithValueCache explicitly supplies a shared cache; nonempty WithSource objects qualify entries by source identity. Cacheable resolutions use per-key locking and recheck the cache after acquiring the lock. Child providers are checked before cached parent values.

Explicit persistent caches store values, not binding metadata. Applications must manage their lifetime and invalidate them when the underlying provider changes. ValueCache.Save and Load support filesystem snapshots; this is not an HTTP response cache. Raw replay capture bypasses decoded persistent values.

Binding Options and Compatibility

WithPlan selects a compiled contract, and WithSource supplies state for state-dependent providers. OnlyKinds and SkipKinds restrict the bindings resolved by a call. Required bindings reject missing or null values by default; AllowMissingRequired explicitly relaxes that policy.

The existing WithState[T] / Inject entry point uses the same compiled-plan execution path. WithDynamicState supports runtime-owned targets through Inject, Assign and Value. Its WithCache, WithAllowedKinds, WithDelayedLocator and WithMissingPolicy options remain available.

locator.ComposeProviders resolves named layers in declared order. A found value, including null, an error, or an authoritative missing value stops fallback. Layer names must be nonempty and unique; every layer must supply the same kind. The composed priority is the maximum layer priority, and default caching requires every layer to permit it.

Trusted resolved input

WithResolvedInput(plan, input, paths...) imports selected canonical destination values for one binding target. Supply the identical compiled plan through WithPlan and a nonnil input of the exact target pointer type. This is trusted internal input, not a transport replay or provider-cache override. The selected ordinary data graph is cloned; callers must not mutate it during capture. Selected unscoped, cacheable component pointer bindings retain their exact reference, including private data. Their caller owns validation of component identity and capability admission. Caller and receiver must treat these borrowed outputs as read-only throughout the invocation, with no concurrent mutation. This does not add a provider override or shared cache. Unknown or duplicate paths, incompatible types and replay combinations fail before binding.

Normal ordering and conditions still run. Selected values bypass provider lookup, conversion, defaults and transforms, then follow ordinary validation, assignment, presence-marker and observer processing. Unselected fields bind normally. Seeded observer metadata is nil; this option creates no authorization provenance.

With dependency-mode resolution groups, selected non-group values bind before any group opens, using the normal conditions, validation, presence markers and observation. A declared barrier already bound from a seed is not assigned again. Unselected bindings, including dependent param loaders, still resolve normally. The selected paths and their marker writes must not overlap any group member or its markers, including ancestor/descendant paths and promoted-field aliases. Validation rejects overlap before cloning or starting providers, even for nil or zero values. Legacy groups (including mixed legacy/dependency plans) still reject resolved input. Authentication and trusted-seed admission remain the caller's responsibility; a supplied value does not establish verified authorization.

The clone retains shared references within the selected data graph while detaching supported mutable data from the caller. Unsupported mutable values fail capture. Presence selects explicitly supplied zero values as well as nonzero values; it does not infer authorization or turn the seed into a shared cache. For example, a canonical Auth component binding in WithResolvedInput(plan, input, "Auth", "Rows") retains input.Auth while detaching ordinary Rows. An absent component path still resolves normally. See component reference tests for read-only sharing, and resolved-input tests for ordering, isolation and concurrent binding examples.

Projection, Metadata and Replay

Plan.Projection exposes selected bindings under their canonical names or explicit aliases without creating a second binding pipeline. WithBindingObserver receives binding events, including metadata supplied by metadata-aware locators.

Plan.Replay selects bindings for a replay contract. Capture snapshots typed values, DecodeJSON accepts replay JSON, and CaptureSources snapshots selected provider sources before transformation, defaults or dependencies run. Providers implementing locator.SourceCapturer can retain raw JSON presence and numbers. ReplayPlan.Prepare declares fresh prerequisite bindings; WithReplay applies the replay through the normal binding and authorization path. See replay tests and source capture tests for complete examples.

Embedded Resources

Bindly accepts any standard fs.FS, including go:embed:

//go:embed sql/*.sql
var assets embed.FS

injector, err := bindly.NewInjector(
    bindly.WithResourceFS("component", assets),
)
sqlText, err := injector.ReadResource("component:sql/find.sql")
embeddedFS, ok := injector.ResourceFS("component")

ResourceFS returns the original fs.FS, so an embed.FS remains available to SQL URI, StructQL, or other resource-aware compilers. Transformers receive the same generic resource store. Bindly does not infer resource type from paths or parse resources with regular-expression heuristics.

injector.Resources() exposes that same store for registration-time compilers. Passing it as an fs.FS lets SQL URI and StructQL owners read package assets without copying them into a parallel map or resource cache. Only an explicitly registered empty namespace is a default; named namespaces never become an order-dependent fallback for unqualified references.

Store.WithDefault(sourceFS) creates a view with its own default filesystem while sharing named registrations with the original store. Pass that view to WithResources when compiling a component against its package-local assets. Changing one view's default does not change another view or the root store. Lookup and the compatibility Filesystem method expose registered filesystems; resource paths must be valid fs.FS paths.

Concurrency

Compiled plans, injector metadata caches, registries, resource stores, and value caches are safe for concurrent reads and binding after bootstrap. Invocation scopes should not be shared across unrelated requests. Provider implementations remain responsible for the concurrency safety of the data they expose. A Replay contains invocation values and must not be shared across requests; Plan, Projection and ReplayPlan retain contract metadata.

Explicit Dependency Groups

Groups require an application-supplied ResolutionGroupController. Authoring metadata alone never authorizes execution. Existing groups (empty mode) retain their concurrent-attempt, barrier, and completion-order error behavior.

Opt into bounded dependency scheduling with resolutionMode=dependencies:

type Input struct {
    Audiences *AudienceOutput `bind:"kind=component,in=audiences,resolutionGroup=subject,resolutionMode=dependencies"`
    Creatives *CreativeOutput `bind:"kind=component,in=creatives,resolutionGroup=subject,resolutionMode=dependencies"`
}

err := injector.Bind(ctx, input,
    bindly.WithSource(input),
    bindly.WithResolutionGroupController(controller),
    bindly.WithResolutionGroupConcurrency(2),
)

The equivalent programmatic metadata uses ResolutionGroupSpec.Mode = ResolutionGroupDependencies. Optional resolutionAfter=Jwt|Data barriers must bind successfully before the group opens. dependsOn=OtherMember waits for that member's complete provider result and publication. Unknown prerequisites, cycles, overlapping member paths, and inconsistent group settings fail plan compilation. Declare any input required by a group as a barrier or member prerequisite; ungrouped bindings retain sequential execution and are not automatically made prerequisites. Separate groups run sequentially.

Dependency groups default to four runnable members. They admit work before creating worker goroutines, isolate resolver maps and destination scratch records, and join all started work before closing the controller. Errors are reported in member declaration order; controller observations still describe actual completion. Optional missing values remain missing, zero values remain present, and optional provider errors remain errors. Failed prerequisites skip their dependents, with an unattempted ResolutionOutcome carrying ResolutionPrerequisiteError instead of a fabricated read failure. Cancellation skips pending work and joins started work. Controllers must honor cancellation and observe skipped outcomes for cleanup.

Nested dependency groups inherit the invocation budget. The application must identify waits explicitly rather than holding a runnable permit across descendants:

err := bindly.SuspendResolutionGroup(ctx, func(waitCtx context.Context) error {
    return childInjector.Bind(waitCtx, child,
        bindly.WithSource(child),
        bindly.WithResolutionGroupController(childController),
    )
})

The waiting ancestor retains its call stack but no runnable permit. Pending work does not consume a goroutine. A nested group without suspension fails rather than deadlocking. A nested limit cannot override the inherited budget. Use RunResolutionGroupPhase(waitCtx, execute) for runnable sequential descendant phases, including reader execution and hooks. Suspend only dependency waits, never SQL execution or arbitrary work. Propagate suspension errors immediately. Do not reuse a member context concurrently; pass the callback's context to descendants.

Destination pointer ancestors use copy-on-write so publication cannot change retained peer snapshots; actual provider result identities are preserved. Source snapshots do not deep-copy completed outputs; providers must treat their values as read-only. Controller and provider state must also be invocation-local or concurrency-safe. Bindly does not classify HTTP methods, grant read-only authority, suppress authorization/transaction failures, or manage transactions. The application must enforce those policies throughout nested calls and finalizers and return a provider result only after its lifecycle is complete.

Verification

The module requires Go 1.25 or newer. Run against this module's dependencies:

GOWORK=off GO111MODULE=on go test -mod=readonly ./...
GOWORK=off GO111MODULE=on go test -mod=readonly -race ./...
GOWORK=off GO111MODULE=on go vet -mod=readonly ./...

Documentation

Overview

Example (Inject)
package main

import (
	"context"
	"fmt"
	"github.com/viant/bindly"
	"github.com/viant/bindly/locator/buildin"
	"github.com/viant/structology"
)

type AppConfig struct {
	ServerPort int
	BaseURL    string
}

// Logger is a simple logging service
type Logger interface {
	Log(message string)
}

// SimpleLogger implements Logger
type SimpleLogger struct{}

func (l *SimpleLogger) Log(message string) {
	fmt.Println(message)
}

type DependencySetup struct {
	Config     *AppConfig
	Settings   map[string]interface{}
	Interfaces map[string]interface{}
}

// Service uses the configuration
type Service struct {
	Debug      bool   `bind:"kind=setting,in=debug"`
	ServerPort int    `bind:"in=Config.ServerPort"` //state kind is a default kind
	Logger     Logger //interface bind by defaul to interface kind
}

func main() {

	var iLogger Logger
	appLoger := &SimpleLogger{}

	dependencies := &DependencySetup{
		Config: &AppConfig{
			ServerPort: 8080,
			BaseURL:    "http://localhost:8080",
		},

		Interfaces: map[string]interface{}{
			structology.InterfaceTypeOf(&iLogger).String(): appLoger,
		},
		Settings: map[string]interface{}{
			"debug": true,
			"port":  8080,
		},
	}

	var opts = append([]bindly.InjectorOption{}, bindly.WithProviders(
		buildin.Struct("state", "", 1), //empty kind
		buildin.Map("setting", "Settings", 1),
		buildin.Map("interface", "Interfaces", 1)))

	injector, err := bindly.NewInjector(opts...)
	if err != nil {
		fmt.Println(err)
		return
	}
	service := &Service{}
	err = bindly.WithState[Service](injector, dependencies).Inject(context.Background(), service)

	fmt.Println(service, err)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func RunResolutionGroupPhase added in v0.4.1

func RunResolutionGroupPhase(ctx context.Context, execute func(context.Context) error) error

RunResolutionGroupPhase executes runnable work under the inherited dependency group's limit. Use it for sequential descendant work inside a suspended wait; explicitly grouped descendants acquire their own permits automatically. Existing member phases reuse their permit. No scheduler means ordinary execution.

func SuspendResolutionGroup added in v0.4.1

func SuspendResolutionGroup(ctx context.Context, wait func(context.Context) error) error

SuspendResolutionGroup releases the current runnable permit while wait waits for descendants. Nested binds inherit the same scheduler, but not the parent's permit. On return the permit is reacquired before caller execution resumes.

Call only around dependency waits, not database work or arbitrary execution. A member context must not be shared by concurrently executing branches. A canceled wait returns without reacquiring; the caller must propagate the error. Outside a dependency-group member this simply calls wait.

Types

type BindOption added in v0.2.0

type BindOption func(*bindOptions)

func AllowMissingRequired added in v0.3.0

func AllowMissingRequired() BindOption

func OnlyKinds added in v0.3.0

func OnlyKinds(kinds ...string) BindOption

func SkipKinds added in v0.3.0

func SkipKinds(kinds ...string) BindOption

func WithBindingObserver added in v0.2.0

func WithBindingObserver(observer BindingObserver) BindOption

func WithPlan added in v0.2.0

func WithPlan(plan *Plan) BindOption

func WithReplay added in v0.2.0

func WithReplay(binding ReplayBinding) BindOption

func WithResolutionGroupConcurrency added in v0.4.1

func WithResolutionGroupConcurrency(limit int) BindOption

WithResolutionGroupConcurrency bounds runnable dependency-group members across nested binds in one invocation. Zero uses four; negative values are invalid. It does not change legacy concurrent groups or ordinary sequential binding.

func WithResolutionGroupController added in v0.4.1

func WithResolutionGroupController(controller ResolutionGroupController) BindOption

func WithResolvedInput added in v0.4.1

func WithResolvedInput(plan *Plan, detachedInput any, paths ...string) BindOption

WithResolvedInput imports explicitly selected, already-transformed canonical destination values for this Bind target only. It is trusted internal input, not transport replay or provider-cache authority. Callers own capture of detachedInput and must not mutate it concurrently with Bind. Canonical, cacheable unscoped component pointers are borrowed by identity, read-only throughout the invocation; ordinary selected data remains detached. WithPlan must supply the identical plan; replay cannot be combined with this option. Normal conditions, validation, assignment and observation still run. Dependency-mode groups allow only paths disjoint from every group member and its presence marker. Those selected values bind before any group is opened.

func WithSource added in v0.2.0

func WithSource(source any) BindOption

func WithValueCache added in v0.3.0

func WithValueCache(cache *ValueCache) BindOption

type Binder added in v0.5.0

type Binder interface {
	Bind(ctx context.Context, target any, options ...BindOption) error
}

Binder binds a typed target using the implementation's provider scope. Calls without options retain the implementation's normal binding behavior. Specialized binders may restrict options to preserve their source, plan or invocation authority; unsupported options must return an error, not be ignored.

type Binding

type Binding struct {

	// Metadata fields (from bind tag)
	Name         string
	Scope        string
	When         string
	ErrorCode    int
	ErrorMessage string
	DataType     string
	Cardinality  string
	With         string
	URI          string
	ResourceRef  string
	Required     *bool
	Cacheable    *bool
	Async        bool
	Tags         tags.Values
	DefaultValue interface{}
	Tag          reflect.StructTag
	// Extension holds optional immutable metadata supplied by a plan compiler.
	Extension interface{}

	XformConfig tags.Values
	// contains filtered or unexported fields
}

Binding represents a single field binding, including metadata parsed from struct tags, resource reference, and runtime resolver and transformer settings.

func (*Binding) Default added in v0.3.0

func (b *Binding) Default() interface{}

Default returns default value associated with this binding.

func (*Binding) In added in v0.3.0

func (b *Binding) In() string

In returns binding location in-path.

func (*Binding) IsCacheable added in v0.3.0

func (b *Binding) IsCacheable() bool

IsCacheable reports whether binding result should be cached.

func (*Binding) IsRequired added in v0.3.0

func (b *Binding) IsRequired() bool

IsRequired reports whether binding is required.

func (*Binding) Kind added in v0.3.0

func (b *Binding) Kind() string

Kind returns binding location kind.

func (*Binding) Location added in v0.3.0

func (b *Binding) Location() *state.Location

Location returns underlying state.Location.

func (*Binding) NameTag added in v0.3.0

func (b *Binding) NameTag() string

NameTag returns logical parameter name.

func (*Binding) ScopeTag added in v0.3.0

func (b *Binding) ScopeTag() string

ScopeTag returns binding scope.

type BindingCache

type BindingCache struct {
	internal.Map[reflect.Type, *BindingType]
}

func NewBindingCache

func NewBindingCache() *BindingCache

type BindingContext

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

BindingContext represents binding context with state

func WithState

func WithState[T any](binder *Injector, state interface{}, opt ...BindingOption[T]) *BindingContext[T]

func (*BindingContext[T]) Bind added in v0.3.0

func (c *BindingContext[T]) Bind(ctx context.Context) error

func (*BindingContext[T]) BindTarget added in v0.3.0

func (c *BindingContext[T]) BindTarget(ctx context.Context, target any) error

func (*BindingContext[T]) Inject

func (c *BindingContext[T]) Inject(ctx context.Context, target *T) error

Inject uses the same immutable-plan invocation path as Injector.Bind.

func (*BindingContext[T]) Value

func (c *BindingContext[T]) Value(ctx context.Context, location *state.Location) (any, bool, error)

type BindingError added in v0.2.0

type BindingError struct {
	Path    string
	Name    string
	Kind    string
	In      string
	Code    int
	Message string
	Cause   error
	Err     error
}

func (*BindingError) Error added in v0.2.0

func (e *BindingError) Error() string

func (*BindingError) RequiredAbsenceMessage added in v0.4.1

func (e *BindingError) RequiredAbsenceMessage() (string, bool)

RequiredAbsenceMessage returns safe text only for this binding's own typed absence event. It never traverses dependency failures or formats private causes. Callers must preserve authored Message precedence.

func (*BindingError) StatusCode added in v0.2.0

func (e *BindingError) StatusCode() int

func (*BindingError) Unwrap added in v0.2.0

func (e *BindingError) Unwrap() error

type BindingEvent added in v0.2.0

type BindingEvent struct {
	Target   any
	Path     string
	Location state.Location
	Value    any
	Metadata any
}

BindingEvent describes one successfully assigned target field. Target is the actual Bind/BindTarget destination, not necessarily the initial input. Path is that target's full planned field selector. Value is the assigned value; Metadata is nil when its provenance is unknown or an opaque conversion ran. Later bindings served by the explicit persistent value cache also have nil metadata: opaque evidence is never persisted or reconstructed from a value. No values or metadata are logged automatically.

type BindingObserver added in v0.2.0

type BindingObserver func(context.Context, BindingEvent) error

BindingObserver runs after field and presence-marker assignment. An error aborts binding through BindingError; already applied assignments are not rolled back. Observers own any longer-lived recording or publication policy.

type BindingOption

type BindingOption[T any] func(ctx *BindingContext[T])

func WithAllowedKinds added in v0.3.0

func WithAllowedKinds[T any](kinds ...string) BindingOption[T]

func WithCache

func WithCache[T any](cache *ValueCache) BindingOption[T]

func WithDelayedLocator added in v0.3.0

func WithDelayedLocator[T any](kinds ...string) BindingOption[T]

func WithMissingPolicy added in v0.3.0

func WithMissingPolicy[T any](strict bool) BindingOption[T]

type BindingSpec added in v0.2.0

type BindingSpec struct {
	ResolutionGroup                                                          *ResolutionGroupSpec
	BodyNullPolicy                                                           string
	MarkerField                                                              string
	Path, Name                                                               string
	Location                                                                 state.Location
	SourceType                                                               reflect.Type
	Required, Cacheable                                                      *bool
	MinAllowedRecords, MaxAllowedRecords, ExpectedReturned                   *int
	When, Scope, With, URI, ResourceRef, DataType, ErrorMessage, Cardinality string
	Priority                                                                 int
	Async                                                                    bool
	DefaultValue, Extension                                                  any
	ErrorCode                                                                int
	Transformer                                                              xform.Transformer
}

func BindingSpecFromField added in v0.2.0

func BindingSpecFromField(field reflect.StructField) (BindingSpec, bool, error)

func (BindingSpec) ValidateBodyNullPolicy added in v0.4.0

func (b BindingSpec) ValidateBodyNullPolicy(target reflect.Type) error

ValidateBodyNullPolicy checks the bounded whole-body normalization contract. The empty policy preserves the existing decoding and required-value behavior.

type BindingType

type BindingType struct {
	Bindings []Bindings
	Type     *structology.StateType
	// contains filtered or unexported fields
}

BindingType retains the public metadata surface; execution uses its canonical Plan.

type Bindings

type Bindings []*Binding

func (Bindings) GroupByPriority

func (b Bindings) GroupByPriority(registry *locator.Registry) ([]Bindings, error)

GroupByPriority orders legacy binding metadata using the active registry.

type DynamicContext added in v0.2.0

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

DynamicContext binds runtime-owned targets through the canonical invocation.

func WithDynamicState added in v0.2.0

func WithDynamicState(injector *Injector, stateValue interface{}) *DynamicContext

func (*DynamicContext) Assign added in v0.2.0

func (c *DynamicContext) Assign(ctx context.Context, target interface{}, location *state.Location) error

Assign resolves a typed location and writes its value into a nonnil pointer.

func (*DynamicContext) Inject added in v0.2.0

func (c *DynamicContext) Inject(ctx context.Context, target interface{}) error

func (*DynamicContext) Value added in v0.2.0

func (c *DynamicContext) Value(ctx context.Context, location *state.Location) (interface{}, bool, error)

type Injector

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

Injector represents dependency injector

func NewInjector

func NewInjector(options ...InjectorOption) (*Injector, error)

NewInjector creates injector

func (*Injector) Bind added in v0.2.0

func (i *Injector) Bind(ctx context.Context, target any, options ...BindOption) error

func (*Injector) CompilePlan added in v0.2.0

func (i *Injector) CompilePlan(target reflect.Type, specs ...BindingSpec) (*Plan, error)

func (*Injector) ForScope added in v0.2.0

func (i *Injector) ForScope(providers ...locator.Provider) (*Injector, error)

func (*Injector) HasProvider added in v0.4.1

func (b *Injector) HasProvider(kind string) bool

HasProvider reports whether a provider kind is registered in this injector's lookup ancestry. It does not resolve values or confer binding authority.

func (*Injector) ReadResource added in v0.2.0

func (i *Injector) ReadResource(reference string) ([]byte, error)

func (*Injector) ResourceFS added in v0.2.0

func (i *Injector) ResourceFS(name string) (fs.FS, bool)

func (*Injector) Resources added in v0.2.0

func (i *Injector) Resources() *resource.Store

func (*Injector) TransformerRegistry

func (b *Injector) TransformerRegistry() *xform.Registry

TransformerRegistry returns the transformer registry

type InjectorOption

type InjectorOption func(*Injector)

func WithBindingTag

func WithBindingTag(tag string) InjectorOption

func WithLocators

func WithLocators(registry *locator.Registry) InjectorOption

func WithProviders

func WithProviders(providers ...locator.Provider) InjectorOption

func WithResourceFS added in v0.2.0

func WithResourceFS(name string, source fs.FS) InjectorOption

func WithResources added in v0.2.0

func WithResources(store *resource.Store) InjectorOption

func WithTransformerTag

func WithTransformerTag(tag string) InjectorOption

type Plan added in v0.2.0

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

Plan contains only immutable target metadata; providers are resolved per bind.

func (*Plan) ExplicitPresence added in v0.4.0

func (p *Plan) ExplicitPresence(target any, path string) (present, hasMarker bool, err error)

ExplicitPresence reports suppliedness only from an actual compiled marker. Markerless inputs return hasMarker=false and cannot prove explicit null.

func (*Plan) Presence added in v0.2.0

func (p *Plan) Presence(target any, path string) (bool, error)

Presence reads a binding's compiled presence marker. Inputs without a marker carry values unconditionally. Missing marker pointers represent absence.

func (*Plan) Projection added in v0.2.0

func (p *Plan) Projection(fields ...ProjectionField) (*Projection, error)

func (*Plan) Replay added in v0.2.0

func (p *Plan) Replay(paths ...string) (*ReplayPlan, error)

func (*Plan) SetPresence added in v0.2.0

func (p *Plan) SetPresence(target any, path string, present bool) error

SetPresence restores presence through the same compiled marker used by Bind.

func (*Plan) TargetType added in v0.2.0

func (p *Plan) TargetType() reflect.Type

type Projection added in v0.2.0

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

func (*Projection) Resolver added in v0.2.0

func (p *Projection) Resolver(target any) ValueResolver

func (*Projection) TargetType added in v0.2.0

func (p *Projection) TargetType() reflect.Type

func (*Projection) Value added in v0.2.0

func (p *Projection) Value(target any, name string) (any, bool, error)

func (*Projection) Without added in v0.2.0

func (p *Projection) Without(target any, names ...string) (any, error)

type ProjectionField added in v0.2.0

type ProjectionField struct {
	Path  string
	Names []string
}

type Replay added in v0.2.0

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

Replay holds one detached set of source values. Prepared values can only be produced by successful native binding. It is invocation-owned, not shareable.

func (*Replay) MarshalJSON added in v0.2.0

func (r *Replay) MarshalJSON() ([]byte, error)

func (*Replay) Plan added in v0.2.0

func (r *Replay) Plan() *Plan

func (*Replay) Providers added in v0.2.0

func (r *Replay) Providers() ([]locator.Provider, error)

Providers exposes each selected source kind independently to dependency components. Missing selected inputs are authoritative absence, not fallback.

type ReplayBinding added in v0.2.0

type ReplayBinding struct {
	Replay *Replay
	Only   bool
	Gate   func(context.Context, any) error
}

type ReplayPlan added in v0.2.0

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

ReplayPlan is an immutable selection of external fields from one canonical binding plan. It retains no invocation values or dependency-read evidence.

func (*ReplayPlan) Capture added in v0.2.0

func (p *ReplayPlan) Capture(input any) (*Replay, error)

func (*ReplayPlan) CaptureSources added in v0.2.0

func (p *ReplayPlan) CaptureSources(ctx context.Context, providers []locator.Provider) (*Replay, error)

CaptureSources snapshots only this plan's selected source bindings. Providers are invocation-scoped; no target is initialized, transformer applied, default materialized or prerequisite/dependency evaluated here. Raw-source hooks retain JSON presence and exact numbers before the normal ReplayBinding preflight.

func (*ReplayPlan) DecodeJSON added in v0.2.0

func (p *ReplayPlan) DecodeJSON(data []byte) (*Replay, error)

func (*ReplayPlan) Prepare added in v0.2.0

func (p *ReplayPlan) Prepare(projection *Projection, paths ...string) (*ReplayPlan, error)

Prepare includes fresh, non-persisted bindings needed to authorize external input. Param dependencies are resolved through the plan's canonical aliases.

type ResolutionGroupController added in v0.4.1

type ResolutionGroupController interface {
	Open(context.Context, ResolutionGroupPlan) (ResolutionGroupRun, error)
}

ResolutionGroupController authorizes a finite compiled group for one bind. A controller is invocation scoped; metadata alone grants no continuation.

type ResolutionGroupError added in v0.4.1

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

ResolutionGroupError retains real failures in completion order for the default mode and declaration order for dependency-scheduled groups. Returned slices and BindingError records are copies; causes are retained.

func (*ResolutionGroupError) Error added in v0.4.1

func (e *ResolutionGroupError) Error() string

func (*ResolutionGroupError) Failures added in v0.4.1

func (e *ResolutionGroupError) Failures() []*BindingError

func (*ResolutionGroupError) Unwrap added in v0.4.1

func (e *ResolutionGroupError) Unwrap() []error

type ResolutionGroupMode added in v0.4.1

type ResolutionGroupMode string

ResolutionGroupMode selects scheduling, not application authority.

const (
	// ResolutionGroupConcurrent preserves concurrent attempts and completion-order errors.
	ResolutionGroupConcurrent ResolutionGroupMode = ""
	// ResolutionGroupDependencies waits for successful prerequisites and reports
	// failures in declaration order. Barriers are optional in this mode.
	ResolutionGroupDependencies ResolutionGroupMode = "dependencies"
)

type ResolutionGroupPlan added in v0.4.1

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

ResolutionGroupPlan exposes copied immutable canonical descriptors.

func (ResolutionGroupPlan) After added in v0.4.1

func (p ResolutionGroupPlan) After() []string

func (ResolutionGroupPlan) Members added in v0.4.1

func (p ResolutionGroupPlan) Members() []BindingSpec

func (ResolutionGroupPlan) Mode added in v0.4.1

func (ResolutionGroupPlan) Name added in v0.4.1

func (p ResolutionGroupPlan) Name() string

type ResolutionGroupRun added in v0.4.1

type ResolutionGroupRun interface {
	// Enter must derive its returned context from the supplied member context.
	// Dependency scheduling retains invocation ownership and cancellation.
	Enter(context.Context, string) (context.Context, error)
	Observe(context.Context, ResolutionOutcome) error
	Close(context.Context) error
}

type ResolutionGroupSpec added in v0.4.1

type ResolutionGroupSpec struct {
	Name      string
	Mode      ResolutionGroupMode
	After     []string
	DependsOn []string
}

ResolutionGroupSpec is explicit opt-in authoring metadata. After lists successful canonical barriers. In the default mode DependsOn denotes child input validation; in dependencies mode it also orders member execution.

type ResolutionOutcome added in v0.4.1

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

ResolutionOutcome describes the actual completed binding, including an actual nested BindingError. It never retires child activities.

func (ResolutionOutcome) Attempted added in v0.4.1

func (o ResolutionOutcome) Attempted() bool

Attempted distinguishes actual canonical binding from denied admission.

func (ResolutionOutcome) Cause added in v0.4.1

func (o ResolutionOutcome) Cause() error

func (ResolutionOutcome) Failure added in v0.4.1

func (o ResolutionOutcome) Failure() *BindingError

func (ResolutionOutcome) Metadata added in v0.4.1

func (o ResolutionOutcome) Metadata() any

func (ResolutionOutcome) Path added in v0.4.1

func (o ResolutionOutcome) Path() string

func (ResolutionOutcome) Terminal added in v0.4.1

func (o ResolutionOutcome) Terminal() bool

Terminal reports an actual observer or panic-stage failure, never author metadata.

func (ResolutionOutcome) Value added in v0.4.1

func (o ResolutionOutcome) Value() (any, bool)

type ResolutionPrerequisiteError added in v0.4.1

type ResolutionPrerequisiteError struct {
	Path         string
	Prerequisite string
	Cause        error
}

ResolutionPrerequisiteError describes a skipped member, not an attempted read.

func (*ResolutionPrerequisiteError) Error added in v0.4.1

func (*ResolutionPrerequisiteError) Unwrap added in v0.4.1

func (e *ResolutionPrerequisiteError) Unwrap() error

type StructTypeCache

type StructTypeCache struct {
	internal.Map[reflect.Type, *structology.StateType]
}

func NewStructTypeCache

func NewStructTypeCache() *StructTypeCache

type ValueCache

type ValueCache struct {
	internal.Map[string, interface{}]
	// contains filtered or unexported fields
}

func NewValueCache

func NewValueCache() *ValueCache

func (*ValueCache) Clear

func (c *ValueCache) Clear()

Clear empties the cache

func (*ValueCache) Load

func (c *ValueCache) Load(ctx context.Context, URL string) error

Load loads the cache from disk

func (*ValueCache) Save

func (c *ValueCache) Save(ctx context.Context, destURL string) error

Save persists the cache to disk

type ValueResolver added in v0.2.0

type ValueResolver func(string) (any, bool, error)

Directories

Path Synopsis
Package input owns typed failures of external value decoding and conversion.
Package input owns typed failures of external value decoding and conversion.
bodyjson
Package bodyjson shares native typed JSON and presence reconstruction inside Bindly.
Package bodyjson shares native typed JSON and presence reconstruction inside Bindly.
field
Package field applies immutable field indexes compiled by x/shape.
Package field applies immutable field indexes compiled by x/shape.
provider
body
Package body resolves whole or named request bodies to planned Go types.
Package body resolves whole or named request bodies to planned Go types.
request
Package request composes independently scoped HTTP value providers while preserving the original request pointer for handler capabilities.
Package request composes independently scoped HTTP value providers while preserving the original request pointer for handler capabilities.
values
Package values supplies an invocation-scoped source of authored values.
Package values supplies an invocation-scoped source of authored values.
Package resource owns named package filesystems shared by compilation and invocation.
Package resource owns named package filesystems shared by compilation and invocation.

Jump to

Keyboard shortcuts

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