class Zold::Http

Http page

Constants

CONNECT_TIMEOUT

Connect timeout in seconds

NETWORK_HEADER

HTTP header we add, in order to inform the node about our network. This is done in order to isolate test networks from production one.

PROTOCOL_HEADER

HTTP header we add, in order to inform the node about our protocol.

READ_TIMEOUT

Read timeout in seconds

SCORE_HEADER

HTTP header we add to each HTTP request, in order to inform the other node about the score. If the score is big enough, the remote node will add us to its list of remote nodes.

VERSION_HEADER

HTTP header we add, in order to inform the node about our version. This is done mostly in order to let the other node reboot itself, if the version is higher.

Public Class Methods

new(uri:, score: Score::ZERO, network: 'test') click to toggle source
# File lib/zold/http.rb, line 102
def initialize(uri:, score: Score::ZERO, network: 'test')
  @uri = uri.is_a?(URI) ? uri : URI(uri)
  @score = score
  @network = network
end

Public Instance Methods

get(timeout: READ_TIMEOUT) click to toggle source
# File lib/zold/http.rb, line 108
def get(timeout: READ_TIMEOUT)
  HttpResponse.new(
    Typhoeus::Request.get(
      @uri,
      accept_encoding: 'gzip',
      headers: headers,
      connecttimeout: CONNECT_TIMEOUT,
      timeout: timeout
    )
  )
rescue StandardError => e
  HttpError.new(e)
end
get_file(file) click to toggle source
# File lib/zold/http.rb, line 122
def get_file(file)
  File.open(file, 'w') do |f|
    request = Typhoeus::Request.new(
      @uri,
      accept_encoding: 'gzip',
      headers: headers,
      connecttimeout: CONNECT_TIMEOUT
    )
    request.on_body do |chunk|
      f.write(chunk)
    end
    request.run
    response = new HttpResponse(request)
    raise "Invalid response code #{response.status}" unless response.status == 200
    response
  end
rescue StandardError => e
  HttpError.new(e)
end
put(file) click to toggle source
# File lib/zold/http.rb, line 142
def put(file)
  HttpResponse.new(
    Typhoeus::Request.put(
      @uri,
      accept_encoding: 'gzip',
      body: IO.read(file),
      headers: headers.merge(
        'Content-Type': 'text/plain'
      ),
      connecttimeout: CONNECT_TIMEOUT,
      timeout: 2 + File.size(file) * 0.01 / 1024
    )
  )
rescue StandardError => e
  HttpError.new(e)
end

Private Instance Methods

headers() click to toggle source
# File lib/zold/http.rb, line 161
def headers
  headers = {
    'User-Agent': "Zold #{VERSION}",
    'Connection': 'close',
    'Accept-Encoding': 'gzip'
  }
  headers[Http::VERSION_HEADER] = Zold::VERSION
  headers[Http::PROTOCOL_HEADER] = Zold::PROTOCOL.to_s
  headers[Http::NETWORK_HEADER] = @network
  headers[Http::SCORE_HEADER] = @score.reduced(4).to_s if @score.valid? && !@score.expired? && @score.value > 3
  headers
end