Documentation ¶
Overview ¶
Package apfel provides an application context implementation with the support of "mixins" – services which may be used in the context of "dependency injection". "Dependency injection" means the ability not to pass all services dependency directly for initialization, but instead implementing a Mixin interface and calling MixinApp.Use in Mixin.Include implementation in order to get (or create) a mixin dependency from application context.
Index ¶
- Variables
- func Default[C any]() C
- func GetCodec(extension string) flu.Codec
- func GobViaYAML(value any) flu.ValueCodec
- func JSONViaYAML(value any) flu.ValueCodec
- func ViaYAML(encoder func(io.Writer) Encoder, decoder func(io.Reader) Decoder) flu.Codec
- func XMLViaYAML(value any) flu.ValueCodec
- type AfterInclude
- type BeforeInclude
- type Boot
- type ConfigSource
- type ConfigSourceFunc
- type ConfigSources
- type Core
- func (app *Core[C]) Close() error
- func (app *Core[C]) Config() C
- func (app *Core[C]) ForEach(ctx context.Context, forEach ForEachMixin[C]) error
- func (app *Core[C]) Manage(ctx context.Context, service any) error
- func (app *Core[C]) String() string
- func (app *Core[C]) Use(ctx context.Context, mixin Mixin[C], mustExist bool) error
- func (app *Core[C]) Uses(ctx context.Context, mixins ...Mixin[C])
- func (app *Core[C]) Version() string
- type Decoder
- type DecoderFunc
- type Encoder
- type EncoderFunc
- type ForEachMixin
- type Gorm
- type GormConfig
- type GormDB
- type GormDriver
- type GormDrivers
- type Graphite
- type GraphiteConfig
- type GraphiteContext
- type Help
- type InputSource
- type KeyValueSource
- type Logf
- type LogfConfig
- type LogfContext
- type LogfRule
- type Mixin
- type MixinAny
- type MixinApp
- type Prometheus
- type PrometheusConfig
- type PrometheusContext
Constants ¶
This section is empty.
Variables ¶
var BootHelpTemplate = `` /* 531-byte string literal not displayed */
var DefaultConfigSourceHelpTemplate = `` /* 1066-byte string literal not displayed */
var ErrDisabled = errors.New("disabled")
ErrDisabled should be returned from a Mixin.Include when it is disabled for some reason. A warning message will be logged for such mixins in Core.Uses.
var ErrStopIteration = errors.New("stop iteration")
ErrStopIteration should be returned from ForEachMixin when iteration must be stopped.
var ExtensionCodecs = map[string]flu.Codec{ "json": JSONViaYAML, "yaml": flu.YAML, "yml": flu.YAML, "xml": XMLViaYAML, "gob": GobViaYAML, }
ExtensionCodecs is an index of flu.Codecs by their common file extensions.
Functions ¶
func Default ¶ added in v0.11.0
func Default[C any]() C
Default creates a value of type C and fills it with default values based on resolved JSON schema.
func GobViaYAML ¶ added in v0.10.5
func GobViaYAML(value any) flu.ValueCodec
GobViaYAML is encoding/gob "frontend" for ViaYAML.
func JSONViaYAML ¶ added in v0.10.5
func JSONViaYAML(value any) flu.ValueCodec
JSONViaYAML is encoding/json "frontend" for ViaYAML.
func ViaYAML ¶ added in v0.10.5
ViaYAML returns a flu.Codec which performs marshalling and unmarshalling via YAML codec. Marshal steps: marshal value with YAML, decode as YAML into internal.AnyMap and encode the map with encoder function. Unmarshal steps: unmarshal internal.AnyMap with decoder function, marshal it with YAML and unmarshal value as YAML. This provides the ability to use a single tag (yaml) for field declarations for all codecs.
func XMLViaYAML ¶ added in v0.10.5
func XMLViaYAML(value any) flu.ValueCodec
XMLViaYAML is encoding/xml "frontend" for ViaYAML.
Types ¶
type AfterInclude ¶ added in v0.10.5
type AfterInclude[C any] interface { AfterInclude(ctx context.Context, app MixinApp[C], mixin Mixin[C]) error }
AfterInclude is an interface which may be implemented by a Mixin in order to be called after some other Mixin is included (initialized).
type BeforeInclude ¶ added in v0.10.5
type BeforeInclude[C any] interface { BeforeInclude(ctx context.Context, app MixinApp[C], mixin Mixin[C]) error }
BeforeInclude is an interface which may be implemented by a Mixin in order to be called before some other Mixin is included (initialized).
type Boot ¶ added in v0.10.5
type Boot[C any] struct { // Name is the application name. // It is also used as environment variable prefix for reading configuration. Name string // Version is the application version. // Generally you do not want to statically set it, // but instead define a variable and set via ldflags during build. Version string // Desc is the optional application description. // It will be printed along with BootHelpTemplate when using `--help` CLI option. Desc string // Clock is the optional clock which should be used for the application instance. // If not set, syncf.DefaultClock will be used (basically time.Now()). Clock syncf.Clock // Stdout is the optional application stdout. // If not set, os.Stdout will be used. Stdout flu.Output // Source is the optional ConfigSource for the application instance. // If not set, DefaultConfigSource will be used. Source ConfigSource // Quit is the optional exit function for calling when common CLI options are processed. // By default, os.Exit(0) is used. Quit func() }
Boot implements common CLI interface (see BootHelpTemplate). It also helps initialize Core instance.
func (Boot[C]) App ¶ added in v0.10.5
App reads configuration properties, processes common "immediate" CLI arguments (see BootHelpTemplate) and sets up a Core instance. Application should not set up anything prior to calling App method, since it may call os.Exit.
Configuration schema is resolved automatically from C structure fields and their tags. You can see LogfConfig or GormConfig for examples on how to define configuration structs and annotate fields. Note that `yaml` tags are always used for marshalling/unmarshalling no matter what the codec is. Also note that schema resolution has some limitations and sometimes a little help is needed. For example, it is recommended to use `example` and/or `default` tags as often as possible, since the framework sometimes fail to resolve JSON type by its Go type (and rightfully so – this is impossible, especially when doing some exotic stuff like marshalling flu.Set into JSON array). Some limitations when filling default values may also apply (you can use `--config.values` and `--config.schema` for debug).
See package schema for more details on schema resolution.
type ConfigSource ¶ added in v0.10.5
ConfigSource implementations read the configuration properties into internal.AnyMap from a configuration source.
func Arguments ¶
func Arguments(args []string, ignores ...string) ConfigSource
Arguments produces a Properties instance for parsing command-line arguments. Ignored configuration options may be specified with ignores vararg. For example, the following command-line arguments:
--appName=test-app --service.name=test-service --service.enabled=true OR SIMPLY --service.enabled --service.threshold=0.05 --service.instances=10 --service.true=enabled --service.10=instances
with Arguments(os.Args[1:]) call would yield the following configuration:
Map{ "appName": "test-app", "service": Map{ "name": "test-service", "enabled": bool(true), "threshold": float64(0.05), "instances": int64(10), bool(true): "enabled", int64(10): "instances", }, }
func DefaultConfigSource ¶ added in v0.11.1
func DefaultConfigSource(appName string) ConfigSource
DefaultConfigSource creates a generally applicable ConfigSource instance which reads configuration properties from stdin (with --config.stdin option), file (with --config.file=<filepath> option, the codec is automatically resolved by filename extension, see ExtensionCodecs), environment variables (with appName_ prefix with all hyphens replaced with underscores), and direct CLI arguments (like --service.timeout=10s). See DefaultConfigSourceHelpTemplate for more info.
func Environ ¶
func Environ(environ []string, prefix string) ConfigSource
Environ produces a Properties instance for parsing configuration from environment variables with the specified prefix. Nested option keys are separated with underscore (_). Options with underscores in the name are not supported. For example, using the following environment variables:
test_appName=test-app test_service_name=test-service test_service_enabled=true test_service_threshold=0.05 test_service_instances=10 test_service_true=enabled test_service_10=instances
with Environ(os.Environ(), "test_") call would yield the following configuration:
Map{ "appName": "test-app", "service": Map{ "name": "test-service", "enabled": bool(true), "threshold": float64(0.05), "instances": int64(10), bool(true): "enabled", int64(10): "instances", }, }
type ConfigSourceFunc ¶ added in v0.10.5
ConfigSourceFunc is the ConfigSource functional adapter.
type ConfigSources ¶ added in v0.10.5
type ConfigSources struct { Name string HelpText string Sources []ConfigSource }
ConfigSources is the umbrella Parser for multiple ConfigSources. It merges the Map from each Parser in the order of appearance into one global Map and returns it as the result. Failures are reported as warnings and do not interrupt execution.
func (*ConfigSources) Help ¶ added in v0.10.5
func (cs *ConfigSources) Help() string
func (*ConfigSources) String ¶ added in v0.10.5
func (cs *ConfigSources) String() string
type Core ¶
Core is the default MixinApp implementation.
func (*Core[C]) ForEach ¶ added in v0.10.5
func (app *Core[C]) ForEach(ctx context.Context, forEach ForEachMixin[C]) error
type DecoderFunc ¶ added in v0.10.5
type DecoderFunc func() Decoder
DecoderFunc is the Decoder functional adapter.
type EncoderFunc ¶ added in v0.10.5
type EncoderFunc func() Encoder
EncoderFunc in the Encoder functional adapter.
type ForEachMixin ¶ added in v0.10.5
ForEachMixin is an iteration function.
type Gorm ¶ added in v0.10.5
type Gorm[C any] struct { // Config will be used for all created gorm.DB instances. Config gorm.Config // Drivers contains supported drivers and dialectors. Drivers GormDrivers }
Gorm is the base gorm.io/gorm application Mixin. It serves as configuration template and supported driver registry.
type GormConfig ¶ added in v0.10.5
type GormConfig struct { DSN string `yaml:"dsn" doc:"Database connection string." examples:"postgresql://user:pass@host:port/db,sqlite::memory:"` Driver string `` /* 132-byte string literal not displayed */ }
GormConfig is the configuration for GormDB.
type GormDB ¶ added in v0.10.5
type GormDB[C any] struct { // Config contains configuration for connecting to the database. // It is required to fill Config before passing the mixin to MixinApp.Use. Config GormConfig // contains filtered or unexported fields }
GormDB is the "frontend" gorm.io/gorm Mixin.
type GormDriver ¶ added in v0.10.5
GormDriver creates a gorm.Dialector from a connection string.
type GormDrivers ¶ added in v0.10.5
type GormDrivers map[string]GormDriver
GormDrivers is a map of GormDrivers and their names.
type Graphite ¶ added in v0.11.0
type Graphite[C GraphiteContext] struct { // contains filtered or unexported fields }
Graphite is the Graphite application Mixin.
type GraphiteConfig ¶ added in v0.10.5
type GraphiteConfig struct { Address string `` /* 166-byte string literal not displayed */ FlushEvery flu.Duration `yaml:"flushEvery,omitempty" format:"duration" doc:"Interval to keep between consequent metric flushes." default:"\"1m\""` HistogramBucketFormat string `` /* 163-byte string literal not displayed */ }
type GraphiteContext ¶ added in v0.10.5
type GraphiteContext interface{ GraphiteConfig() GraphiteConfig }
GraphiteContext is the Graphite application configuration interface.
type Help ¶ added in v0.10.5
type Help interface {
Help() string
}
Help may be implemented by a ConfigSource in order to injection help message into `--help` output.
type InputSource ¶ added in v0.10.5
type InputSource struct { // Args is a collection of command-line arguments (most commonly os.Args[1:]). Args []string // Stdin is the standard input (most commonly os.Stdin). Stdin flu.Input // FileOption is the option which will be used for supplying configuration file paths // (most commonly "config.file" for --config.file=config.yml style arguments). FileOption string // StdinOption is the option which will be used for supplying the stdin configuration codec // (most commonly "config.stdin" for --config.stdin=json style arguments). // If the stdin option is not specified in the argument list, the source will not read stdin. StdinOption string }
InputSource reads configuration file paths as arguments from command line and parses the provided files. The codec is detected based on file extension (see supported extensions in ExtensionCodecs). The source also supports reading the configuration from stdin using the supplied codec. The configuration is merged from all sources, overriding options from respective sources in the order of appearance. This allows for building highly modular configurations with default values. An error (absent file, invalid format, etc.) causes a warning in logs, but does not interrupt execution.
type KeyValueSource ¶ added in v0.10.5
type KeyValueSource struct { // Prefix is an optional prefix for configuration options. // If set, only the options with this prefix are read, // and the prefix is stripped from option key. Prefix string // PathSeparator is used for separating nested configuration keys (for example, service.instance.name contains . as a separator). PathSeparator string // Separator is a key-value separator. Separator string // Lines is a collection of strings containing key-value pairs. Lines []string // Except is a collection of option regexes which should be ignored when reading configuration from Lines. Except colf.Set[string] }
KeyValueSource is used to read configuration as key-value pairs from a collection of string values. Nested option keys are joined using the PathSeparator. Type specification is performed on keys as well as values (and nested objects). Please note that this Parser does not support options with array values. Having a nested and simple value for the same key (for example, APP_OPTIONS=a and APP_OPTIONS_DEBUG=true) will cause a warning and preference of the option with the longest path (converting into Map and overwriting all of its parents).
type Logf ¶ added in v0.10.5
type Logf[C LogfContext] struct{}
Logf configures logging via logf package. Implements Mixin interface.
type LogfConfig ¶ added in v0.10.5
type LogfContext ¶ added in v0.10.5
type LogfContext interface{ LogfConfig() LogfConfig }
LogfContext is the logf application configuration interface.
type Mixin ¶ added in v0.10.5
type Mixin[C any] interface { // String is used to identify mixins in application context. // This should be generally be a constant string which does not depend on implementing struct values. String() string // Include is called when mixin is initialized. // Note that no automatic cleanup is performed on mixins themselves, // implementations are required to call MixinApp.Manage for used resources // in order to schedule their closing on application shutdown. Include(ctx context.Context, app MixinApp[C]) error }
Mixin is a service which may be used in application context. A Mixin will be initialized at most once (when MixinApp.Use is called). This interface serves as a base "dependency injection" unit.
C is the application configuration type (should be struct). Its type bound should be a configuration interface which must be implemented by enclosing application configuration type.
type MixinAny ¶ added in v0.11.5
MixinAny allows to apply dependency management to a value based on its type.
type MixinApp ¶ added in v0.10.5
type MixinApp[C any] interface { syncf.Clock // Version returns the application version. Version() string // Config returns the application configuration. Config() C // Manage schedules the service for closing on application shutdown if service implements io.Closer. Manage(ctx context.Context, service any) error // Use creates or gets a mixin from application context. // If mustExist is set, an error is returned if the mixin is not initialized yet. // A mixin should generally be an empty struct pointer which will be initialized // and put into application context, or an already initialized mixin value from // application context will be copied into this pointer. // // This is the main "dependency injection" entrypoint. Use(ctx context.Context, mixin Mixin[C], mustExist bool) error // ForEach iterates all initialized mixins with a ForEachMixin function. // Iteration stops when ErrStopIteration is returned from the function. ForEach(ctx context.Context, forEach ForEachMixin[C]) error }
MixinApp is the base application interface with Mixin support. C is the application configuration type (should be struct).
type Prometheus ¶ added in v0.11.0
type Prometheus[C PrometheusContext] struct { // contains filtered or unexported fields }
Prometheus is the Prometheus application Mixin.
func (*Prometheus[C]) Include ¶ added in v0.11.0
func (p *Prometheus[C]) Include(ctx context.Context, app MixinApp[C]) error
func (*Prometheus[C]) Registry ¶ added in v0.11.0
func (p *Prometheus[C]) Registry() me3x.Registry
Registry returns the me3x.Registry instance.
func (*Prometheus[C]) String ¶ added in v0.11.0
func (p *Prometheus[C]) String() string
type PrometheusConfig ¶ added in v0.10.5
type PrometheusContext ¶ added in v0.10.5
type PrometheusContext interface{ PrometheusConfig() PrometheusConfig }
PrometheusContext is the Prometheus application configuration interface.