component

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package component defines the Component abstraction that unifies every subsystem in chok (logger, db, cache, scheduler, auth, ...) under a single lifecycle + configuration + health + reload contract.

Design rationale and architecture: docs/design.md (§4 核心抽象).

The mandatory Component interface requires only Name, Init, and Close. All other capabilities (Reload, Health, Route mounting, Migration, Dependencies, ConfigKey, etc.) are opt-in via separate interfaces that the Registry discovers through type assertions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigChanged

func ConfigChanged(ctx context.Context) bool

ConfigChanged returns whether the config file changed during this reload. Returns true if absent (conservative default: assume config changed).

func Get

func Get[T Component](k Kernel, name string) (T, bool)

Get is a type-safe helper for retrieving a Component from a Kernel. It replaces the common k.Get("name").(*SomeComponent) pattern with a nil-safe generic alternative that never panics on type mismatch:

redis, ok := component.Get[*parts.RedisComponent](k, "redis")

func MustGet

func MustGet[T Component](k Kernel, name string) T

MustGet is like Get but panics if the component is not found or has the wrong type. Intended for Init methods where a missing declared dependency is a programming error that should fail fast:

redis := component.MustGet[*parts.RedisComponent](k, "redis")

func ReasonFrom

func ReasonFrom(ctx context.Context) string

ReasonFrom retrieves the trigger reason from ctx. Returns "" if absent.

func SectionChanged

func SectionChanged(ctx context.Context, section string) bool

SectionChanged reports whether the named config section changed during this reload cycle. Returns true if:

  • the section is in the changed set
  • no section info is available (conservative default)
  • ConfigChanged(ctx) is false (no config changed at all → false for all sections)

Components should use their ConfigKey() as the section name:

func (l *LoggerComponent) Reload(ctx context.Context) error {
    if !component.SectionChanged(ctx, l.ConfigKey()) {
        return nil // my config didn't change, skip
    }
    // ... actual reload
}

func WithChangedSections

func WithChangedSections(ctx context.Context, sections map[string]bool) context.Context

WithChangedSections stores the set of config section keys that changed during a reload. Components can check SectionChanged(ctx, key) to skip expensive re-initialization when their specific config section didn't change.

func WithConfigChanged

func WithConfigChanged(ctx context.Context, changed bool) context.Context

WithConfigChanged marks in ctx whether the config file actually changed during a reload. Components can check this via ConfigChanged(ctx) to skip expensive re-initialization when the reload was triggered manually (e.g. SIGHUP) without actual config changes.

func WithEvent

func WithEvent(ctx context.Context, event Event) context.Context

WithEvent stores the lifecycle event name in ctx. Injected automatically by Registry.emit — hooks receive it for free.

func WithPhaseResult

func WithPhaseResult(ctx context.Context, result PhaseResult) context.Context

WithPhaseResult stores the lifecycle phase result in ctx. Injected by Registry into after-event hooks (EventAfterStart, EventAfterStop, EventAfterReload).

func WithReason

func WithReason(ctx context.Context, reason string) context.Context

WithReason stores a human-readable trigger reason in ctx (e.g. "signal", "file_change", "api_call"). Callers inject this before invoking Reload or Stop so hooks can distinguish the trigger source.

Types

type CloseTimeouter

type CloseTimeouter interface {
	CloseTimeout() time.Duration
}

CloseTimeouter is implemented by components that need a custom Close timeout. When a component's Close exceeds this duration, the context passed to Close is cancelled and the error is recorded.

Components that don't implement this interface use the Registry's default close timeout (see Registry.SetCloseTimeout).

type Component

type Component interface {
	// Name is the unique identifier used for registration, dependency
	// lookup, logging, and health reports. Conventionally a short
	// lowercase identifier (e.g. "log", "db", "cache").
	Name() string

	// Init is called once during Registry.Start, after all declared
	// Dependencies have been Init'd. It is where the component acquires
	// resources (opens connections, starts goroutines, mounts routes on
	// the HTTP server, etc.).
	//
	// Returning an error aborts startup: already-initialised components
	// are Close'd in reverse order and Start returns the error.
	Init(ctx context.Context, k Kernel) error

	// Close releases resources acquired in Init. Called in reverse
	// topological order during Registry.Stop. Close should be idempotent
	// and safe to call even if Init failed partway.
	Close(ctx context.Context) error
}

