Class: Proc::Client

Inherits:
Http::Client
  • Object
show all
Defined in:
lib/proc/client.rb

Constant Summary collapse

DEFAULT_HEADERS =
{
  "content-type" => "application/json"
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(authorization, scheme: "https", host: "proc.dev") ⇒ Client



29
30
31
32
33
34
35
# File 'lib/proc/client.rb', line 29

def initialize(authorization, scheme: "https", host: "proc.dev")
  @authorization = authorization
  @scheme = scheme
  @host = host

  super()
end

Instance Method Details

#[](proc) ⇒ Object



37
38
39
# File 'lib/proc/client.rb', line 37

def [](proc)
  Callable.new(proc, client: self)
end

#compose(&block) ⇒ Object



41
42
43
# File 'lib/proc/client.rb', line 41

def compose(&block)
  Composition.new(client: self, &block)
end

#perform(proc, input, **arguments) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/proc/client.rb', line 49

def perform(proc, input, **arguments)
  Async(logger: NullLogger) { |task|
    body = {
      input: input, arguments: arguments
    }

    headers = {
      "authorization" => "Bearer #{@authorization}"
    }.merge(DEFAULT_HEADERS)

    begin
      response = call(:post, build_uri(proc), headers: headers, body: Oj.dump(body, mode: :json), task: task)

      payload = Oj.load(response.read, mode: :strict)
    rescue => error
      raise Proc::Unavailable, error.message
    ensure
      response&.close
    end

    case response.status
    when 200
      payload["value"]
    when 400
      raise Proc::ArgumentError, payload.dig("error", "message")
    when 403
      raise Proc::Unauthorized, payload.dig("error", "message")
    when 404
      raise Proc::Undefined, payload.dig("error", "message")
    when 500
      raise Proc::Error, payload.dig("error", "message")
    end
  }.wait
end