|
| 1 | +package tm |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "github.com/gitopia/git-server/logger" |
| 7 | + "github.com/pkg/errors" |
| 8 | + "github.com/spf13/viper" |
| 9 | + "github.com/tendermint/tendermint/rpc/jsonrpc/client" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + TM_WS_ENDPOINT = "/websocket" |
| 14 | +) |
| 15 | + |
| 16 | +type Client struct { |
| 17 | + c *client.WSClient |
| 18 | +} |
| 19 | + |
| 20 | +type evenHandlerFunc func(context.Context, []byte) error |
| 21 | + |
| 22 | +func NewTmClient() (*Client, error) { |
| 23 | + wsc, err := client.NewWS(viper.GetString("tm_addr"), TM_WS_ENDPOINT) |
| 24 | + if err != nil { |
| 25 | + return nil, errors.Wrap(err, "error creating ws client") |
| 26 | + } |
| 27 | + err = wsc.Start() |
| 28 | + if err != nil { |
| 29 | + return nil, errors.Wrap(err, "error connecting to WS") |
| 30 | + } |
| 31 | + return &Client{ |
| 32 | + c: wsc, |
| 33 | + }, nil |
| 34 | +} |
| 35 | + |
| 36 | +// processes events from tm |
| 37 | +// returns error on failure |
| 38 | +// returns error when event handler returns error |
| 39 | +func (c Client) Subscribe(ctx context.Context, q string, h evenHandlerFunc) (<-chan struct{}, chan error) { |
| 40 | + e := make(chan error) |
| 41 | + ctx, cancel := context.WithCancel(ctx) |
| 42 | + go func() { |
| 43 | + defer cancel() |
| 44 | + err := c.c.Subscribe(ctx, q) |
| 45 | + if err != nil { |
| 46 | + e <- errors.Wrap(err, "error sending subscribe request") |
| 47 | + return |
| 48 | + } |
| 49 | + for { |
| 50 | + event := <-c.c.ResponsesCh |
| 51 | + if event.Error != nil { |
| 52 | + e <- errors.Wrap(err, "error reading from ws") |
| 53 | + return |
| 54 | + } |
| 55 | + |
| 56 | + jsonBuf, err := event.Result.MarshalJSON() |
| 57 | + if err != nil { |
| 58 | + e <- errors.Wrap(err, "error parsing result") |
| 59 | + return |
| 60 | + } |
| 61 | + // hack: TM sends empty event to begin with. skipping |
| 62 | + if string(jsonBuf) == "{}" { |
| 63 | + logger.FromContext(ctx).Info("received empty event. continuing...") |
| 64 | + continue |
| 65 | + } |
| 66 | + err = h(ctx, jsonBuf) |
| 67 | + if err != nil { |
| 68 | + logger.FromContext(ctx).Error(errors.WithMessage(err, "error from event handler")) |
| 69 | + } |
| 70 | + } |
| 71 | + }() |
| 72 | + return ctx.Done(), e |
| 73 | +} |
0 commit comments