Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Private Modules #1030

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,13 @@ func New(opts ...Option) *App {
}
app.modules = append(app.modules, app.root)

for _, opt := range opts {
if _, ok := opt.(privateOption); ok {
app.root.private = true
break
}
}

for _, opt := range opts {
opt.apply(app.root)
}
Expand Down
130 changes: 0 additions & 130 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,136 +383,6 @@ func TestNewApp(t *testing.T) {
})
}

func TestPrivateProvide(t *testing.T) {
t.Parallel()

t.Run("CanUsePrivateAndNonPrivateFromOuterModule", func(t *testing.T) {
t.Parallel()

app := fxtest.New(t,
Module("SubModule", Invoke(func(a int, b string) {})),
Provide(func() int { return 0 }, Private),
Provide(func() string { return "" }),
)
app.RequireStart().RequireStop()
})

t.Run("CantUsePrivateFromSubModule", func(t *testing.T) {
t.Parallel()

app := NewForTest(t,
Module("SubModule", Provide(func() int { return 0 }, Private)),
Invoke(func(a int) {}),
)
err := app.Err()
require.Error(t, err)
assert.Contains(t, err.Error(), "missing dependencies for function")
assert.Contains(t, err.Error(), "missing type: int")
})

t.Run("DifferentModulesCanProvideSamePrivateType", func(t *testing.T) {
t.Parallel()

app := fxtest.New(t,
Module("SubModuleA",
Provide(func() int { return 1 }, Private),
Invoke(func(s int) {
assert.Equal(t, 1, s)
}),
),
Module("SubModuleB",
Provide(func() int { return 2 }, Private),
Invoke(func(s int) {
assert.Equal(t, 2, s)
}),
),
Provide(func() int { return 3 }),
Invoke(func(s int) {
assert.Equal(t, 3, s)
}),
)
app.RequireStart().RequireStop()
})
}

func TestPrivateProvideWithDecorators(t *testing.T) {
t.Parallel()

t.Run("DecoratedPublicOrPrivateTypeInSubModule", func(t *testing.T) {
t.Parallel()

runApp := func(private bool) {
provideOpts := []interface{}{func() int { return 0 }}
if private {
provideOpts = append(provideOpts, Private)
}
app := NewForTest(t,
Module("SubModule",
Provide(provideOpts...),
Decorate(func(a int) int { return a + 2 }),
Invoke(func(a int) { assert.Equal(t, 2, a) }),
),
Invoke(func(a int) { assert.Equal(t, 0, a) }),
)
err := app.Err()
if private {
require.Error(t, err)
assert.Contains(t, err.Error(), "missing dependencies for function")
assert.Contains(t, err.Error(), "missing type: int")
} else {
require.NoError(t, err)
}
}

t.Run("Public", func(t *testing.T) { runApp(false) })
t.Run("Private", func(t *testing.T) { runApp(true) })
})

t.Run("DecoratedPublicOrPrivateTypeInOuterModule", func(t *testing.T) {
t.Parallel()

runApp := func(private bool) {
provideOpts := []interface{}{func() int { return 0 }}
if private {
provideOpts = append(provideOpts, Private)
}
app := fxtest.New(t,
Provide(provideOpts...),
Decorate(func(a int) int { return a - 5 }),
Invoke(func(a int) {
assert.Equal(t, -5, a)
}),
Module("Child",
Decorate(func(a int) int { return a + 10 }),
Invoke(func(a int) {
assert.Equal(t, 5, a)
}),
),
)
app.RequireStart().RequireStop()
}

t.Run("Public", func(t *testing.T) { runApp(false) })
t.Run("Private", func(t *testing.T) { runApp(true) })
})

t.Run("CannotDecoratePrivateChildType", func(t *testing.T) {
t.Parallel()

app := NewForTest(t,
Module("Child",
Provide(func() int { return 0 }, Private),
),
Decorate(func(a int) int { return a + 5 }),
Invoke(func(a int) {}),
)
err := app.Err()
require.Error(t, err)
assert.Contains(t, err.Error(), "missing dependencies for function")
assert.Contains(t, err.Error(), "missing type: int")
})
}

