dixinternal

package
v2.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultProviderTimeout is the default max execution time for a single provider call.
	// Set WithProviderTimeout(0) to disable timeout control.
	DefaultProviderTimeout = 15 * time.Second

	// DefaultSlowProviderThreshold is the default warning threshold for provider execution latency.
	// Set WithSlowProviderThreshold(0) to disable slow-provider warnings.
	DefaultSlowProviderThreshold = 2 * time.Second
)
View Source
const (

	// InjectMethodPrefix can inject objects, as long as the method of this object contains a prefix of `InjectMethodPrefix`
	InjectMethodPrefix = "DixInject"
)

Variables

This section is empty.

Functions

func GetFnName

func GetFnName(fn reflect.Value) string

GetFnName returns the name of the function represented by reflect.Value

func GetFnTraceName

func GetFnTraceName(fn reflect.Value) string

GetFnTraceName returns function name for trace logs with best-effort full package path. For normal packages runtime already returns full import path. For `main.*` symbols, this attempts to rebuild a module-qualified path from source file location.

func GetProvideAllInputTypes

func GetProvideAllInputTypes(typ reflect.Type) []reflect.Type

GetProvideAllInputTypes returns all input types for a given type, including struct fields This is a public version of getProvideAllInputs that returns types instead of internal structures

func SetLog

func SetLog(handler slog.Handler)

Types

type DiagFileQuery

type DiagFileQuery struct {
	Kind      string
	Event     string
	Search    string
	Limit     int
	BeforeID  int64
	SinceUnix int64
	UntilUnix int64
}

DiagFileQuery controls filtering and pagination for DIX_DIAG_FILE records.

type DiagFileReadResult

type DiagFileReadResult struct {
	Enabled    bool             `json:"enabled"`
	Path       string           `json:"path,omitempty"`
	Exists     bool             `json:"exists"`
	Total      int              `json:"total"`
	Returned   int              `json:"returned"`
	NextBefore int64            `json:"next_before_id,omitempty"`
	Records    []DiagFileRecord `json:"records"`
}

DiagFileReadResult is the API response object for diagnostic file queries.

func ReadDiagFileRecords

func ReadDiagFileRecords(query DiagFileQuery) (DiagFileReadResult, error)

ReadDiagFileRecords loads and filters records from DIX_DIAG_FILE.

func ReadDiagFileRecordsFromLines

func ReadDiagFileRecordsFromLines(lines []string, query DiagFileQuery) DiagFileReadResult

ReadDiagFileRecordsFromLines is a test helper for parsing query behavior without I/O.

type DiagFileRecord

type DiagFileRecord struct {
	RecordID   int64          `json:"record_id,omitempty"`
	Source     string         `json:"source,omitempty"`
	PID        int            `json:"pid,omitempty"`
	Process    string         `json:"process,omitempty"`
	Hostname   string         `json:"hostname,omitempty"`
	TraceDI    bool           `json:"trace_di,omitempty"`
	Kind       string         `json:"kind"`
	OccurredAt int64          `json:"occurred_at_unix_nano"`
	Event      string         `json:"event,omitempty"`
	Fields     map[string]any `json:"fields,omitempty"`
	Payload    any            `json:"payload,omitempty"`
}

DiagFileRecord is an exported diagnostic record returned by file-query APIs.

type Dix

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

func New

func New(opts ...Option) *Dix

New Dix new

func (*Dix) EgoGraph added in v2.2.0

func (dix *Dix) EgoGraph(center string, depth int, direction string) GraphView

EgoGraph 以 center 类型为中心,沿声明边做 depth 跳 BFS: direction=deps 只看依赖方向,dependents 只看被依赖方向,both 双向。

func (*Dix) GetObjects

func (dix *Dix) GetObjects() map[reflect.Type]map[string][]reflect.Value

GetObjects returns a copy of the objects map for inspection This is useful for HTTP visualization endpoints

func (*Dix) GetProviderDetails

func (dix *Dix) GetProviderDetails() []ProviderDetails

GetProviderDetails returns detailed information about all providers

