Skip to content

Commit

Permalink
Merge branch 'master' into release
Browse files Browse the repository at this point in the history
  • Loading branch information
sywhang authored May 8, 2023
2 parents 0cebee0 + 7174fde commit 15b566c
Show file tree
Hide file tree
Showing 11 changed files with 190 additions and 32 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.19.3](https://github.com/uber-go/fx/compare/v1.19.2...v1.19.3) - 2023-04-17

### Changed
- Fixed several typos in docs.
- WASM build support.
- Annotating In and Out structs with From/As annotations generated invalid results.
The annotation check now blocks this.

### Deprecated
- Deprecate `ShutdownTimeout` option.

## [1.19.2](https://github.com/uber-go/fx/compare/v1.19.1...v1.19.2) - 2023-02-21

### Changed
Expand Down
6 changes: 3 additions & 3 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -574,20 +574,20 @@ func (app *App) Run() {
// Historically, we do not os.Exit(0) even though most applications
// cede control to Fx with they call app.Run. To avoid a breaking
// change, never os.Exit for success.
if code := app.run(app.Wait()); code != 0 {
if code := app.run(app.Wait); code != 0 {
app.exit(code)
}
}

func (app *App) run(done <-chan ShutdownSignal) (exitCode int) {
func (app *App) run(done func() <-chan ShutdownSignal) (exitCode int) {
startCtx, cancel := app.clock.WithTimeout(context.Background(), app.StartTimeout())
defer cancel()

if err := app.Start(startCtx); err != nil {
return 1
}

sig := <-done
sig := <-done()
app.log().LogEvent(&fxevent.Stopping{Signal: sig.Signal})
exitCode = sig.ExitCode

Expand Down
2 changes: 1 addition & 1 deletion app_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func TestAppRun(t *testing.T) {
wg.Add(1)
go func() {
defer wg.Done()
app.run(done)
app.run(func() <-chan ShutdownSignal { return done })
}()

done <- ShutdownSignal{Signal: _sigINT}
Expand Down
1 change: 1 addition & 0 deletions docs/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,6 @@ module.exports = {
'@vuepress/plugin-medium-zoom',
'fulltext-search',
'vuepress-plugin-mermaidjs',
'vuepress-plugin-code-copy',
]
}
3 changes: 2 additions & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
},
"dependencies": {
"cacheable-request": "10.2.7",
"got": "^10.3.0"
"got": "^10.3.0",
"vuepress-plugin-code-copy": "^1.0.6"
}
}
5 changes: 5 additions & 0 deletions docs/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8990,6 +8990,11 @@ vuepress-html-webpack-plugin@^3.2.0:
toposort "^1.0.0"
util.promisify "1.0.0"

vuepress-plugin-code-copy@^1.0.6:
version "1.0.6"
resolved "https://registry.yarnpkg.com/vuepress-plugin-code-copy/-/vuepress-plugin-code-copy-1.0.6.tgz#6431dab764b48b5b203e4936d98b1943651ce4ad"
integrity sha512-FiqwMtlb4rEsOI56O6sSkekcd3SlESxbkR2IaTIQxsMOMoalKfW5R9WlR1Pjm10v6jmU661Ex8MR11k9IzrNUg==

vuepress-plugin-container@^2.0.2:
version "2.1.5"
resolved "https://registry.yarnpkg.com/vuepress-plugin-container/-/vuepress-plugin-container-2.1.5.tgz#37fff05662fedbd63ffd3a5463b2592c7a7f3133"
Expand Down
54 changes: 54 additions & 0 deletions internal/e2e/shutdowner_wait_exitcode/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// 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 main

import (
"context"
"log"
"os"
"time"

"go.uber.org/fx"
)

func main() {
app := fx.New(
fx.Invoke(func(shutdowner fx.Shutdowner) error {
shutdowner.Shutdown(fx.ExitCode(20))
return nil
}),
)

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if err := app.Start(ctx); err != nil {
log.Fatal(err)
}

sig := <-app.Wait()

if err := app.Stop(ctx); err != nil {
log.Fatal(err)
}

os.Exit(sig.ExitCode)
}
72 changes: 72 additions & 0 deletions internal/e2e/shutdowner_wait_exitcode/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// 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 main

import (
"os"
"os/exec"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/fx/internal/testutil"
)

// Hijacks the test binary so that the test can run main() as a subprocess
// instead of trying to compile the program and run it directly.
func TestMain(m *testing.M) {
// If the test binary is named "app", then we're running as a subprocess.
// Otherwise, run the tests.
switch filepath.Base(os.Args[0]) {
case "app":
main()
os.Exit(0)
default:
os.Exit(m.Run())
}
}

// Verifies that an Fx program running with Run
// exits with the exit code passed to Shutdowner.
//
// Regression test for https://github.com/uber-go/fx/issues/1074.
func TestShutdownExitCode(t *testing.T) {
exe, err := os.Executable()
require.NoError(t, err)

out := testutil.WriteSyncer{T: t}

// Run the test binary with the name 'app' so that it runs main().
cmd := exec.Command(exe)
cmd.Args[0] = "app"
cmd.Stdout = &out
cmd.Stderr = &out

// The program should exit with code 20.
err = cmd.Run()
require.Error(t, err)

var exitErr *exec.ExitError
require.ErrorAs(t, err, &exitErr)

assert.Equal(t, 20, exitErr.ExitCode())
}
27 changes: 5 additions & 22 deletions shutdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
package fx

import (
"context"
"time"
)

Expand Down Expand Up @@ -57,49 +56,33 @@ func ExitCode(code int) ShutdownOption {

type shutdownTimeoutOption time.Duration

func (to shutdownTimeoutOption) apply(s *shutdowner) {
s.shutdownTimeout = time.Duration(to)
}
func (shutdownTimeoutOption) apply(*shutdowner) {}

var _ ShutdownOption = shutdownTimeoutOption(0)

// ShutdownTimeout is a [ShutdownOption] that allows users to specify a timeout
// for a given call to Shutdown method of the [Shutdowner] interface. As the
// Shutdown method will block while waiting for a signal receiver relay
// goroutine to stop.
//
// Deprecated: This option has no effect. Shutdown is not a blocking operation.
func ShutdownTimeout(timeout time.Duration) ShutdownOption {
return shutdownTimeoutOption(timeout)
}

type shutdowner struct {
app *App
exitCode int
shutdownTimeout time.Duration
app *App
exitCode int
}

// Shutdown broadcasts a signal to all of the application's Done channels
// and begins the Stop process. Applications can be shut down only after they
// have finished starting up.
// In practice this means Shutdowner.Shutdown should not be called from an
// fx.Invoke, but from a fx.Lifecycle.OnStart hook.
func (s *shutdowner) Shutdown(opts ...ShutdownOption) error {
for _, opt := range opts {
opt.apply(s)
}

ctx := context.Background()

if s.shutdownTimeout != time.Duration(0) {
c, cancel := context.WithTimeout(
context.Background(),
s.shutdownTimeout,
)
defer cancel()
ctx = c
}

defer s.app.receivers.Stop(ctx)

return s.app.receivers.Broadcast(ShutdownSignal{
Signal: _sigTERM,
ExitCode: s.exitCode,
Expand Down
42 changes: 41 additions & 1 deletion shutdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,46 @@ func TestShutdown(t *testing.T) {

assert.NoError(t, s.Shutdown(fx.ExitCode(2), fx.ShutdownTimeout(time.Second)))
})

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

app := fxtest.New(
t,
fx.Invoke(func(s fx.Shutdowner) {
s.Shutdown()
}),
)

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

require.NoError(t, app.Start(ctx), "error starting app")
defer app.Stop(ctx)
select {
case <-ctx.Done():
assert.Fail(t, "app did not shutdown in time")
case <-app.Wait():
// success
}
})

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

var shutdowner fx.Shutdowner
app := fxtest.New(
t,
fx.Populate(&shutdowner),
)

for i := 0; i < 10; i++ {
app.RequireStart()
shutdowner.Shutdown(fx.ExitCode(i))
assert.Equal(t, i, (<-app.Wait()).ExitCode, "run %d", i)
app.RequireStop()
}
})
}

