arrange

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2023 License: Apache-2.0 Imports: 5 Imported by: 15

README

arrange

Arrange is a companion to fx that adds some standard, opinionated APIs for common dependency injection tasks. Refer to the godoc for more information and examples.

Build Status Dependency Updateer codecov.io Go Report Card Quality Gate Status Apache V2 License GitHub Release GoDoc

Summary

Arrange provides some additional utility for microservices built on fx. In particular, arrangehttp provides a lightly opinionated way to bootstrap clients and servers.

Table of Contents

Code of Conduct

This project and everyone participating in it are governed by the XMiDT Code Of Conduct. By participating, you agree to this Code.

Install

go get github.com/xmidt-org/arrange

Contributing

Refer to CONTRIBUTING.md.

Documentation

Index

Examples

Constants

View Source
const DefaultErrorExitCode int = 1

DefaultErrorExitCode is used when no exit code could otherwise be determined for a non-nil error.

Variables

This section is empty.

Functions

func ExitCodeFor added in v0.5.0

func ExitCodeFor(err error, coder ErrorCoder) int

ExitCodeFor provides a standard way of determining the exit code associated with an error. Logic is applied in the following order:

  • If err implements ExitCoder, that exit code is returned
  • If coder is not nil, it is invoked to determine the exit code
  • If err is not nil, DefaultErrorExitCode is returned
  • If none of the above are true, this function returns zero (0).

func ShutdownWhenDone added in v0.5.0

func ShutdownWhenDone[T Task](sh fx.Shutdowner, coder ErrorCoder, task T) (err error)

ShutdownWhenDone executes a context-less task and ensures that the enclosing fx.App is shutdown when the task is complete. Any error, including a nil error, from the task is interpolated into an exit code via ExitCodeFor. That exit code will be available in the fx.ShutdownSignal.

func ShutdownWhenDoneCtx added in v0.5.0

func ShutdownWhenDoneCtx[T TaskCtx](ctx context.Context, sh fx.Shutdowner, coder ErrorCoder, task T) (err error)

ShutdownWhenDoneCtx executes a context-based task and ensures that the enclosing fx.App is shutdown when the task is complete. This function is like ShutdownWhenDone, but for use when a context.Context is needed.

func UseExitCode added in v0.5.0

func UseExitCode(err error, exitCode int) error

UseExitCode returns a new error object that associates an existing error with an exit code. The new error will implement ExitCoder and will have an Unwrap method as described in the errors package.

If err is nil, this function immediately panics so as not to delay a panic until the returned error is used.

Types

type Conditional

type Conditional struct {
}

Conditional is a simple strategy for emitting options into an fx.App container

func If

func If(f bool) *Conditional

If returns a non-nil Conditional if its sole argument is true. This allows one to build up conditional components:

v := viper.New() // initialize
fx.New(
  fx.Supply(v),

  // it's safe to provide this unconditionally as fx will not invoke
  // this constructor unless needed
  arrange.ProvideKey("server.main", ServerConfig{}),

  arrange.If(v.IsSet("server.main")).Then(
    fx.Invoke(
      func(cfg ServerConfig) error {
        // use the configuration to start the server
      },
    ),
  ),

  arrange.IfNot(v.IsSet("server.main")).Then(
    fx.Invoke(
      func() {
        log.Println("Main server not started")
      },
    ),
  ),
)

Note that conditional components do not have to use viper. Any function or series of boolean operators may be used:

feature := flag.Bool("feature", false, "this is a feature flag")
flag.Parse()
fx.New(
  arrange.If(os.Getenv("feature") != "" || feature).Then(
    fx.Provide(
      func() ConditionalComponent {
        return ConditionalComponent{}
      },
    ),
    fx.Invoke(
      func(cc ConditionalComponent) error {
        // start whatever is needed for this conditionally enabled component
      },
    ),
  )
)
Example
condition := true

type Config struct {
	Address string
}

fx.New(
	fx.NopLogger,
	If(condition).Then(
		fx.Supply(Config{
			Address: ":8080",
		}),
		fx.Invoke(
			func(cfg Config) error {
				fmt.Println("address", cfg.Address)
				return nil
			},
		),
	),
)
Output:

address :8080

func IfNot

func IfNot(f bool) *Conditional

IfNot is the boolean inverse of If

func (*Conditional) Then

func (c *Conditional) Then(o ...fx.Option) fx.Option

Then returns all the given options if this Conditional is not nil. If this Conditional is nil, it returns an empty fx.Options.

type ErrorCoder added in v0.5.0

type ErrorCoder func(error) int

ErrorCoder is a strategy type for determining the exit code for an error. Note that this strategy will be invoked with a nil error to allow custom logic for returning exit codes indicating success.

type ExitCoder added in v0.5.0