func TestWithLoggerErrorUseDefault(t *testing.T) {
// This test cannot be run in paralllel with the others because
// it hijacks stderr.
Expand Down
3 changes: 3 additions & 0 deletions docs/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ To write an Fx module:
No modules that contain "server" will be able to use the resulting
`Config` type because it can only be seen by the "server" module.

You can also pass `fx.Private` to a module to mark all
provided and supplied contents of that module as private.

That's all there's to writing modules.
The rest of this section covers standards and conventions
we've established for writing Fx modules at Uber.
Expand Down
8 changes: 6 additions & 2 deletions fxevent/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,16 @@ func (l *ConsoleLogger) LogEvent(event Event) {
l.logf("HOOK OnStop\t\t%s called by %s ran successfully in %s", e.FunctionName, e.CallerName, e.Runtime)
}
case *Supplied:
var privateStr string
if e.Private {
privateStr = " (PRIVATE)"
}
if e.Err != nil {
l.logf("ERROR\tFailed to supply %v: %+v", e.TypeName, e.Err)
} else if e.ModuleName != "" {
l.logf("SUPPLY\t%v from module %q", e.TypeName, e.ModuleName)
l.logf("SUPPLY%v\t%v from module %q", privateStr, e.TypeName, e.ModuleName)
} else {
l.logf("SUPPLY\t%v", e.TypeName)
l.logf("SUPPLY%v\t%v", privateStr, e.TypeName)
}
case *Provided:
var privateStr string
Expand Down
22 changes: 20 additions & 2 deletions fxevent/console_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,32 @@ func TestConsoleLogger(t *testing.T) {
},
{
name: "Supplied",
give: &Supplied{TypeName: "*bytes.Buffer"},
give: &Supplied{TypeName: "*bytes.Buffer", Private: false},
want: "[Fx] SUPPLY *bytes.Buffer\n",
},
{
name: "Supplied with module",
give: &Supplied{TypeName: "*bytes.Buffer", ModuleName: "myModule"},
give: &Supplied{
TypeName: "*bytes.Buffer",
ModuleName: "myModule",
Private: false,
},
want: "[Fx] SUPPLY *bytes.Buffer from module \"myModule\"\n",
},
{
name: "Supplied privately",
give: &Supplied{TypeName: "*bytes.Buffer", Private: true},
want: "[Fx] SUPPLY (PRIVATE) *bytes.Buffer\n",
},
{
name: "Supplied with module privately",
give: &Supplied{
TypeName: "*bytes.Buffer",
ModuleName: "myModule",
Private: true,
},
want: "[Fx] SUPPLY (PRIVATE) *bytes.Buffer from module \"myModule\"\n",
},
{
name: "SuppliedError",
give: &Supplied{TypeName: "*bytes.Buffer", Err: errors.New("great sadness")},
Expand Down
3 changes: 3 additions & 0 deletions fxevent/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ type Supplied struct {

// Err is non-nil if we failed to supply the value.
Err error

// Private denotes whether the supplied value is [Private] or not
Private bool
}

// Provided is emitted when a constructor is provided to Fx.
Expand Down
1 change: 1 addition & 0 deletions fxevent/zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ func (l *ZapLogger) LogEvent(event Event) {
l.logEvent("supplied",
zap.String("type", e.TypeName),
moduleField(e.ModuleName),
maybeBool("private", e.Private),
)
}
case *Provided:
Expand Down
19 changes: 17 additions & 2 deletions fxevent/zap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,28 @@ func TestZapLogger(t *testing.T) {
},
},
{
name: "Supplied",
give: &Supplied{TypeName: "*bytes.Buffer"},
name: "Supplied",
give: &Supplied{
TypeName: "*bytes.Buffer",
Private: false,
},
wantMessage: "supplied",
wantFields: map[string]interface{}{
"type": "*bytes.Buffer",
},
},
{
name: "PrivateSupply",
give: &Supplied{
TypeName: "*bytes.Buffer",
Private: true,
},
wantMessage: "supplied",
wantFields: map[string]interface{}{
"type": "*bytes.Buffer",
"private": true,
},
},
{
name: "Supplied/Error",
give: &Supplied{TypeName: "*bytes.Buffer", Err: someError},
Expand Down
20 changes: 17 additions & 3 deletions module.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,22 @@ func (o moduleOption) apply(mod *module) {
// 2. Apply child Options on the new module.
// 3. Append it to the parent module.
newModule := &module{
name: o.name,
parent: mod,
app: mod.app,
name: o.name,
parent: mod,
app: mod.app,
private: mod.private,
}

// Look for private option first, if not set through parent
if !newModule.private {
for _, opt := range o.options {
if _, ok := opt.(privateOption); ok {
newModule.private = true
break
}
}
}

for _, opt := range o.options {
opt.apply(newModule)
}
Expand All @@ -83,6 +95,7 @@ type module struct {
parent *module
name string
scope scope
private bool
provides []provide
invokes []invoke
decorators []decorator
Expand Down Expand Up @@ -157,6 +170,7 @@ func (m *module) provide(p provide) {
TypeName: p.SupplyType.String(),
ModuleName: m.name,
Err: m.app.err,
Private: p.Private,
}

default:
Expand Down
58 changes: 58 additions & 0 deletions private.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright (c) 2023 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package fx

type privateOption struct{}

// Private is an [Option] that will mark the scope of a module as private.
// When a module is private, all of its provided and supplied contents
// (including those of inner modules that the private modules contains)
// cannot be accessed by outer modules that contain the private module.
//
// fx.New(
// fx.Module("SubModule",
// fx.Private,
// fx.Supply(5),
// fx.Provide(func() string { return "b"}),
// fx.Invoke(a int, b str) {}, // Runs w/ a = 5, b = "b"
// ),
// fx.Invoke(func(a int) {}), // This will fail
// fx.Invoke(func(b str) {}), // This will also fail
// )
//
// Private can also be used directly as an argument in a call to [Provide] to
// mark only those provided functions as private, rather than a whole module.
//
// fx.New(
// fx.Module("SubModule",
// fx.Provide(func() int { return 0 }, fx.Private),
// fx.Provide(func() string { return "b" }),
// ),
// fx.Invoke(func(a int) {}), // This will fail
// fx.Invoke(func(b str) {}), // This will not
// )
var Private = privateOption{}

func (o privateOption) String() string {
return "fx.Private"
}

func (o privateOption) apply(mod *module) {}
Loading