|
| 1 | +package printer |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "sync" |
| 7 | + |
| 8 | + "github.com/dipdup-net/indexer-sdk/pkg/modules" |
| 9 | + "github.com/pkg/errors" |
| 10 | + "github.com/rs/zerolog/log" |
| 11 | +) |
| 12 | + |
| 13 | +// input name |
| 14 | +const ( |
| 15 | + InputName = "input" |
| 16 | +) |
| 17 | + |
| 18 | +// Printer - the structure which is responsible for print received messages |
| 19 | +type Printer struct { |
| 20 | + input *modules.Input |
| 21 | + |
| 22 | + wg *sync.WaitGroup |
| 23 | +} |
| 24 | + |
| 25 | +// NewPrinter - constructor of printer structure |
| 26 | +func NewPrinter() *Printer { |
| 27 | + return &Printer{ |
| 28 | + input: modules.NewInput(InputName), |
| 29 | + |
| 30 | + wg: new(sync.WaitGroup), |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +// Name - |
| 35 | +func (printer *Printer) Name() string { |
| 36 | + return "printer" |
| 37 | +} |
| 38 | + |
| 39 | +// Input - returns input by name |
| 40 | +func (printer *Printer) Input(name string) (*modules.Input, error) { |
| 41 | + switch name { |
| 42 | + case InputName: |
| 43 | + return printer.input, nil |
| 44 | + default: |
| 45 | + return nil, errors.Wrap(modules.ErrUnknownInput, name) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// Output - returns output by name |
| 50 | +func (printer *Printer) Output(name string) (*modules.Output, error) { |
| 51 | + return nil, errors.Wrap(modules.ErrUnknownOutput, name) |
| 52 | +} |
| 53 | + |
| 54 | +// AttachTo - attach input to output with name |
| 55 | +func (printer *Printer) AttachTo(name string, input *modules.Input) error { |
| 56 | + output, err := printer.Output(name) |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + output.Attach(input) |
| 61 | + return nil |
| 62 | +} |
| 63 | + |
| 64 | +// Close - gracefully stops module |
| 65 | +func (printer *Printer) Close() error { |
| 66 | + printer.wg.Wait() |
| 67 | + |
| 68 | + if err := printer.input.Close(); err != nil { |
| 69 | + return err |
| 70 | + } |
| 71 | + |
| 72 | + return nil |
| 73 | +} |
| 74 | + |
| 75 | +// Start - starts module |
| 76 | +func (printer *Printer) Start(ctx context.Context) { |
| 77 | + printer.wg.Add(1) |
| 78 | + go printer.listen(ctx) |
| 79 | +} |
| 80 | + |
| 81 | +func (printer *Printer) listen(ctx context.Context) { |
| 82 | + defer printer.wg.Done() |
| 83 | + |
| 84 | + for { |
| 85 | + select { |
| 86 | + case <-ctx.Done(): |
| 87 | + return |
| 88 | + case msg, ok := <-printer.input.Listen(): |
| 89 | + if !ok { |
| 90 | + return |
| 91 | + } |
| 92 | + log.Info().Str("obj_type", fmt.Sprintf("%T", msg)).Msgf("%##v", msg) |
| 93 | + } |
| 94 | + } |
| 95 | +} |
0 commit comments