type ExitCoder interface {
	// ExitCode returns the exit code associated with this error.
	ExitCode() int
}

ExitCoder is an optional interface that an error can implement to supply an associated exit code with that error. Useful particularly with fx.ExitCode or to determine the process exit code upon an error.

type TagBuilder added in v0.5.0

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

TagBuilder is a Fluent Builder for creating sequences of fx struct tags in various situations. This type enforces certain rules that fx requires, e.g. value groups cannot be optional, a component cannot be named and in a group, etc.

Typical use is to start a chain of calls via the Tags function. This yields safer alternative to simply declaring strings:

fx.New(
  fx.Provide(
    fx.Annotate(
      func(dep http.Handler) (*http.Server, error) { ... },
      arrange.Tags().Name("myHandler").ParamTags(),
      arrange.Tags().Name("myServer").ResultTags(),
    ),
  ),
)

func Tags added in v0.5.0

func Tags() *TagBuilder

Tags starts a Fluent Builder chain for creating a sequence of tags.

func (*TagBuilder) Group added in v0.5.0

func (tb *TagBuilder) Group(v string) *TagBuilder

Group adds a `group:"..."` tag to the sequence being built. Groups cannot be optional.

func (*TagBuilder) Name added in v0.5.0

func (tb *TagBuilder) Name(v string) *TagBuilder

Name adds a `name:"..."` tag to the sequence being built. Use OptionalName if a named component should also be optional.

func (*TagBuilder) Optional added in v0.5.0

func (tb *TagBuilder) Optional() *TagBuilder

Optional adds an `optional:"true"` tag to the sequence being built.

func (*TagBuilder) OptionalName added in v0.5.0

func (tb *TagBuilder) OptionalName(v string) *TagBuilder

OptionalName adds a `name:"..." optional:"true"` tag to the sequence being built.

func (*TagBuilder) ParamTags added in v0.5.0

func (tb *TagBuilder) ParamTags() fx.Annotation

ParamTags creates an fx.ParamTags annotation using the previously described sequence of tags.

This method does not reset the state of this builder.

func (*TagBuilder) Pop added in v0.5.0

func (tb *TagBuilder) Pop() *TagBuilder

Pop removes the most recent prefix established with Push. If no prefixes are currently in use, this method does nothing.

func (*TagBuilder) Push added in v0.5.0

func (tb *TagBuilder) Push(prefix string) *TagBuilder

Push pushes a new prefix (or, scope) onto this builder. Subsequent names and groups are prefixed with this string, separated by a '.'. For example:

arrange.Tags().Push("foo").Name("bar").ParamTags()

results in a `name="foo.bar"` parameter tag.

If the given prefix is the empty string, then no prefix is applied. This allows temporarily suspending prefixed names and groups during a sequence of tags by doing Push("") followed by Pop() and continuing with the previous prefix.

func (*TagBuilder) ResultTags added in v0.5.0

func (tb *TagBuilder) ResultTags() fx.Annotation

ResultTags creates an fx.ResultTags annotation using the previously described sequence of tags. Note that results cannot be marked as optional. If one of the Optional methods of this builder was used to create a tag in the sequence, an error will short circuit fx.App startup.

This method does not reset the state of this builder.

func (*TagBuilder) Skip added in v0.5.0

func (tb *TagBuilder) Skip() *TagBuilder

Skip adds an empty tag to the sequence of tags under construction. Useful when a parameter or a result doesn't need any tag information, but there are subsequence parameters or results that do.

func (*TagBuilder) StructTags added in v0.5.0

func (tb *TagBuilder) StructTags() (tags []reflect.StructTag)

StructTags creates a sequence of reflect.StructTag objects using the previously described sequence of tags.

This method does not reset the state of this builder.

type Task added in v0.5.0

type Task interface {
	~func() | ~func() error
}

Task is the type that any context-less operation must conform to.

type TaskCtx added in v0.5.0

type TaskCtx interface {
	~func(context.Context) | ~func(context.Context) error
}

TaskCtx is the type that any operation that requires a context must conform to.

Directories

Path Synopsis
Package arrangehttp further extends the notion of unmarshaled components to the idea of building http servers and clients from configuration.
Package arrangehttp further extends the notion of unmarshaled components to the idea of building http servers and clients from configuration.
Package arrangepprof enables pprof functionality bound to an fx.App instance.
Package arrangepprof enables pprof functionality bound to an fx.App instance.
Package arrangetest contains useful unit test utilities for working with dependency injection and client/server lifecycle.
Package arrangetest contains useful unit test utilities for working with dependency injection and client/server lifecycle.
Package arrangetls has basic unmarshaling and external configuration support for HTTP clients and servers created within an uber/fx App.
Package arrangetls has basic unmarshaling and external configuration support for HTTP clients and servers created within an uber/fx App.
internal

Jump to

Keyboard shortcuts

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