Skip to content

Commit

Permalink
fix: support graceful shutdown (#230)
Browse files Browse the repository at this point in the history
  • Loading branch information
simlecode authored Jul 29, 2022
1 parent 4386d21 commit be2c20e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 11 deletions.
9 changes: 5 additions & 4 deletions api/modules.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"context"
"errors"
"net"
"net/http"

Expand Down Expand Up @@ -55,15 +56,15 @@ func RunAPI(lc fx.Lifecycle, jwtCli *jwt.Client, lst net.Listener, log *log.Logg
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
go func() {
log.Info("Start rpcserver ", lst.Addr())
if err := apiserv.Serve(lst); err != nil {
log.Errorf("Start rpcserver failed: %v", err)
log.Info("start rpcserver ", lst.Addr())
if err := apiserv.Serve(lst); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Errorf("start rpcserver failed: %v", err)
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
return lst.Close()
return apiserv.Shutdown(ctx)
},
})
return nil
Expand Down
17 changes: 13 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,6 @@ func runAction(ctx *cli.Context) error {
}
lst := manet.NetListener(apiListener)

shutdownChan := make(chan struct{})
provider := fx.Options(
fx.Logger(fxLogger{log}),
// prover
Expand All @@ -246,7 +245,6 @@ func runAction(ctx *cli.Context) error {
fx.Provide(func() filestore.FSRepo {
return fsRepo
}),
fx.Supply((ShutdownChan)(shutdownChan)),

fx.Provide(service.NewMessageState),
// db
Expand Down Expand Up @@ -281,21 +279,32 @@ func runAction(ctx *cli.Context) error {
app := fx.New(provider, invoker, apiOption)
if err := app.Start(ctx.Context); err != nil {
// comment fx.NopLogger few lines above for easier debugging
return fmt.Errorf("starting node: %w", err)
return fmt.Errorf("starting app: %w", err)
}

shutdownChan := make(chan struct{})
// wait for exit to complete
finishCh := make(chan struct{})
go func() {
<-shutdownChan

log.Warn("received shutdown")

log.Warn("Shutting down...")
if err := app.Stop(ctx.Context); err != nil {
log.Errorf("graceful shutting down failed: %s", err)
}
log.Warn("Graceful shutdown successful")
log.Info("Graceful shutdown successful")

close(finishCh)
}()

<-app.Done()

shutdownChan <- struct{}{}

<-finishCh

return nil
}

Expand Down
3 changes: 0 additions & 3 deletions modules.go

This file was deleted.

0 comments on commit be2c20e

Please sign in to comment.