slice

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2021 License: MIT Imports: 16 Imported by: 1

README

Slice (Work in progress)

Documentation Release Build Status Code Coverage

Problem

During the process of writing software in the team, you develop a certain style and define standards that meet the requirements for this software. These standards grow into libraries and frameworks. This is our approach based on interface-based programming and modular programming.

Overview

package main

import (
	"github.com/goava/slice"
	"github.com/goava/di"
	// imports omitted
)

func main() {
	slice.Run(
		slice.WithName("grpc-service"),
		slice.WithBundles(
			logging.Bundle,
			monitoring.Bundle,
			grpc.Bundle,
		),
		slice.WithComponents(
			slice.Provide(NewDispatcher, di.As(new(slice.Dispatcher))),
			slice.Provide(grpcsrv.NewService, di.As(new(grpc.Service))),
		),
	)
}

Minimal start

The minimum that you need to run the application on slice.

Set application name

Use slice.WithName("your name") to specify the application name.

slice.Run(
    slice.WithName("sliced"),
    // ...
)

Check application environment

Use environment variable ENV to specify the application environment. The value can be any string. Environments that have a prefix dev will be recognized as a development environment. Others will be recognized as production.

Provide application dispatcher

Provide your own slice.Dispatcher implementation:

slice.Run(
    slice.WithName("sliced"),
    slice.WithComponents(
        slice.Provide(NewDispatcher, di.As(new(slice.Dispatcher))),
    ),
)

How it works

Application lifecycle

Initialization
  • Initializes slice.StdLogger
  • Checks application name
  • Initializes slice.Context
  • Parses environment variables:
    • ENV
    • DEBUG
  • Provide slice.Env
  • Initializes slice.Info
  • Checks bundle acyclic and sort dependencies
  • Validates component signatures
Configuring
  • Resolves slice.ParameterParser
  • Collects parameters
  • Checks --parameters flag
  • Provides parameters
  • Resolves slice.Logger
Starting
  • Check dispatchers exists
  • Sets StartTimeout and ShutdownTimeout
  • Runs interrupt signal catcher
  • Invokes BeforeStart bundle hooks
  • Resolves dispatchers
Running
  • Run dispatchers
Shutdown
  • Invokes BeforeShutdown bundle hooks in reverse order

Lifecycle details

Parameter parsing

Applications created with slice support parameter parsing. By default, it's processed by envconfig.

You can use your own parameter parser. To do this, implement the ParameterParser interface and use it using the WithParameterParser() or by setting the ParameterParser field of the Application.

You can print all parameters by using <binary-name> --parameters. Example output with default parameter parser and following structure:

// Parameters contains application configuration.
type Parameters struct {
	Addr         string        `envconfig:"addr" required:"true" desc:"Server address"`
	ReadTimeout  time.Duration `envconfig:"read_timeout" required:"true" desc:"Server read timeout"`
	WriteTimeout time.Duration `envconfig:"write_timeout" required:"true" desc:"Server write timeout"`
}

Output:

KEY              TYPE        DEFAULT    REQUIRED    DESCRIPTION
ADDR             String                 true        Server address
READ_TIMEOUT     Duration               true        Server read timeout
WRITE_TIMEOUT    Duration               true        Server write timeout

Components

Default components

slice.Context

A Context carries a deadline, a cancellation signal, and other values across API boundaries.

slice.Info

Info contains information about application: name, env, debug.

User components

TBD

Bundle components

TBD

References

Documentation

Index

Constants

View Source
const DefaultTableFormat = `{{range .}}{{usage_key .}}	{{usage_type .}}	{{usage_default .}}	{{usage_required .}}	{{usage_description .}}
{{end}}`

DefaultTableFormat constant to use to display usage in a tabular format

Variables

This section is empty.

Functions

func Run

func Run(options ...Option)

Run creates and runs application with default shutdown flow (SIGTERM, SIGINT).

Types

type Application

type Application struct {
	Name            string
	Prefix          string
	Parameters      []Parameter
	Dispatcher      Dispatcher
	Bundles         []Bundle
	StartTimeout    time.Duration
	ShutdownTimeout time.Duration
	Logger          Logger
	ParameterParser ParameterParser
	// contains filtered or unexported fields
}

Application is a control part of application.

func New

func New(options ...Option) *Application

New creates slice application with provided options.

func (*Application) Start

func (app *Application) Start() error

Start starts application.

func (*Application) Stop

func (app *Application) Stop()

Stop stops application.

type Bundle

type Bundle struct {
	Name       string
	Parameters []Parameter
	Components []ComponentOption
	Hooks      []Hook
	Bundles    []Bundle
}