Component is the mandatory interface every subsystem implements. Optional capabilities (Reload, Health, Route mounting, Migration, explicit dependencies) are declared by also implementing the corresponding interface below; the Registry uses type assertions to dispatch to them.

type ComponentInfo

type ComponentInfo struct {
	Name                 string   `json:"name"`
	Level                int      `json:"level"`
	Dependencies         []string `json:"dependencies,omitempty"`
	OptionalDependencies []string `json:"optional_dependencies,omitempty"`
	Capabilities         []string `json:"capabilities"`
	InitDurationMs       int64    `json:"init_duration_ms,omitempty"`
}

ComponentInfo describes a registered component for debug/diagnostics.

type ConfigKeyer

type ConfigKeyer interface {
	ConfigKey() string
}

ConfigKeyer is an optional interface for components that map to a specific top-level key in the application config (e.g. "log", "cache"). Not part of the mandatory Component contract — most components use the Resolver pattern instead, making ConfigKey redundant. Implement this only when external tooling needs to discover the mapping.

type Dependent

type Dependent interface {
	// Dependencies returns the names of components that must be Init'd
	// before this one. Unknown names abort startup with a clear error.
	// Cyclic declarations abort startup with a cycle listing.
	Dependencies() []string
}

Dependent declares ordering constraints. Components without Dependencies are assumed to depend on nothing and are Init'd in registration order relative to other no-dependency components.

type DepsValidator

type DepsValidator interface {
	ValidateDeps(k Kernel) error
}

DepsValidator is implemented by components that want to validate their dependencies are properly configured before Init runs. ValidateDeps is called after topological sort but before any Init — catching "account enabled but db not configured" errors early rather than deep inside Init.

type Event

type Event string

Event identifies an application-level lifecycle phase. Hooks registered via Kernel.On run in registration order when the phase fires.

const (
	// EventBeforeStart fires after config is loaded and the Registry is
	// about to Init the first component.
	EventBeforeStart Event = "before_start"

	// EventAfterStart fires once every component's Init has succeeded and
	// the application is fully running.
	EventAfterStart Event = "after_start"

	// EventBeforeStop fires when shutdown is initiated, before the first
	// Close is invoked. Useful for draining traffic or posting a "going
	// away" notice.
	EventBeforeStop Event = "before_stop"

	// EventAfterStop fires after the last component has Close'd
	// successfully. The process is about to exit.
	EventAfterStop Event = "after_stop"

	// EventBeforeReload fires when a reload is triggered (SIGHUP / API
	// call), before any component sees the new config.
	EventBeforeReload Event = "before_reload"

	// EventAfterReload fires after every Reloadable.Reload has been
	// invoked (even if some returned errors).
	EventAfterReload Event = "after_reload"
)

func EventFrom

func EventFrom(ctx context.Context) Event

EventFrom retrieves the event name from ctx. Returns "" if absent.

type HealthLevel

type HealthLevel string

HealthLevel is a coarse status classification used by /healthz.

const (
	// HealthOK means the component is fully operational.
	HealthOK HealthLevel = "ok"

	// HealthDegraded means the component is serving but impaired
	// (e.g. fallback cache path active, replica lag high). Aggregated
	// report still returns HTTP 200 but flags the component.
	HealthDegraded HealthLevel = "degraded"

	// HealthDown means the component cannot serve requests. Causes the
	// aggregated /healthz to return 503.
	HealthDown HealthLevel = "down"
)

type HealthReport

type HealthReport struct {
	Status     HealthLevel             `json:"status"`
	Components map[string]HealthStatus `json:"components"`
}

HealthReport is the aggregated view returned by Registry.Health. Status is "ok" only when every component is OK; any down component forces Status=down; any degraded (with no down) yields Status=degraded.

type HealthStatus

type HealthStatus struct {
	Status  HealthLevel    `json:"status"`
	Details map[string]any `json:"details,omitempty"`
	// Error is the stringified error (if any) that caused degraded/down
	// status. Kept separate from Details so probes can render it
	// consistently without nested type assertions.
	Error string `json:"error,omitempty"`
}

HealthStatus is a single component's health probe result.

type Healther

type Healther interface {
	Health(ctx context.Context) HealthStatus
}

Healther is implemented by components that expose a health probe. The returned HealthStatus is aggregated by Registry.Health into a report suitable for /healthz. Non-implementers are assumed healthy.

type Hook

type Hook func(ctx context.Context) error

