kubo/core/node/helpers.go
Andrew Gillis 3a1b8eed0f
refactor: update to boxo without goprocess (#10567)
* chore: update to boxo without goprocess
* Use boxo fix for registering metrics
* chore: switch to boxo main with PR 723

---------

Co-authored-by: Marcin Rataj <lidel@lidel.org>
2024-11-19 18:04:22 +01:00

69 lines
1.3 KiB
Go

package node
import (
"context"
"errors"
"github.com/jbenet/goprocess"
"go.uber.org/fx"
)
type lcStartStop struct {
fx.In
LC fx.Lifecycle
}
// Append wraps a function into a fx.Hook and appends it to the fx.Lifecycle.
func (lcss *lcStartStop) Append(f func() func()) {
// Hooks are guaranteed to run in sequence. If a hook fails to start, its
// OnStop won't be executed.
var stopFunc func()
lcss.LC.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
if ctx.Err() != nil {
return nil
}
stopFunc = f()
return nil
},
OnStop: func(ctx context.Context) error {
if ctx.Err() != nil {
return nil
}
if stopFunc == nil { // Theoretically this shouldn't ever happen
return errors.New("lcStatStop: stopFunc was nil")
}
stopFunc()
return nil
},
})
}
func maybeProvide(opt interface{}, enable bool) fx.Option {
if enable {
return fx.Provide(opt)
}
return fx.Options()
}
// nolint unused
func maybeInvoke(opt interface{}, enable bool) fx.Option {
if enable {
return fx.Invoke(opt)
}
return fx.Options()
}
// baseProcess creates a goprocess which is closed when the lifecycle signals it to stop
func baseProcess(lc fx.Lifecycle) goprocess.Process {
p := goprocess.WithParent(goprocess.Background())
lc.Append(fx.Hook{
OnStop: func(_ context.Context) error {
return p.Close()
},
})
return p
}