func (*Dix) GetProviderRuntimeStats

func (dix *Dix) GetProviderRuntimeStats() []ProviderRuntimeStats

GetProviderRuntimeStats returns runtime stats sorted by total duration (descending). This is helpful for startup latency diagnosis.

func (*Dix) GetProviders

func (dix *Dix) GetProviders() map[reflect.Type][]*providerFn

GetProviders returns a copy of the providers map for inspection This is useful for HTTP visualization endpoints

func (*Dix) GetRecentErrors

func (dix *Dix) GetRecentErrors(limit int) []RecentError

GetRecentErrors returns recent Inject/TryInject errors in reverse-chronological order. limit <= 0 means return all currently retained errors.

func (*Dix) GraphVersion added in v2.2.0

func (dix *Dix) GraphVersion() uint64

GraphVersion 返回运行时依赖图版本号,供 dixhttp 快照判脏。

func (*Dix) Inject

func (dix *Dix) Inject(param any, opts ...Option) any

Inject injects dependencies into the given parameter. Panics on error. NOTE: Dix container is not thread-safe. Do not call Provide/Inject concurrently on the same container.

func (*Dix) InjectContext

func (dix *Dix) InjectContext(ctx context.Context, param any, opts ...Option) any

InjectContext injects dependencies using the provided context as trace propagation root. Panics on error. NOTE: Dix container is not thread-safe. Do not call Provide/Inject concurrently on the same container.

func (*Dix) ModuleGraph added in v2.2.0

func (dix *Dix) ModuleGraph() []ModuleInfo

ModuleGraph 按模块聚合节点,并从声明边提取跨模块依赖(去重、排序)。

func (*Dix) ModuleView added in v2.2.0

func (dix *Dix) ModuleView(name string, nodeLimit, edgeLimit int) ModuleDetailView

ModuleView returns providers, produced outputs, declared dependencies, and external dependency types for one module. Results are deterministically bounded so a large module cannot force an unrenderable response.

func (*Dix) Option

func (dix *Dix) Option() Options

func (*Dix) ProblemProviders added in v2.2.0

func (dix *Dix) ProblemProviders() (slow, errored []string)

ProblemProviders 返回慢 provider 与错误 provider 的函数名(去重、排序)。

func (*Dix) Provide

func (dix *Dix) Provide(param any)

Provide registers a provider function. Panics on error. NOTE: Dix container is not thread-safe. Do not call Provide/Inject concurrently on the same container.

func (*Dix) ResolvedTopN added in v2.2.0

func (dix *Dix) ResolvedTopN(n int) []ResolvedCount

ResolvedTopN 返回解析次数最多的前 n 个类型(降序)。

func (*Dix) SearchNodes added in v2.2.0

func (dix *Dix) SearchNodes(q, kind, module, state string, limit int) []SearchHit

SearchNodes 按关键字/类别/模块前缀/运行时状态过滤图节点。

func (*Dix) TraceTree added in v2.2.0

func (dix *Dix) TraceTree(traceID string) dixtrace.TreeResult

TraceTree 返回一次注入链路的调用树(按 trace_id)。 容器启用 WithTraceBuffer 时查询私有缓冲,否则查询全局。

func (*Dix) TryInject

func (dix *Dix) TryInject(param any, opts ...Option) error

TryInject injects dependencies into the given parameter. Returns error instead of panicking. NOTE: Dix container is not thread-safe. Do not call Provide/Inject concurrently on the same container.

func (*Dix) TryInjectContext

func (dix *Dix) TryInjectContext(ctx context.Context, param any, opts ...Option) error

TryInjectContext injects dependencies using the provided context as trace propagation root. Returns error instead of panicking. NOTE: Dix container is not thread-safe. Do not call Provide/Inject concurrently on the same container.

func (*Dix) TryProvide

func (dix *Dix) TryProvide(param any) (err error)

TryProvide registers a provider function. Returns error instead of panicking. NOTE: Dix container is not thread-safe. Do not call Provide/Inject concurrently on the same container.

type Edge added in v2.2.0

