Skip to content

Commit

Permalink
log shutdown functions after application is shutdown and call shutdow…
Browse files Browse the repository at this point in the history
…n listeners in creating application in case of failure
  • Loading branch information
mrsoftware committed Aug 3, 2024
1 parent 7029867 commit c881be4
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions vabastegi.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@ type Provider[T any] func(context.Context, *App[T]) error
type App[T any] struct {
waitGroup sync.WaitGroup
errList []error
onShutdown []func(ctx context.Context) error
onShutdown []shoutDown
Hub T
options Options
backgroundTasksCount int
}

type shoutDown struct {
fn func(ctx context.Context) error
name string
}

// New instance of App Dependency management.
func New[T any](options ...Option) *App[T] {
app := App[T]{options: Options{}}
Expand Down Expand Up @@ -50,17 +55,22 @@ func (a *App[T]) UpdateOptions(options ...Option) {
// Builds the dependency structure of your app.
func (a *App[T]) Builds(ctx context.Context, providers ...Provider[T]) error {
for _, provider := range providers {
if err := a.Build(ctx, provider); err != nil {
return err
err := a.Build(ctx, provider)
if err == nil {
continue
}

a.Shutdown(ctx, "Provider Failure")

return err
}

return nil
}

// Build use the provider to set a dependency.
func (a *App[T]) Build(ctx context.Context, provider Provider[T]) (err error) {
logMessage := a.getProviderName(provider)
logMessage := a.getFuncName(provider, 0)

defer func() {
if err != nil {
Expand Down Expand Up @@ -103,10 +113,12 @@ func (a *App[T]) Wait() error {

// Shutdown ths application.
func (a *App[T]) Shutdown(ctx context.Context, reason string) {
a.options.Logger.Infof("Shutting down( %s ) ...", reason)
a.options.Logger.Infof("Shutting Down( %s ) ...", reason)

for _, shutdown := range a.onShutdown {
a.options.Logger.Infof("Shutting Down %s", shutdown.name)

for i := len(a.onShutdown) - 1; i >= 0; i-- {
if err := a.onShutdown[i](ctx); err != nil {
if err := shutdown.fn(ctx); err != nil {
a.errList = append(a.errList, err)
}
}
Expand All @@ -118,13 +130,13 @@ func (a *App[T]) Shutdown(ctx context.Context, reason string) {

// OnShutdown register any method for Shutdown method.
func (a *App[T]) OnShutdown(fn func(ctx context.Context) error) {
a.onShutdown = append(a.onShutdown, fn)
a.onShutdown = append(a.onShutdown, shoutDown{fn: fn, name: a.getFuncName(fn, 1)})
}

func (a *App[T]) getProviderName(creator interface{}) string {
func (a *App[T]) getFuncName(creator interface{}, index int) string {
parts := strings.Split(runtime.FuncForPC(reflect.ValueOf(creator).Pointer()).Name(), ".")

return parts[len(parts)-1]
return parts[len(parts)-(1+index)]
}

func (a *App[T]) registerGracefulShutdown() {
Expand Down

0 comments on commit c881be4

Please sign in to comment.