A Bundle is a separate unit of application.

type ComponentOption added in v0.4.0

type ComponentOption interface {
	// contains filtered or unexported methods
}

ComponentOption modifies application components.

func Group added in v0.5.0

func Group(options ...ComponentOption) ComponentOption

Group groups component options.

func Provide added in v0.4.0

func Provide(constructor di.Constructor, options ...di.ProvideOption) ComponentOption

Provide returns container option that provides to container reliable way to build type. The constructor will be invoked lazily on-demand. For more information about constructors see di.Constructor interface. di.ProvideOption can add additional behavior to the process of type resolving.

func Supply added in v0.4.0

func Supply(value di.Value, options ...di.ProvideOption) ComponentOption

Supply provides value as is.

type Context

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

Context is a slice mutable context.

func NewContext

func NewContext(ctx context.Context) *Context

NewContext creates new context.

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context interface.

func (*Context) Done

func (c *Context) Done() <-chan struct{}

Done implements context.Context interface.

func (*Context) Err

func (c *Context) Err() error

Err implements context.Context interface.

func (*Context) Join

func (c *Context) Join(ctx context.Context) context.Context

Join merges two contexts.

func (*Context) Set

func (c *Context) Set(key interface{}, value interface{})

Set set value to context with key.

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

Value implements context.Context interface.

type Dispatcher

type Dispatcher interface {
	// Run runs your application. Context will be canceled if application get
	// syscall.SIGINT or syscall.SIGTERM. Example implementation handles application
	// shutdown and worker errors:
	//
	// 	func(d *ExampleDispatcher) Run(ctx context.Context) (err error) {
	//		errChan := make(chan error)
	//		go func() {
	//			errChan <- d.Worker.Start()
	//		}
	// 		select {
	//		// application shutdown
	// 		case <-ctx.Done():
	//			return ctx.Err()
	//		case err = <-errChan:
	// 		}
	//		return err
	// 	}
	Run(ctx context.Context) (err error)
}

Dispatcher controls application lifecycle.

type Env

type Env string

Env

func (Env) IsDev

func (e Env) IsDev() bool

IsDev is a helper function to check whether app is running in Dev mode

func (Env) IsTest added in v0.4.0

func (e Env) IsTest() bool

IsTest is a helper function to check whether app is running in Dev mode

func (Env) String

func (e Env) String() string

String converts environment value to predefined strings.

type Hook

type Hook struct {
	// BeforeStart invokes function before application start.
	BeforeStart di.Invocation
	// BeforeShutdown invokes function before application shutdown.
	BeforeShutdown di.Invocation
}

Hook

type Info

type Info struct {
	// The Application name.
	Name string
	// The raw value of APP_ENV environment variable. Due to the abundance of possible
	// application launch environments, this is a raw value.
	Env Env
	// The debug flag.
	Debug bool
}

The application information.

type Logger

type Logger interface {
	Printf(bundle string, format string, values ...interface{})
	Fatal(err error)
}

Logger

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configure slice.

func ShutdownTimeout added in v0.4.0

func ShutdownTimeout(timeout time.Duration) Option

ShutdownTimeout sets application shutdown timeout.

func StartTimeout

func StartTimeout(timeout time.Duration) Option

StartTimeout sets application boot timeout.

func WithBundles

func WithBundles(bundles ...Bundle) Option

WithBundles registers application bundles.

func WithComponents

func WithComponents(components ...ComponentOption) Option

WithComponents contains component options.

func WithLogger added in v0.4.0

func WithLogger(logger Logger) Option

WithLogger sets application logger.

func WithName

func WithName(name string) Option

WithName sets application name. In case you need to change the name, you can use the APP_NAME environment variable.

func WithParameterParser

func WithParameterParser(parser ParameterParser) Option

WithParameterParser sets parser for application.

func WithParameters

func WithParameters(parameters ...Parameter) Option

WithParameters adds parameters to container. On boot stage all parameter structures will be processed via ParameterParser.

type Parameter

type Parameter interface {
}

Parameter contains application configuration.

type Parameters struct {
	Addr         string        `envconfig:"addr"`
	ReadTimeout  time.Duration `envconfig:"read_timeout"`
	WriteTimeout time.Duration `envconfig:"write_timeout"`
}

type ParameterParser

type ParameterParser interface {
	// Parse parses Parameter fields.
	Parse(prefix string, parameters ...Parameter) error
	// Usage prints parameters usage to stdout.
	Usage(prefix string, parameters ...Parameter) error
}

ParameterParser parses application parameters.

Directories

Path Synopsis
_example

Jump to

Keyboard shortcuts

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