Module: Tempest::HTTP

Defined in:
lib/tempest/http.rb

Overview

JSON-over-HTTP transport for XRPC endpoints. Backed by Async::HTTP::Internet, which keeps connections alive per origin and reuses them across calls. The public interface stays synchronous (returns Response on call) by wrapping work in Sync so the REPL doesn’t need to know about Async.

Defined Under Namespace

Classes: Response

Class Method Summary collapse

Class Method Details

.get_json(url, headers: {}, query: nil) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/tempest/http.rb', line 34

def get_json(url, headers: {}, query: nil)
  uri = URI(url)
  if query && !query.empty?
    existing = uri.query ? URI.decode_www_form(uri.query) : []
    uri.query = URI.encode_www_form(existing + query.to_a)
  end
  request("GET", uri.to_s, headers: headers)
end

.internetObject



72
73
74
75
76
# File 'lib/tempest/http.rb', line 72

def internet
  @internet_mutex.synchronize do
    @internet ||= Async::HTTP::Internet.new
  end
end

.parse_body(response, body_str) ⇒ Object



65
66
67
68
69
70
# File 'lib/tempest/http.rb', line 65

def parse_body(response, body_str)
  return nil if body_str.empty?
  ctype = response.headers["content-type"].to_s
  return JSON.parse(body_str) if ctype.include?("application/json")
  body_str
end

.post_json(url, body: nil, headers: {}) ⇒ Object



30
31
32
# File 'lib/tempest/http.rb', line 30

def post_json(url, body: nil, headers: {})
  request("POST", url, body: body, headers: headers)
end

.request(method, url, body: nil, headers: {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tempest/http.rb', line 43

def request(method, url, body: nil, headers: {})
  normalized = headers.each_with_object({}) { |(k, v), h| h[k.to_s.downcase] = v }
  payload = nil
  if body
    normalized["content-type"] ||= "application/json"
    payload = [JSON.generate(body)]
  end
  normalized["accept"] ||= "application/json"

  header_pairs = normalized.to_a

  Sync do
    response = internet.call(method, url, header_pairs, payload)
    begin
      body_str = response.read.to_s
      Response.new(response.status, parse_body(response, body_str))
    ensure
      response.close
    end
  end
end

.reset!Object



78
79
80
81
82
83
84
85
86
# File 'lib/tempest/http.rb', line 78

def reset!
  @internet_mutex.synchronize do
    existing = @internet
    @internet = nil
    if existing
      Sync { existing.close }
    end
  end
end