func TestDataRace(t *testing.T) {
Expand All @@ -138,7 +178,7 @@ func TestDataRace(t *testing.T) {
t,
fx.Populate(&s),
)
require.NoError(t, app.Start(context.Background()), "error starting app")
defer app.RequireStart().RequireStop()

const N = 50
ready := make(chan struct{}) // used to orchestrate goroutines for Done() and ShutdownOption()
Expand Down
6 changes: 3 additions & 3 deletions signal.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ func (recv *signalReceivers) Start(ctx context.Context) {
return
}

recv.last = nil
recv.finished = make(chan struct{}, 1)
recv.shutdown = make(chan struct{}, 1)
recv.notify(recv.signals, os.Interrupt, _sigINT, _sigTERM)
Expand All @@ -135,11 +134,12 @@ func (recv *signalReceivers) Stop(ctx context.Context) error {
close(recv.finished)
recv.shutdown = nil
recv.finished = nil
recv.last = nil
return nil
}
}

func (recv *signalReceivers) Done() chan os.Signal {
func (recv *signalReceivers) Done() <-chan os.Signal {
recv.m.Lock()
defer recv.m.Unlock()

Expand All @@ -157,7 +157,7 @@ func (recv *signalReceivers) Done() chan os.Signal {
return ch
}

func (recv *signalReceivers) Wait() chan ShutdownSignal {
func (recv *signalReceivers) Wait() <-chan ShutdownSignal {
recv.m.Lock()
defer recv.m.Unlock()

Expand Down

0 comments on commit 15b566c

Please sign in to comment.