Class: Kobako::Transport::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/kobako/transport/response.rb

Overview

Value object for a single host-side Transport Response (docs/wire-codec.md Envelope Encoding → Response).

2-element msgpack array: [status, value-or-fault]. status is 0 (success) or 1 (fault). For success the second element is the return value; for fault it is a Fault (ext 0x02 envelope).

Built on the class X < Data.define(…) subclass form so the class body is fully Steep-visible; see lib/kobako/outcome/panic.rb for the rationale.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status:, payload:) ⇒ Response

Returns a new instance of Response.



48
49
50
51
52
53
54
55
56
57
# File 'lib/kobako/transport/response.rb', line 48

def initialize(status:, payload:)
  unless [STATUS_OK, STATUS_ERROR].include?(status)
    raise ArgumentError, "Response status must be 0 (ok) or 1 (error), got #{status.inspect}"
  end
  if status == STATUS_ERROR && !payload.is_a?(Kobako::Fault)
    raise ArgumentError, "Response with error status must carry a Kobako::Fault payload"
  end

  super
end

Class Method Details

.decode(bytes) ⇒ Object

Decode bytes into a Kobako::Transport::Response. Raises Codec::InvalidType when the envelope is not the expected 2-element msgpack array, or when the Value Object’s construction invariants reject the decoded fields.



37
38
39
40
41
42
43
44
45
46
# File 'lib/kobako/transport/response.rb', line 37

def self.decode(bytes)
  Codec::Decoder.decode(bytes) do |arr|
    unless arr.is_a?(Array) && arr.length == 2
      raise Codec::InvalidType, "Response envelope is malformed (expected a 2-element array)"
    end

    status, payload = arr
    new(status: status, payload: payload)
  end
end

.error(fault) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/kobako/transport/response.rb', line 26

def self.error(fault)
  unless fault.is_a?(Kobako::Fault)
    raise ArgumentError, "Response.error requires Kobako::Fault, got #{fault.class}"
  end

  new(status: STATUS_ERROR, payload: fault)
end

.ok(value) ⇒ Object



22
23
24
# File 'lib/kobako/transport/response.rb', line 22

def self.ok(value)
  new(status: STATUS_OK, payload: value)
end

Instance Method Details

#encodeObject

Encode this Response to msgpack bytes as the 2-element [status, payload] array.



64
65
66
# File 'lib/kobako/transport/response.rb', line 64

def encode
  Codec::Encoder.encode([status, payload])
end

#error?Boolean

Returns:

  • (Boolean)


60
# File 'lib/kobako/transport/response.rb', line 60

def error? = status == STATUS_ERROR

#ok?Boolean

Returns:

  • (Boolean)


59
# File 'lib/kobako/transport/response.rb', line 59

def ok?    = status == STATUS_OK