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)
}
Output:
Index ¶
- func RunResolutionGroupPhase(ctx context.Context, execute func(context.Context) error) error
- func SuspendResolutionGroup(ctx context.Context, wait func(context.Context) error) error
- type BindOption
- func AllowMissingRequired() BindOption
- func OnlyKinds(kinds ...string) BindOption
- func SkipKinds(kinds ...string) BindOption
- func WithBindingObserver(observer BindingObserver) BindOption
- func WithPlan(plan *Plan) BindOption
- func WithReplay(binding ReplayBinding) BindOption
- func WithResolutionGroupConcurrency(limit int) BindOption
- func WithResolutionGroupController(controller ResolutionGroupController) BindOption
- func WithResolvedInput(plan *Plan, detachedInput any, paths ...string) BindOption
- func WithSource(source any) BindOption
- func WithValueCache(cache *ValueCache) BindOption
- type Binder
- type Binding
- type BindingCache
- type BindingContext
- func (c *BindingContext[T]) Bind(ctx context.Context) error
- func (c *BindingContext[T]) BindTarget(ctx context.Context, target any) error
- func (c *BindingContext[T]) Inject(ctx context.Context, target *T) error
- func (c *BindingContext[T]) Value(ctx context.Context, location *state.Location) (any, bool, error)
- type BindingError
- type BindingEvent
- type BindingObserver
- type BindingOption
- type BindingSpec
- type BindingType
- type Bindings
- type DynamicContext
- type Injector
- func (i *Injector) Bind(ctx context.Context, target any, options ...BindOption) error
- func (i *Injector) CompilePlan(target reflect.Type, specs ...BindingSpec) (*Plan, error)
- func (i *Injector) ForScope(providers ...locator.Provider) (*Injector, error)
- func (b *Injector) HasProvider(kind string) bool
- func (i *Injector) ReadResource(reference string) ([]byte, error)
- func (i *Injector) ResourceFS(name string) (fs.FS, bool)
- func (i *Injector) Resources() *resource.Store
- func (b *Injector) TransformerRegistry() *xform.Registry
- type InjectorOption
- func WithBindingTag(tag string) InjectorOption
- func WithLocators(registry *locator.Registry) InjectorOption
- func WithProviders(providers ...locator.Provider) InjectorOption
- func WithResourceFS(name string, source fs.FS) InjectorOption
- func WithResources(store *resource.Store) InjectorOption
- func WithTransformerTag(tag string) InjectorOption
- type Plan
- func (p *Plan) ExplicitPresence(target any, path string) (present, hasMarker bool, err error)
- func (p *Plan) Presence(target any, path string) (bool, error)
- func (p *Plan) Projection(fields ...ProjectionField) (*Projection, error)
- func (p *Plan) Replay(paths ...string) (*ReplayPlan, error)
- func (p *Plan) SetPresence(target any, path string, present bool) error
- func (p *Plan) TargetType() reflect.Type
- type Projection
- type ProjectionField
- type Replay
- type ReplayBinding
- type ReplayPlan
- func (p *ReplayPlan) Capture(input any) (*Replay, error)
- func (p *ReplayPlan) CaptureSources(ctx context.Context, providers []locator.Provider) (*Replay, error)
- func (p *ReplayPlan) DecodeJSON(data []byte) (*Replay, error)
- func (p *ReplayPlan) Prepare(projection *Projection, paths ...string) (*ReplayPlan, error)
- type ResolutionGroupController
- type ResolutionGroupError
- type ResolutionGroupMode
- type ResolutionGroupPlan
- type ResolutionGroupRun
- type ResolutionGroupSpec
- type ResolutionOutcome
- func (o ResolutionOutcome) Attempted() bool
- func (o ResolutionOutcome) Cause() error
- func (o ResolutionOutcome) Failure() *BindingError
- func (o ResolutionOutcome) Metadata() any
- func (o ResolutionOutcome) Path() string
- func (o ResolutionOutcome) Terminal() bool
- func (o ResolutionOutcome) Value() (any, bool)
- type ResolutionPrerequisiteError
- type StructTypeCache
- type ValueCache
- type ValueResolver
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func RunResolutionGroupPhase ¶ added in v0.4.1
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
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) IsCacheable ¶ added in v0.3.0
IsCacheable reports whether binding result should be cached.
func (*Binding) IsRequired ¶ added in v0.3.0
IsRequired reports whether binding is required.
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
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
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 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.
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) CompilePlan ¶ added in v0.2.0
func (*Injector) HasProvider ¶ added in v0.4.1
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 (*Injector) ResourceFS ¶ added in v0.2.0
func (*Injector) TransformerRegistry ¶
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
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
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) SetPresence ¶ added in v0.2.0
SetPresence restores presence through the same compiled marker used by Bind.
func (*Plan) TargetType ¶ added in v0.2.0
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
type ProjectionField ¶ added in v0.2.0
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
type ReplayBinding ¶ added in v0.2.0
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 (p ResolutionGroupPlan) Mode() ResolutionGroupMode
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
ResolutionPrerequisiteError describes a skipped member, not an attempted read.
func (*ResolutionPrerequisiteError) Error ¶ added in v0.4.1
func (e *ResolutionPrerequisiteError) Error() string
func (*ResolutionPrerequisiteError) Unwrap ¶ added in v0.4.1
func (e *ResolutionPrerequisiteError) Unwrap() error
type StructTypeCache ¶
func NewStructTypeCache ¶
func NewStructTypeCache() *StructTypeCache
type ValueCache ¶
type ValueCache struct {
internal.Map[string, interface{}]
// contains filtered or unexported fields
}
func NewValueCache ¶
func NewValueCache() *ValueCache
Source Files
¶
- bind_option.go
- binder.go
- binding.go
- binding_metadata.go
- binding_reflect.go
- bindings.go
- cache.go
- context.go
- convert.go
- dynamic.go
- inject.go
- injector.go
- option.go
- plan.go
- projection.go
- record_count.go
- replay.go
- replay_binding.go
- replay_capture.go
- replay_plan.go
- replay_provider.go
- required_absence.go
- resolution_dependencies.go
- resolution_group.go
- resolution_group_controller.go
- resolution_group_error.go
- resolution_scheduler.go
- resolved_input.go
- resource.go
- scope.go
- spec.go
- tag.go
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. |