Hook is a lifecycle event callback. Return an error to surface it to the reload/shutdown caller; most hooks should only return an error for critical issues since hook errors do not necessarily abort the phase.

The ctx passed to hooks carries enrichment values accessible via EventFrom(ctx) and ReasonFrom(ctx).

type InitTimeouter

type InitTimeouter interface {
	InitTimeout() time.Duration
}

InitTimeouter is implemented by components that need a custom Init timeout. When a component's Init exceeds this duration, the context passed to Init is cancelled and the startup is aborted.

Components that don't implement this interface use the Registry's default init timeout (see Registry.SetDefaultInitTimeout).

type Kernel

type Kernel interface {
	// Config returns the application config pointer. Components cast it
	// to the concrete struct type they expect. The pointer refers to the
	// live config struct that is updated in-place during Reload via
	// reflect.Value.Set under configMu. Single-field reads are safe on
	// aligned architectures, but multi-field reads across a reload
	// boundary may observe inconsistent state. For consistent multi-field
	// access, use ConfigSnapshot() instead.
	Config() any

	// ConfigSnapshot returns a shallow copy of the top-level config
	// struct, captured atomically after each Reload (or after initial
	// load). Resolvers that read multiple fields should prefer this
	// over Config() to avoid torn reads: the top-level struct value
	// is a fresh allocation, so value-type fields are fully
	// independent of subsequent reloads.
	//
	// Slice/map/pointer fields still share backing storage with the
	// live config. Mutating elements of such a field (e.g. indexing
	// into a []string TrustedProxies or map[string]any Metadata) CAN
	// affect the live config — treat the snapshot as read-only. For
	// deeply nested dynamic config, copy the slice/map explicitly
	// before handing it out to caller code that might mutate it.
	ConfigSnapshot() any

	// Logger returns the shared framework logger. Components should
	// derive per-component loggers via Logger().With("component", Name).
	Logger() log.Logger

	// Get returns a previously-registered component by name, or nil if
	// unregistered or disabled. Components use this to reach declared
	// dependencies — e.g. the cache component obtains the redis client
	// via k.Get("redis").(*RedisComponent).Client().
	Get(name string) Component

	// On subscribes a hook to an application-level event. The hook fires
	// during the corresponding phase in Registry.Start/Stop/Reload. See
	// the Event constants for the available phases.
	On(event Event, hook Hook)

	// Health aggregates every Healther component into a single report.
	// Intended for HealthComponent (which exposes /healthz) and admin
	// tooling; callers that only need one component's status should
	// use Get(name) and type-assert instead.
	Health(ctx context.Context) HealthReport

	// ReadyCheck polls every ReadyChecker component and returns the
	// first non-nil error. Returns nil when all components (or none)
	// are ready. Intended for /readyz to gate traffic until warm-up
	// completes.
	ReadyCheck(ctx context.Context) error
}

Kernel is the minimal view a Component has of the surrounding application. It deliberately excludes App-specific lifecycle methods so Components cannot re-enter Run/Stop or mutate registration. The interface is also easy to mock in tests.

type Migratable

type Migratable interface {
	Migrate(ctx context.Context) error
}

Migratable is implemented by components that need to run database or schema migrations at startup. Called between Init and Close in dependency order (typically db → components-that-own-tables).

type OptionalDependent

type OptionalDependent interface {
	OptionalDependencies() []string
}

OptionalDependent declares soft ordering constraints. Unlike Dependent, missing optional dependencies do NOT abort startup — they are silently skipped. When an optional dependency IS registered, it will be Init'd before this component; when it is absent, the component Init proceeds without it.

Typical use: HTTPComponent optionally depends on "metrics" and "log" for middleware injection. If those components exist, they Init first; if not, HTTP inits without them.

type Optionaler

type Optionaler interface {
	Optional() bool
}

Optionaler is implemented by components whose Init failure should not abort application startup. When Init returns an error for an optional component, the Registry logs a warning and continues — the component is not added to the start order and Kernel.Get returns nil for it.

Typical candidates: cache, metrics, tracing — subsystems that enhance but are not required for core business logic.

type PhaseResult

type PhaseResult struct {
	Duration time.Duration // wall-clock duration of the phase
	Err      error         // nil on success
}

PhaseResult carries the outcome of a lifecycle phase (Start/Stop/Reload) so hooks can observe success/failure and duration for observability.

func PhaseResultFrom

