apfel

package
v0.11.5 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2022 License: MIT Imports: 27 Imported by: 3

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

Constants

This section is empty.

Variables

View Source
var BootHelpTemplate = `` /* 531-byte string literal not displayed */
View Source
var DefaultConfigSourceHelpTemplate = `` /* 1066-byte string literal not displayed */
View Source
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.

View Source
var ErrStopIteration = errors.New("stop iteration")

ErrStopIteration should be returned from ForEachMixin when iteration must be stopped.

View Source
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 GetCodec

func GetCodec(extension string) flu.Codec

GetCodec resolves the flu.Codec using the provided extension.

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

func ViaYAML(encoder func(io.Writer) Encoder, decoder func(io.Reader) Decoder) flu.Codec

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

func (b Boot[C]) App(ctx context.Context) *Core[C]

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

type ConfigSource interface {
	ReadInto(ctx context.Context, values internal.AnyMap) error
}

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

type ConfigSourceFunc func(ctx context.Context, values internal.AnyMap) error

ConfigSourceFunc is the ConfigSource functional adapter.

func (ConfigSourceFunc) ReadInto added in v0.10.5

func (f ConfigSourceFunc) ReadInto(ctx context.Context, values internal.AnyMap) error

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) ReadInto added in v0.10.5

func (cs *ConfigSources) ReadInto(ctx context.Context, values internal.AnyMap) error

func (*ConfigSources) String added in v0.10.5

func (cs *ConfigSources) String() string

type Core

type Core[C any] struct {
	syncf.Clock
	// contains filtered or unexported fields
}

Core is the default MixinApp implementation.

func (*Core[C]) Close

func (app *Core[C]) Close() error

Close closes the context and shuts down the application.

func (*Core[C]) Config added in v0.10.5

func (app *Core[C]) Config() C

func (*Core[C]) ForEach added in v0.10.5

func (app *Core[C]) ForEach(ctx context.Context, forEach ForEachMixin[C]) error

func (*Core[C]) Manage

func (app *Core[C]) Manage(ctx context.Context, service any) error

Manage adds the Service to lifecycle management.

func (*Core[C]) String added in v0.10.5

func (app *Core[C]) String() string

func (*Core[C]) Use added in v0.10.5

func (app *Core[C]) Use(ctx context.Context, mixin Mixin[C], mustExist bool) error

func (*Core[C]) Uses added in v0.10.5

func (app *Core[C]) Uses(ctx context.Context, mixins ...Mixin[C])

Uses calls Use for multiple mixins, skipping the ones which returned ErrDisabled on Mixin.Include. It panics on other include errors.

func (*Core[C]) Version added in v0.10.7

func (app *Core[C]) Version() string

type Decoder added in v0.10.5

type Decoder interface{ Decode(any) error }

Decoder may decoded into a value.

type DecoderFunc added in v0.10.5

type DecoderFunc func() Decoder

DecoderFunc is the Decoder functional adapter.

type Encoder added in v0.10.5

type Encoder interface{ Encode(any) error }

Encoder may be encoded a value to.

type EncoderFunc added in v0.10.5

type EncoderFunc func() Encoder

EncoderFunc in the Encoder functional adapter.

type ForEachMixin added in v0.10.5

type ForEachMixin[C any] func(ctx context.Context, mixin Mixin[C]) error

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.

func (*Gorm[C]) Include added in v0.10.5

func (m *Gorm[C]) Include(ctx context.Context, app MixinApp[C]) error

func (*Gorm[C]) String added in v0.10.5

func (m *Gorm[C]) String() string

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.

func (*GormDB[C]) Close added in v0.10.5

func (m *GormDB[C]) Close() error

func (*GormDB[C]) DB added in v0.10.5

func (m *GormDB[C]) DB() *gorm.DB

DB returns the gorm.DB instance.

func (*GormDB[C]) Include added in v0.10.5

func (m *GormDB[C]) Include(ctx context.Context, app MixinApp[C]) error

func (*GormDB[C]) String added in v0.10.5

func (m *GormDB[C]) String() string

type GormDriver added in v0.10.5

type GormDriver func(conn string) gorm.Dialector

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.

func (*Graphite[C]) Include added in v0.11.0

func (g *Graphite[C]) Include(ctx context.Context, app MixinApp[C]) error

func (*Graphite[C]) Registry added in v0.11.0

func (g *Graphite[C]) Registry() me3x.Registry

Registry returns me3x.Registry instance.

func (Graphite[C]) String added in v0.11.0

func (g Graphite[C]) String() string

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.

func (*InputSource) ReadInto added in v0.10.5

func (s *InputSource) ReadInto(ctx context.Context, values internal.AnyMap) error

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).

func (*KeyValueSource) ReadInto added in v0.10.5

func (s *KeyValueSource) ReadInto(ctx context.Context, values internal.AnyMap) error

type Logf added in v0.10.5

type Logf[C LogfContext] struct{}

Logf configures logging via logf package. Implements Mixin interface.

func (*Logf[C]) Include added in v0.10.5

func (m *Logf[C]) Include(ctx context.Context, app MixinApp[C]) error

func (Logf[C]) String added in v0.10.5

func (m Logf[C]) String() string

type LogfConfig added in v0.10.5

type LogfConfig struct {
	Level  logf.Level `` /* 176-byte string literal not displayed */
	Output string     `` /* 130-byte string literal not displayed */
	Rules  []LogfRule `` /* 144-byte string literal not displayed */
}

type LogfContext added in v0.10.5

type LogfContext interface{ LogfConfig() LogfConfig }

LogfContext is the logf application configuration interface.

type LogfRule added in v0.10.5

type LogfRule struct {
	Match  string     `yaml:"match" format:"regex" doc:"Defines a regex which is used for matching logger names." example:"^apfel"`
	Level  logf.Level `` /* 200-byte string literal not displayed */
	Output string     `` /* 137-byte string literal not displayed */
}

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

type MixinAny[C any, V any] struct {
	Value V
}

MixinAny allows to apply dependency management to a value based on its type.

func (MixinAny[C, V]) Include added in v0.11.5

func (m MixinAny[C, V]) Include(ctx context.Context, app MixinApp[C]) error

func (MixinAny[C, V]) String added in v0.11.5

func (m MixinAny[C, V]) String() string

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 PrometheusConfig struct {
	Address    string   `yaml:"address" doc:"Prometheus listener address URL." example:"http://localhost:9090/metrics"`
	Collectors []string `` /* 155-byte string literal not displayed */
}

type PrometheusContext added in v0.10.5

type PrometheusContext interface{ PrometheusConfig() PrometheusConfig }

PrometheusContext is the Prometheus application configuration interface.

Directories

Path Synopsis
Package schema implements OpenAPI 3 compatible JSON Schema which can be generated from structs.
Package schema implements OpenAPI 3 compatible JSON Schema which can be generated from structs.

Jump to

Keyboard shortcuts

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