type Edge struct {
	From, To  NodeID
	Kind      EdgeKind
	Field     string
	Aggregate string
	Provider  *providerFn
	Count     int64
}

Edge 是 Graph 有向边。声明边:输出类型 -> 输入类型; 产物边:provider -> 输出类型;解析边:provider -> 输出类型(执行计数)。

type EdgeKind added in v2.2.0

type EdgeKind uint8

EdgeKind 区分声明依赖、产物输出与运行时实际解析。

const (
	EdgeDeclared EdgeKind = iota
	EdgeProduced
	EdgeResolved
)

type Graph added in v2.2.0

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

Graph 是容器运行时依赖图。Dix 单线程写,但 dixhttp 并发读, 因此全部访问走读写锁;version 供快照判脏。

func (*Graph) Version added in v2.2.0

func (g *Graph) Version() uint64

Version 返回图版本号;Provide 或新对象入图时递增。

type GraphEdge added in v2.2.0

type GraphEdge struct {
	From     string `json:"from"`
	To       string `json:"to"`
	FromKind string `json:"from_kind,omitempty"`
	ToKind   string `json:"to_kind,omitempty"`
}

GraphEdge 是邻域子图里的一条声明依赖边(类型 label 表示)。

type GraphView added in v2.2.0

type GraphView struct {
	Nodes []SearchHit `json:"nodes"`
	Edges []GraphEdge `json:"edges"`
}

GraphView 是邻域子图:节点摘要 + 声明边。

type ModuleDependency added in v2.2.0

type ModuleDependency struct {
	Name      string `json:"name"`
	EdgeCount int    `json:"edge_count"`
}

ModuleDependency is an aggregated cross-module relationship.

type ModuleDetailView added in v2.2.0

type ModuleDetailView struct {
	Name          string             `json:"name"`
	TypeCount     int                `json:"type_count"`
	ProviderCount int                `json:"provider_count"`
	ObjectCount   int                `json:"object_count"`
	DependsOn     []ModuleDependency `json:"depends_on,omitempty"`
	DependedOnBy  []ModuleDependency `json:"depended_on_by,omitempty"`
	Nodes         []SearchHit        `json:"nodes"`
	Edges         []GraphEdge        `json:"edges"`
	Truncated     bool               `json:"truncated"`
}

ModuleDetailView is a bounded topology projection for one module.

type ModuleInfo added in v2.2.0

type ModuleInfo struct {
	Name          string   `json:"name"`
	TypeCount     int      `json:"type_count"`
	ProviderCount int      `json:"provider_count"`
	ObjectCount   int      `json:"object_count"`
	DependsOn     []string `json:"depends_on,omitempty"`
}

ModuleInfo 是模块(pkg)级聚合视图的一行。

type Node added in v2.2.0

type Node struct {
	ID       NodeID
	Kind     NodeKind
	Type     reflect.Type
	Group    string
	Provider *providerFn
	Label    string
	Pkg      string
}

Node 是 Graph 节点。Object 节点的存在即"已实例化"状态。

type NodeID added in v2.2.0

type NodeID uint32

NodeID 是 Graph 内节点自增编号。

type NodeKind added in v2.2.0

type NodeKind uint8

NodeKind 区分依赖类型节点、provider 节点与已创建对象节点。

const (
	NodeType NodeKind = iota
	NodeProvider
	NodeObject
)

type Option

type Option func(opts *Options)

func WithProviderTimeout

func WithProviderTimeout(timeout time.Duration) Option

func WithRejectEmptyCollections added in v2.0.2

func WithRejectEmptyCollections() Option

WithRejectEmptyCollections rejects injections of missing map/list dependencies instead of resolving them as empty collections. It is the counterpart of the default AllowValuesNull=true behavior.

func WithSlowProviderThreshold

func WithSlowProviderThreshold(threshold time.Duration) Option

func WithTraceBuffer added in v2.2.0

func WithTraceBuffer(n int) Option

WithTraceBuffer 为容器分配私有 trace 内存缓冲(条数,容量不足 FIFO 驱逐)。 默认 0:span 事件进入全局内存 sink。