func PhaseResultFrom(ctx context.Context) (PhaseResult, bool)

PhaseResultFrom retrieves the phase result from ctx. Returns a zero PhaseResult if absent.

type ReadyChecker

type ReadyChecker interface {
	ReadyCheck(ctx context.Context) error
}

ReadyChecker is an optional interface for components that need a warm-up period after Init before they can serve traffic. A component whose Init succeeds but whose ReadyCheck returns a non-nil error is treated as "started but not yet ready" — /readyz will return 503 until all ReadyCheckers pass.

Typical candidates: caches that need pre-warming, components that load initial state from a remote service, connection pools that must establish a minimum number of connections.

The context carries a deadline derived from the health timeout; the check should be lightweight and fast.

type Registry

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

Registry sequences the lifecycle of a set of Components according to their declared dependency graph. It is the engine behind the Component abstraction — see the package doc comment for context.

Typical usage from App.Run:

reg := component.New(cfg, logger)
reg.Register(&LoggerComponent{})
reg.Register(&DBComponent{})
reg.Register(&AccountComponent{}) // Dependencies() = ["db", "log"]

if err := reg.Start(ctx); err != nil { return err }
defer reg.Stop(shutdownCtx)

Registry itself implements Kernel, which is the view each Component sees inside its Init method. Registry is safe to use from a single goroutine — start/stop/reload must not be called concurrently. Get and Health may be called concurrently after Start.

func New

func New(config any, logger log.Logger) *Registry

New creates an empty Registry. config is the application's fully-loaded configuration structure; Components cast it to the expected concrete type via Kernel.Config(). logger is the shared framework logger.

func (*Registry) Components

func (r *Registry) Components() []Component

Components returns all registered components in registration order. Includes components that failed Init (optional skip). For only successfully-started components, use StartedComponents(). Safe to call after Start from any goroutine.

func (*Registry) Config

func (r *Registry) Config() any

Config returns the application config that was passed to New.

func (*Registry) ConfigSnapshot

func (r *Registry) ConfigSnapshot() any

ConfigSnapshot returns the last atomically-published config snapshot. The snapshot is a shallow copy of the top-level config struct — all value-type fields (string, int, bool, nested structs) are independent of the live config. Slice and map fields share backing storage with the live config; however, the framework's built-in Options types use only value fields, so this is safe for standard usage.

Resolvers should prefer ConfigSnapshot() over Config() to avoid observing a partially-written struct during a concurrent Reload. Returns the live config if no snapshot has been published yet.

func (*Registry) DebugInfo

func (r *Registry) DebugInfo() map[string]any

DebugInfo returns a structured snapshot of the registry state for diagnostics. Includes component topology, capabilities, init timing, and failed optional components. Intended for /componentz debug endpoints — disabled in production by default.

func (*Registry) Get

func (r *Registry) Get(name string) Component

Get returns a registered Component by name, or nil if not registered.

During the Init phase (initInProgress=true), Get only returns components that have already finished Init — preventing a parallel peer from touching a half-built sibling.

During Stop (phase == phaseStopping/phaseStopped), Get only returns components still in the "available" set. Stop scrubs `available` entries as it Close's each component, so Get cannot hand back a reference to an already-torn-down peer. EventBeforeStop hooks fire before any Close runs, so they still observe the full set.

Outside those windows (phaseBuild for inspection, phaseStarted for runtime), Get returns directly from byName.

Safe to call from any goroutine.

func (*Registry) Health

func (r *Registry) Health(ctx context.Context) HealthReport

Health polls every Healther Component and aggregates the results into a report. Probes run in parallel with a per-probe timeout (see SetHealthTimeout). Non-Healther components default to HealthOK. The aggregate Status follows the rule:

any component down      → HealthDown
none down, any degraded → HealthDegraded
otherwise               → HealthOK

Safe to call concurrently with application traffic; does not take the write lock.

func (*Registry) Logger

func (r *Registry) Logger() log.Logger

Logger returns the shared framework logger.

func (*Registry) On

func (r *Registry) On(event Event, hook Hook)

On subscribes hook to the given event. Registered hooks fire in registration order when the event phase is emitted.

Registration is permitted during phaseBuild (pre-Start) and phaseStarted (post-Start extensions like admin APIs that want to observe Reload/Stop). It is rejected in phaseStopping / phaseStopped with a panic — adding a hook to a registry that's already tearing down is almost always a bug (the hook would never fire for lifecycle events that already emitted, and the caller usually expects otherwise).

