Files
libsam/pkg/shreder/shreder_client.go

91 lines
1.9 KiB
Go
Raw Normal View History

2025-12-26 11:34:45 +08:00
package shreder
2025-12-26 10:57:37 +08:00
import (
"context"
"github.com/samlior/libsam/pkg/logger"
"github.com/samlior/libsam/pkg/txparser"
"github.com/samlior/libsam/pkg/types"
"github.com/samlior/libsam/third_party/shreder_protos"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type ShrederClient struct {
log logger.Logger
2025-12-26 11:34:45 +08:00
conn *grpc.ClientConn
client shreder_protos.ShrederServiceClient
subscription map[string]*shreder_protos.SubscribeRequestFilterTransactions
2025-12-26 10:57:37 +08:00
}
2025-12-26 11:34:45 +08:00
func NewShrederClient(
logger logger.Logger,
url string,
subscription map[string]*shreder_protos.SubscribeRequestFilterTransactions,
) (*ShrederClient, func(), error) {
2025-12-26 10:57:37 +08:00
conn, err := grpc.NewClient(url, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, func() {}, err
}
s := &ShrederClient{
2025-12-26 11:34:45 +08:00
log: logger,
conn: conn,
client: shreder_protos.NewShrederServiceClient(conn),
subscription: subscription,
2025-12-26 10:57:37 +08:00
}
return s, func() {
s.Wait()
}, nil
}
func (c *ShrederClient) Wait() {
c.log.Debug("waiting for shreder client to stop")
err := c.conn.Close()
if err != nil {
c.log.Errorf("failed to close connection: %v", err)
}
c.log.Debug("shreder client stopped")
}
func (c *ShrederClient) ReadSync(ctx context.Context, txCh chan<- types.TxSignalBatch) error {
stream, err := c.client.SubscribeTransactions(ctx)
if err != nil {
return err
}
err = stream.Send(&shreder_protos.SubscribeTransactionsRequest{
2025-12-26 11:34:45 +08:00
Transactions: c.subscription,
2025-12-26 10:57:37 +08:00
})
if err != nil {
return err
}
for {
response, err := stream.Recv()
if err != nil {
return err
}
txBatch := txparser.ParseTransaction(response.Transaction)
if len(txBatch) == 0 {
continue
}
// set fixed source for tx signals
for _, tx := range txBatch {
tx.Source = "shreder"
}
select {
case <-ctx.Done():
return ctx.Err()
case txCh <- txBatch:
}
}
}