func WithValuesNull

func WithValuesNull() Option

type Options

type Options struct {
	// AllowValuesNull tolerates missing map/list dependencies by resolving
	// them as empty collections. Missing single-value dependencies always
	// fail regardless of this flag.
	AllowValuesNull bool

	// ProviderTimeout limits the maximum execution time of one provider call.
	// Zero means no timeout.
	// A timed-out call cannot be aborted: the provider is marked as failed and
	// will not be re-executed by later Inject/TryInject calls.
	ProviderTimeout time.Duration

	// SlowProviderThreshold emits warning log if provider execution is slower than this threshold.
	// Zero means no slow-warning threshold.
	SlowProviderThreshold time.Duration

	// TraceBuffer 为容器分配私有 trace 内存缓冲(条数)。
	// 0 表示不私有化:span 事件进入全局内存 sink(默认)。
	TraceBuffer int
}

func (Options) Validate

func (o Options) Validate() error

type ProviderDetails

type ProviderDetails struct {
	OutputType     string   `json:"output_type"`
	OutputPkg      string   `json:"output_pkg"`
	FunctionName   string   `json:"function_name"`
	FunctionPkg    string   `json:"function_pkg"`
	FunctionFile   string   `json:"function_file"`
	FunctionLine   int      `json:"function_line"`
	InputTypes     []string `json:"input_types"`
	InputPkgs      []string `json:"input_pkgs"`
	RegistrationID uint64   `json:"registration_id"`
	ProviderID     string   `json:"provider_id"`
}

ProviderDetails contains detailed information about a provider

type ProviderRuntimeStats

type ProviderRuntimeStats struct {
	FunctionName      string        `json:"function_name"`
	OutputType        string        `json:"output_type"`
	RegistrationID    uint64        `json:"registration_id"`
	ProviderID        string        `json:"provider_id"`
	CallCount         int           `json:"call_count"`
	TotalDuration     time.Duration `json:"total_duration"`
	AverageDuration   time.Duration `json:"average_duration"`
	LastDuration      time.Duration `json:"last_duration"`
	LastError         string        `json:"last_error,omitempty"`
	LastRunAtUnixNano int64         `json:"last_run_at_unix_nano"`
}

ProviderRuntimeStats contains provider runtime metrics for diagnostics.

type RecentError

type RecentError struct {
	Operation          string        `json:"operation"`
	ErrorType          string        `json:"error_type,omitempty"`
	Component          string        `json:"component"`
	Stage              string        `json:"stage,omitempty"`
	ProviderFunction   string        `json:"provider_function,omitempty"`
	OutputType         string        `json:"output_type,omitempty"`
	InputType          string        `json:"input_type,omitempty"`
	InputTypes         []string      `json:"input_types,omitempty"`
	Message            string        `json:"message"`
	RootCause          string        `json:"root_cause,omitempty"`
	Hint               string        `json:"hint,omitempty"`
	TraceID            string        `json:"trace_id,omitempty"`
	TimedOut           bool          `json:"timed_out,omitempty"`
	Duration           time.Duration `json:"duration,omitempty"`
	Timeout            time.Duration `json:"timeout,omitempty"`
	OccurredAtUnixNano int64         `json:"occurred_at_unix_nano"`
}

RecentError contains a recently captured Inject/TryInject failure event.

type ResolvedCount added in v2.2.0

type ResolvedCount struct {
	Type  string `json:"type"`
	Count int64  `json:"count"`
}

ResolvedCount 是类型维度的解析热度。

type SearchHit added in v2.2.0

type SearchHit struct {
	ID       uint32 `json:"id"`
	Kind     string `json:"kind"` // type|provider|object
	Label    string `json:"label"`
	Pkg      string `json:"pkg,omitempty"`
	Group    string `json:"group,omitempty"`
	External bool   `json:"external,omitempty"`
	State    string `json:"state,omitempty"` // instantiated|error|slow
	Provider string `json:"provider,omitempty"`
}

SearchHit 是检索命中的节点摘要。

Jump to

Keyboard shortcuts

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