Lists provider sets in packages given on the command line, including outputs grouped by what is needed to obtain them. The goose package now exports the loading phase as an API. Example output: https://paste.googleplex.com/5509965720584192 Reviewed-by: Tuo Shan <shantuo@google.com>
goose: Compile-Time Dependency Injection for Go
goose is a compile-time dependency injection framework for Go, inspired by Dagger. It works by using Go code to specify dependencies, then generating code to create those structures, mimicking the code that a user might have hand-written.
Usage Guide
Defining Providers
The primary mechanism in goose is the provider: a function that can
produce a value, annotated with the special goose:provide directive. These
functions are otherwise ordinary Go code.
package foobarbaz
type Foo int
// goose:provide
// ProvideFoo returns a Foo.
func ProvideFoo() Foo {
return 42
}
Providers are always part of a provider set: if there is no provider set
named on the //goose:provide line, then the provider is added to the provider
set with the same name as the function (ProvideFoo, in this case).
Providers can specify dependencies with parameters:
package foobarbaz
type Bar int
// goose:provide SuperSet
// ProvideBar returns a Bar: a negative Foo.
func ProvideBar(foo Foo) Bar {
return Bar(-foo)
}
Providers can also return errors:
package foobarbaz
import (
"context"
"errors"
)
type Baz int
// goose:provide SuperSet
// ProvideBaz returns a value if Bar is not zero.
func ProvideBaz(ctx context.Context, bar Bar) (Baz, error) {
if bar == 0 {
return 0, errors.New("cannot provide baz when bar is zero")
}
return Baz(bar), nil
}
Provider sets can import other provider sets. To add the ProvideFoo set to
SuperSet:
// goose:import SuperSet ProvideFoo
You can also import provider sets in another package, provided that you have a Go import for the package:
// goose:import SuperSet "example.com/some/other/pkg".OtherSet
A provider set reference is an optional import qualifier (either a package name or a quoted import path, as seen above) ending with a dot, followed by the provider set name.
Injectors
An application wires up these providers with an injector: a function that calls providers in dependency order. With goose, you write the injector's signature, then goose generates the function's body.
An injector is declared by writing a function declaration without a body in a
file guarded by a gooseinject build tag. Let's say that the above providers
were defined in a package called example.com/foobarbaz. The following would
declare an injector to obtain a Baz:
//+build gooseinject
package main
import (
"context"
"example.com/foobarbaz"
)
// goose:use foobarbaz.SuperSet
func initializeApp(ctx context.Context) (foobarbaz.Baz, error)
Like providers, injectors can be parameterized on inputs (which then get sent to
providers) and can return errors. Each goose:use directive specifies a
provider set to use in the injection. An injector can have one or more
goose:use directives. goose:use directives use the same syntax as
goose:import to reference provider sets.
You can generate the injector by invoking goose in the package directory:
goose
Or you can add the line //go:generate goose to another file in your package to
use go generate:
go generate
(Adding the line to the injection declaration file will be silently ignored by
go generate.)
goose will produce an implementation of the injector in a file called
goose_gen.go that looks something like this:
// Code generated by goose. DO NOT EDIT.
//+build !gooseinject
package main
import (
"example.com/foobarbaz"
)
func initializeApp(ctx context.Context) (foobarbaz.Baz, error) {
foo := foobarbaz.ProvideFoo()
bar := foobarbaz.ProvideBar(foo)
baz, err := foobarbaz.ProvideBaz(ctx, bar)
if err != nil {
return 0, err
}
return baz, nil
}
As you can see, the output is very close to what a developer would write themselves. Further, there is no dependency on goose at runtime: all of the written code is just normal Go code, and can be used without goose.
Best Practices
goose is still not mature yet, but guidance that applies to Dagger generally applies to goose as well. In particular, when thinking about how to group providers into sets, follow the same guidance as Dagger (provider sets are called modules in Dagger/Guice):
Some [...] bindings will have reasonable alternatives, especially for testing, and others will not. For example, there are likely to be alternative bindings for a type like
AuthManager: one for testing, others for different authentication/authorization protocols.But on the other hand, if the
AuthManagerinterface has a method that returns the currently logged-in user, you might want to [export a provider ofUserthat simply callsCurrentUser()] on theAuthManager. That published binding is unlikely to ever need an alternative.Once you’ve classified your bindings into [...] bindings with reasonable alternatives [and] bindings without reasonable alternatives, consider arranging them into provider sets like this:
- One [provider set] for each [...] binding with a reasonable alternative. (If you are also writing the alternatives, each one gets its own [provider set].) That [provider set] contains exactly one provider.
- All [...] bindings with no reasonable alternatives go into [provider sets] organized along functional lines.
- The [provider sets] should each include the no-reasonable-alternative [provider sets] that require the [...] bindings each provides.
One goose-specific practice though: create one-off types where in Java you would use a binding annotation. For example, if you need to pass a string through the dependency graph, you would create a wrapping type:
type MySQLConnectionString string
Advanced Features
Binding Interfaces
Frequently, dependency injection is used to bind concrete implementations for an interface. goose matches inputs to outputs via type identity, so the inclination might be to create a provider that returns an interface type. However, this would not be idiomatic, since the Go best practice is to return concrete types. Instead, you can declare an interface binding in a provider set:
type Fooer interface {
Foo() string
}
type Bar string
func (b *Bar) Foo() string {
return string(*b)
}
//goose:provide BarFooer
func provideBar() *Bar {
b := new(Bar)
*b = "Hello, World!"
return b
}
//goose:bind BarFooer Fooer *Bar
The syntax is provider set name, interface type, and finally the concrete type. An interface binding does not necessarily need to have a provider in the same set that provides the concrete type.
Optional Inputs
A provider input can be marked optional using goose:optional:
//goose:provide Bar
//goose:optional foo
func provideBar(foo Foo) Bar {
// ...
}
If used as part of an injector that does not bring in the Foo dependency, then
the injector will pass the provider the zero value as the foo argument.
Struct Providers
Structs can also be marked as providers. Instead of calling a function, an
injector will fill in each field using the corresponding provider. For a given
struct type S, this would provide both S and *S. For example, given the
following providers:
type Foo int
type Bar int
//goose:provide Foo
func provideFoo() Foo {
// ...
}
//goose:provide Bar
func provideBar() Bar {
// ...
}
//goose:provide
type FooBar struct {
Foo Foo
Bar Bar
}
A generated injector for FooBar would look like this:
func injectFooBar() FooBar {
foo := provideFoo()
bar := provideBar()
fooBar := FooBar{
Foo: foo,
Bar: bar,
}
return fooBar
}
And similarly if the injector needed a *FooBar.
Like function providers, you can mark dependencies of a struct provider optional
by using the goose:optional directive with the field names.
Cleanup functions
If a provider creates a value that needs to be cleaned up (e.g. closing a file), then it can return a closure to clean up the resource. The injector will use this to either return an aggregated cleanup function to the caller or to clean up the resource if a later provider returns an error.
//goose:provide
func provideFile(log Logger, path Path) (*os.File, func(), error) {
f, err := os.Open(string(path))
if err != nil {
return nil, nil, err
}
cleanup := func() {
if err := f.Close(); err != nil {
log.Log(err)
}
}
return f, cleanup, nil
}
A cleanup function is guaranteed to be called before the cleanup function of any
of the provider's inputs and must have the signature func().
Future Work
- Support for map bindings.
- Support for multiple provider outputs.
- Tighter validation for a provider set (cycles in unused providers goes unreported currently)
- Visualization for provider sets