master
go 56 lines 1.01 KB
Raw
1 package node
2
3 import (
4 "context"
5 "errors"
6
7 "go.uber.org/fx"
8 )
9
10 type lcStartStop struct {
11 fx.In
12
13 LC fx.Lifecycle
14 }
15
16 // Append wraps a function into a fx.Hook and appends it to the fx.Lifecycle.
17 func (lcss *lcStartStop) Append(f func() func()) {
18 // Hooks are guaranteed to run in sequence. If a hook fails to start, its
19 // OnStop won't be executed.
20 var stopFunc func()
21
22 lcss.LC.Append(fx.Hook{
23 OnStart: func(ctx context.Context) error {
24 if ctx.Err() != nil {
25 return nil
26 }
27 stopFunc = f()
28 return nil
29 },
30 OnStop: func(ctx context.Context) error {
31 if ctx.Err() != nil {
32 return nil
33 }
34 if stopFunc == nil { // Theoretically this shouldn't ever happen
35 return errors.New("lcStatStop: stopFunc was nil")
36 }
37 stopFunc()
38 return nil
39 },
40 })
41 }
42
43 func maybeProvide(opt any, enable bool) fx.Option {
44 if enable {
45 return fx.Provide(opt)
46 }
47 return fx.Options()
48 }
49
50 // nolint unused
51 func maybeInvoke(opt any, enable bool) fx.Option {
52 if enable {
53 return fx.Invoke(opt)
54 }
55 return fx.Options()
56 }