func (*Registry) Order

func (r *Registry) Order() ([]string, error)

Order returns the component names in topological (init) order. Returns an error if the graph is invalid. Useful for diagnostics.

func (*Registry) PublishConfigSnapshot

func (r *Registry) PublishConfigSnapshot()

PublishConfigSnapshot creates a shallow copy of the top-level config struct and stores it atomically. Called by App after loadConfig and after each successful ReloadConfig. Value-type fields are fully independent; slice/map fields share backing storage (acceptable for the framework's built-in Options which are value-only).

The caller must hold a.configMu (or equivalent) while mutating config and calling this method to prevent torn reads during the copy.

func (*Registry) ReadyCheck

func (r *Registry) ReadyCheck(ctx context.Context) error

ReadyCheck polls every ReadyChecker Component sequentially and returns the first non-nil error. Intended for the /readyz endpoint to distinguish "started but warming up" from "fully ready to serve traffic".

Each check is bounded by the health timeout to prevent a hung ReadyChecker from blocking the /readyz endpoint indefinitely. Before each iteration, the caller's context is also checked — if the /readyz handler is using a bounded ctx (as the HealthComponent does), hitting that deadline aborts the remaining probes instead of letting total latency grow with the component count.

Components that don't implement ReadyChecker are assumed ready. Safe to call concurrently after Start.

func (*Registry) RecordInitDuration

func (r *Registry) RecordInitDuration(name string, d time.Duration)

RecordInitDuration stores the Init duration for a component so it can be reported via DebugInfo. Called by the registry itself during Start — not intended for external use.

func (*Registry) Register

func (r *Registry) Register(c Component)

Register adds a Component to the Registry. Components must be registered before Start is called; registration after Start panics. Duplicate names also panic — a name collision is a programming error that should fail at startup, not return an error upward.

func (*Registry) Reload

func (r *Registry) Reload(ctx context.Context, opts ...ReloadOption) error

Reload calls Reload on every Reloadable Component in dependency order. Errors are collected (not short-circuited) and returned joined — a single component failing to absorb new config should not prevent its peers from trying.

Events fired:

  • EventBeforeReload before the first Reload
  • EventAfterReload after every Reload returns

func (*Registry) SetCloseTimeout

func (r *Registry) SetCloseTimeout(d time.Duration)

SetCloseTimeout sets the per-component Close timeout. When a component's Close exceeds this duration, the context is cancelled and the error is recorded, allowing the remaining components to proceed with their Close. If a component implements CloseTimeouter, its value takes precedence. Zero disables the timeout (the default).

func (*Registry) SetDefaultInitTimeout

func (r *Registry) SetDefaultInitTimeout(d time.Duration)

SetDefaultInitTimeout sets the per-component Init timeout. If a component implements InitTimeouter, its value takes precedence. Zero disables the timeout (the default).

func (*Registry) SetHealthTimeout

func (r *Registry) SetHealthTimeout(d time.Duration)

SetHealthTimeout sets the per-probe timeout for Health checks. Each Healther runs concurrently and is given at most this duration. Zero disables the timeout (the default).

func (*Registry) SetHookTimeout

func (r *Registry) SetHookTimeout(d time.Duration)

SetHookTimeout sets the aggregate timeout for lifecycle hook execution. When set, EventBeforeStop and EventBeforeReload hooks are bounded by this duration — a slow hook cannot block the shutdown sequence past the Kubernetes terminationGracePeriod. Zero disables the timeout (the default).

func (*Registry) SetReloadTimeout

func (r *Registry) SetReloadTimeout(d time.Duration)

SetReloadTimeout sets the per-component Reload timeout. When a component's Reload exceeds this duration, the context is cancelled and the error is recorded, allowing the remaining components to proceed with their Reload. If a component implements ReloadTimeouter, its value takes precedence. Zero disables the timeout (the default).

func (*Registry) SetStopTimeout

func (r *Registry) SetStopTimeout(d time.Duration)

SetStopTimeout overrides the timeout used when rolling back components after an Init or Migrate failure. Default is 30s.

func (*Registry) Start

func (r *Registry) Start(ctx context.Context) error

Start Init's every registered Component in dependency order. On any Init error, already-initialised Components are Close'd in reverse order and the error is returned. Start also runs Migrate for Components implementing Migratable, immediately after each Init.

Events fired:

  • EventBeforeStart before the first Init
  • EventAfterStart after every Init (and Migrate) succeeded

Hook errors during EventBeforeStart abort Start without any Init; errors during EventAfterStart are joined and returned alongside the nominally-successful startup (Components stay running).

func (*Registry) StartOnly

func (r *Registry) StartOnly(ctx context.Context, names ...string) error

StartOnly initialises only the named components and their transitive dependencies. Components not in the transitive closure are skipped. This is intended for integration tests that need a working subset of the application (e.g. "db" + "cache") without starting HTTP servers, auth modules, or other irrelevant components.

The returned Registry behaves like a normal started Registry: Stop closes only the Init'd subset, Health/ReadyCheck operate on the started components, and Get returns nil for components outside the subset.

Example:

reg := component.New(cfg, logger)
reg.Register(&DBComponent{...})
reg.Register(&CacheComponent{...})  // Dependencies: ["redis"]
reg.Register(&RedisComponent{...})
reg.Register(&HTTPComponent{...})

// Start only cache + its transitive deps (redis).
err := reg.StartOnly(ctx, "cache")
// → redis Init'd, cache Init'd; DB and HTTP untouched.

func (*Registry) StartedComponents

func (r *Registry) StartedComponents() []Component

StartedComponents returns only the components that successfully completed Init (and Migrate), in topological start order. Optional components that failed Init/Migrate are excluded. This is the correct source for Health probes and Router mounting — probing or mounting a component that never Init'd risks panics on nil state. Safe to call after Start from any goroutine.

func (*Registry) Stop

func (r *Registry) Stop(ctx context.Context) error

Stop Close's every successfully-started Component in reverse dependency order. Components at the same topological level are Close'd in parallel (mirroring the parallel Init pattern in Start); levels are processed in reverse order so dependents close before their dependencies.

Events fired:

  • EventBeforeStop before the first Close
  • EventAfterStop after every Close returns

Safe to call even after a partial Start failure; only the components that successfully Init'd get Close'd. Safe to call multiple times (subsequent calls are no-ops).

func (*Registry) Verify

func (r *Registry) Verify() error

Verify validates the dependency graph without initialising any components. It checks for: duplicate names, missing dependencies, self-dependencies, and cycles. Returns nil when the graph is valid.

Intended for dev-time CLI checks (e.g. `chok verify`) so developers get fast feedback on wiring errors without waiting for real Init.

Two checks are performed:

  1. topoSort — validates the dependency graph (cycles, unknown deps, self-deps).
  2. DepsValidator — every component implementing ValidateDeps is called with the Kernel so it can assert that declared runtime prerequisites (env vars, paths, sibling component presence) are in place. Errors from both phases are joined.

type ReloadOption

type ReloadOption func(*reloadConfig)

ReloadOption configures a Reload call.

func WithReloadChangedSections

func WithReloadChangedSections(sections map[string]bool) ReloadOption

WithReloadChangedSections passes the per-section diff map so components can check SectionChanged(ctx, key) to skip work when their specific config section didn't change.

func WithReloadConfigChanged

func WithReloadConfigChanged(changed bool) ReloadOption

WithConfigChanged marks whether the config file actually changed during this reload cycle. Components can check component.ConfigChanged(ctx) to skip expensive re-initialization when no config change occurred.

type ReloadTimeouter

type ReloadTimeouter interface {
	ReloadTimeout() time.Duration
}

ReloadTimeouter is implemented by components that need a custom Reload timeout. When a component's Reload exceeds this duration, the context passed to Reload is cancelled and the error is recorded.

Components that don't implement this interface use the Registry's default reload timeout (see Registry.SetReloadTimeout).

type Reloadable

type Reloadable interface {
	Reload(ctx context.Context) error
}

Reloadable is implemented by components that support config hot-reload. Called by Registry.Reload after the config store has been refreshed. The component should re-read its slice of the config and apply whatever is safely swappable at runtime (log level, cache TTL, rate-limit quota). Non-reloadable properties (listen address, DB DSN) should be ignored with a warning log line.

type Router

type Router interface {
	Mount(router any) error
}

Router is implemented by components that mount HTTP routes. The Registry calls Mount during Init for every Router with a Router-capable HTTP server provided in the Kernel. The concrete router type is intentionally left as any here so this package stays free of a gin import; downstream (server component) will assert the concrete type.

Jump to

Keyboard shortcuts

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