github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/bft/rpc/lib/client/batch/batch.go (about)

     1  package batch
     2  
     3  import (
     4  	"context"
     5  
     6  	types "github.com/gnolang/gno/tm2/pkg/bft/rpc/lib/types"
     7  )
     8  
     9  type Client interface {
    10  	SendBatch(context.Context, types.RPCRequests) (types.RPCResponses, error)
    11  }
    12  
    13  // Batch allows us to buffer multiple request/response structures
    14  // into a single batch request.
    15  // NOT thread safe
    16  type Batch struct {
    17  	client   Client
    18  	requests types.RPCRequests
    19  }
    20  
    21  // NewBatch creates a new batch object
    22  func NewBatch(client Client) *Batch {
    23  	return &Batch{
    24  		client:   client,
    25  		requests: make(types.RPCRequests, 0),
    26  	}
    27  }
    28  
    29  // Count returns the number of enqueued requests waiting to be sent
    30  func (b *Batch) Count() int {
    31  	return len(b.requests)
    32  }
    33  
    34  // Clear empties out the request batch
    35  func (b *Batch) Clear() int {
    36  	return b.clear()
    37  }
    38  
    39  func (b *Batch) clear() int {
    40  	count := len(b.requests)
    41  	b.requests = make(types.RPCRequests, 0)
    42  
    43  	return count
    44  }
    45  
    46  // Send will attempt to send the current batch of enqueued requests, and then
    47  // will clear out the requests once done
    48  func (b *Batch) Send(ctx context.Context) (types.RPCResponses, error) {
    49  	defer func() {
    50  		b.clear()
    51  	}()
    52  
    53  	responses, err := b.client.SendBatch(ctx, b.requests)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  
    58  	return responses, nil
    59  }
    60  
    61  // AddRequest adds a new request onto the batch
    62  func (b *Batch) AddRequest(request types.RPCRequest) {
    63  	b.requests = append(b.requests, request)
    64  }