Class: Barrister::BatchClient

Inherits:
Client
  • Object
show all
Defined in:
lib/barrister.rb

Overview

BatchClient acts like a Client and exposes the same proxy classes as a normal Client instance. However, none of the proxy function calls return values. Instead, they are stored in an Array until ‘batch.send()` is called.

Use a batch if you have many small requests that you’d like to send at once.

Note: the JSON-RPC spec indicates that servers may execute batch requests in parallel. Do not batch requests that depend on being sequentially executed.

Instance Attribute Summary

Attributes inherited from Client

#trans

Instance Method Summary collapse

Methods inherited from Client

#get_meta, #init_proxies, #load_contract, #request

Methods included from Barrister

contract_from_file, #err_resp, #ok_resp, parse_method, rand_str

Constructor Details

#initialize(parent, contract) ⇒ BatchClient

  • ‘parent` - the Client instance we were created from

  • ‘contract` - The contract associated with this Client. Used to init proxies.



476
477
478
479
480
481
# File 'lib/barrister.rb', line 476

def initialize(parent, contract)
  @parent   = parent
  @trans    = BatchTransport.new(self)
  @contract = contract
  init_proxies
end

Instance Method Details

#sendObject

Sends the batch of requests to the server.

Returns an Array of RpcResponse instances. The Array is ordered in the order of the requests made to the batch. Your code needs to check each element in the Array for errors.

  • Cannot be called more than once

  • Will raise RpcException if the batch is empty



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# File 'lib/barrister.rb', line 496

def send
  if @trans.sent
    raise "Batch has already been sent!"
  end
  @trans.sent = true

  requests = @trans.requests

  if requests.length < 1
    raise RpcException.new(-32600, "Batch cannot be empty")
  end

  # Send request batch to server
  resp_list = @parent.trans.request(requests)
  
  # Build a hash for the responses so we can re-order them
  # in request order.
  sorted    = [ ]
  by_req_id = { }
  resp_list.each do |resp|
    by_req_id[resp["id"]] = resp
  end

  # Iterate through the requests in the batch and assemble
  # the sorted result array
  requests.each do |req|
    id = req["id"]
    resp = by_req_id[id]
    if !resp
      msg = "No result for request id: #{id}"
      resp = { "id" => id, "error" => { "code"=>-32603, "message" => msg } }
    end
    sorted << RpcResponse.new(req, resp)
  end

  return sorted
end

#start_batchObject

Overrides start_batch and blows up if called



484
485
486
# File 'lib/barrister.rb', line 484

def start_batch
  raise "Cannot call start_batch on a batch!"
end