|
| 1 | +package stopper |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/dipdup-io/workerpool" |
| 6 | + "github.com/dipdup-net/indexer-sdk/pkg/modules" |
| 7 | + "github.com/pkg/errors" |
| 8 | + "github.com/rs/zerolog" |
| 9 | + "github.com/rs/zerolog/log" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + InputName = "signal" |
| 14 | +) |
| 15 | + |
| 16 | +// Module - cancels context of all application if get signal. |
| 17 | +// |
| 18 | +// |----------------| |
| 19 | +// | | |
| 20 | +// -- struct{} -> | MODULE | |
| 21 | +// | | |
| 22 | +// |----------------| |
| 23 | +type Module struct { |
| 24 | + input *modules.Input |
| 25 | + stop context.CancelFunc |
| 26 | + log zerolog.Logger |
| 27 | + g workerpool.Group |
| 28 | +} |
| 29 | + |
| 30 | +func NewModule(cancelFunc context.CancelFunc) Module { |
| 31 | + m := Module{ |
| 32 | + input: modules.NewInput(InputName), |
| 33 | + stop: cancelFunc, |
| 34 | + g: workerpool.NewGroup(), |
| 35 | + } |
| 36 | + m.log = log.With().Str("module", m.Name()).Logger() |
| 37 | + |
| 38 | + return m |
| 39 | +} |
| 40 | + |
| 41 | +func (*Module) Name() string { |
| 42 | + return "stopper" |
| 43 | +} |
| 44 | + |
| 45 | +// Start - |
| 46 | +func (s *Module) Start(ctx context.Context) { |
| 47 | + s.g.GoCtx(ctx, s.listen) |
| 48 | +} |
| 49 | + |
| 50 | +func (s *Module) listen(ctx context.Context) { |
| 51 | + for { |
| 52 | + select { |
| 53 | + case <-ctx.Done(): |
| 54 | + return |
| 55 | + case <-s.input.Listen(): |
| 56 | + log.Info().Msg("stop signal received") |
| 57 | + if s.stop != nil { |
| 58 | + log.Info().Msg("cancelling context...") |
| 59 | + s.stop() |
| 60 | + return |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// Close - |
| 67 | +func (s *Module) Close() error { |
| 68 | + s.g.Wait() |
| 69 | + return s.input.Close() |
| 70 | +} |
| 71 | + |
| 72 | +// Output - |
| 73 | +func (*Module) Output(name string) (*modules.Output, error) { |
| 74 | + return nil, errors.Wrap(modules.ErrUnknownOutput, name) |
| 75 | +} |
| 76 | + |
| 77 | +// Input - |
| 78 | +func (s *Module) Input(name string) (*modules.Input, error) { |
| 79 | + if name != InputName { |
| 80 | + return nil, errors.Wrap(modules.ErrUnknownInput, name) |
| 81 | + } |
| 82 | + return s.input, nil |
| 83 | +} |
| 84 | + |
| 85 | +// AttachTo - |
| 86 | +func (s *Module) AttachTo(name string, input *modules.Input) error { |
| 87 | + output, err := s.Output(name) |
| 88 | + if err != nil { |
| 89 | + return err |
| 90 | + } |
| 91 | + |
| 92 | + output.Attach(input) |
| 93 | + return nil |
| 94 | +} |
0 commit comments